Skip to content

access

mtp_access Documentation

A module to access Mobile Devices from Windows via USB connection.

Author: Heribert Füchtenhans

Version: 1.1.0

Implements access to basic functions of the Windows WPD API Yes I know, there are a lot of pylint disable and type ignors :-) For examples please look into the tests directory.

Requirements: OS: Windows 10 Python: comtypes

The module contains the following functions:

  • 'get_portable_devices' Get all attached portable devices.
  • 'get_content_from_device_path' - Get the content of a path.
  • 'walk' - Iterates ower all files in a tree.
  • 'makedirs' - Creates the directories on the MTP device if they don't exist.

The module contains the following classes:

  • 'PortableDeviceContent' - Class for one file, directory or storage
  • 'PortableDevice' - Class for one portable device found connected

Examples:

>>> import win_mtp.mtp_access
>>> win_mtp.mtp_access.get_portable_devices()
[<PortableDevice: ('HSG1316', 'HSG1316')>]

PortableDevice

Class with the infos for a connected portable device. The instanzes of this class will be created internaly. User should not instanciate them manually until you know what you do.

Public methods

get_description get_content

Public attributes:

Raises:

Type Description
COMError

If something went wrong

Source code in win_mtp\access.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
class PortableDevice:
    """Class with the infos for a connected portable device.
    The instanzes of this class will be created internaly. User should not instanciate them manually
    until you know what you do.

    Public methods:
        get_description
        get_content

    Public attributes:

    Exceptions:
        comtypes.COMError: If something went wrong
    """

    def __init__(self, p_id: str) -> None:
        """Init the class.

        Args:
            p_id: ID of the found device
        """
        self._p_id = p_id
        self._desc = ""
        self._name = ""
        self._device = None

    def get_description(self) -> Tuple[str, str]:
        """Get the name and the description of the device. If no description is available
        name and description will be identical.

        Returns:
            A tuple with of name, description

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> dev[0].get_description()
            ('HSG1316', 'HSG1316')
        """
        if self._name:
            return self._name, self._desc
        if DEVICE_MANAGER is None:
            return "", ""
        name_len = ctypes.pointer(ctypes.c_ulong(0))
        DEVICE_MANAGER.GetDeviceDescription(self._p_id, ctypes.POINTER(ctypes.c_ushort)(), name_len)
        name = ctypes.create_unicode_buffer(name_len.contents.value)
        DEVICE_MANAGER.GetDeviceDescription(
            self._p_id,
            ctypes.cast(name, ctypes.POINTER(ctypes.c_ushort)),
            name_len,
        )
        self._desc = name.value
        try:
            DEVICE_MANAGER.GetDeviceFriendlyName(
                self._p_id, ctypes.POINTER(ctypes.c_ushort)(), name_len
            )
            name = ctypes.create_unicode_buffer(name_len.contents.value)
            DEVICE_MANAGER.GetDeviceFriendlyName(
                self._p_id,
                ctypes.cast(name, ctypes.POINTER(ctypes.c_ushort)),
                name_len,
            )
            self._name = name.value
        except comtypes.COMError:
            self._name = self._desc
            try:
                propvalues = self._get_device().Content().properties().GetValues("DEVICE", None)
                self._name = propvalues.GetStringValue(WPD_OBJECT_NAME)
            except comtypes.COMError:
                self._name = self._desc
        # WPD_DEVICE_SERIAL_NUMBER
        return self._name, self._desc

    def _get_device(self) -> Any:
        """Open a device"""
        if self._device:
            return self._device
        client_information = comtypes.client.CreateObject(
            types.PortableDeviceValues,  # pylint: disable=no-member  # type: ignore
            clsctx=comtypes.CLSCTX_INPROC_SERVER,
            interface=port.IPortableDeviceValues,  # pylint: disable=no-member  # type: ignore
        )
        self._device = comtypes.client.CreateObject(
            port.PortableDevice,  # pylint: disable=no-member  # type: ignore
            clsctx=comtypes.CLSCTX_INPROC_SERVER,
            interface=port.IPortableDevice,  # pylint: disable=no-member  # type: ignore
        )
        if self._device is not None:
            self._device.Open(self._p_id, client_information)  # type: ignore
        return self._device

    def get_content(self) -> PortableDeviceContent:
        """Get the content of a device.

        Returns:
            An instance of PortableDeviceContent

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> str(dev[0].get_content())[:33]
            '<PortableDeviceContent c_wchar_p('
        """
        return PortableDeviceContent(ctypes.c_wchar_p("DEVICE"), self._get_device().Content(), None)

    def __repr__(self) -> str:
        return f"<PortableDevice: {self.get_description()}>"

__init__(p_id)

Init the class.

Parameters:

Name Type Description Default
p_id str

ID of the found device

required
Source code in win_mtp\access.py
698
699
700
701
702
703
704
705
706
707
def __init__(self, p_id: str) -> None:
    """Init the class.

    Args:
        p_id: ID of the found device
    """
    self._p_id = p_id
    self._desc = ""
    self._name = ""
    self._device = None

get_content()

Get the content of a device.

Returns:

Type Description
PortableDeviceContent

An instance of PortableDeviceContent

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> str(dev[0].get_content())[:33]
'<PortableDeviceContent c_wchar_p('
Source code in win_mtp\access.py
774
775
776
777
778
779
780
781
782
783
784
785
786
def get_content(self) -> PortableDeviceContent:
    """Get the content of a device.

    Returns:
        An instance of PortableDeviceContent

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> str(dev[0].get_content())[:33]
        '<PortableDeviceContent c_wchar_p('
    """
    return PortableDeviceContent(ctypes.c_wchar_p("DEVICE"), self._get_device().Content(), None)

get_description()

Get the name and the description of the device. If no description is available name and description will be identical.

Returns:

Type Description
Tuple[str, str]

A tuple with of name, description

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> dev[0].get_description()
('HSG1316', 'HSG1316')
Source code in win_mtp\access.py
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
def get_description(self) -> Tuple[str, str]:
    """Get the name and the description of the device. If no description is available
    name and description will be identical.

    Returns:
        A tuple with of name, description

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> dev[0].get_description()
        ('HSG1316', 'HSG1316')
    """
    if self._name:
        return self._name, self._desc
    if DEVICE_MANAGER is None:
        return "", ""
    name_len = ctypes.pointer(ctypes.c_ulong(0))
    DEVICE_MANAGER.GetDeviceDescription(self._p_id, ctypes.POINTER(ctypes.c_ushort)(), name_len)
    name = ctypes.create_unicode_buffer(name_len.contents.value)
    DEVICE_MANAGER.GetDeviceDescription(
        self._p_id,
        ctypes.cast(name, ctypes.POINTER(ctypes.c_ushort)),
        name_len,
    )
    self._desc = name.value
    try:
        DEVICE_MANAGER.GetDeviceFriendlyName(
            self._p_id, ctypes.POINTER(ctypes.c_ushort)(), name_len
        )
        name = ctypes.create_unicode_buffer(name_len.contents.value)
        DEVICE_MANAGER.GetDeviceFriendlyName(
            self._p_id,
            ctypes.cast(name, ctypes.POINTER(ctypes.c_ushort)),
            name_len,
        )
        self._name = name.value
    except comtypes.COMError:
        self._name = self._desc
        try:
            propvalues = self._get_device().Content().properties().GetValues("DEVICE", None)
            self._name = propvalues.GetStringValue(WPD_OBJECT_NAME)
        except comtypes.COMError:
            self._name = self._desc
    # WPD_DEVICE_SERIAL_NUMBER
    return self._name, self._desc

PortableDeviceContent

Class for one file, directory or storage with it's properties. This class is only internaly created, use it only to read the properties

Parameters:

Name Type Description Default
object_id Any

MTP object id.

required
content PortableDeviceContent

interface to IPortableDeviceContent.

required
properties Optional[Any]

The interface that is required to get or set properties on an object on the device.

None
Public methods

get_properties get_children get_child get_path create_content upload_stream upload_file download_stream download_file remove

Public attributes

name: Name on the MTP device fullname: The full path name date_created: The file date size: The size of the file in bytes content_type: Type of the entry. One of the WPD_CONTENT_TYPE_ constants

Raises:

Type Description
COMError

If something went wrong

Source code in win_mtp\access.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
class PortableDeviceContent:  # pylint: disable=too-many-instance-attributes
    """Class for one file, directory or storage with it's properties.
    This class is only internaly created, use it only to read the properties

    Args:
        object_id: MTP object id.
        content: interface to IPortableDeviceContent.
        properties: The interface that is required to get or set properties on an object on
                    the device.

    Public methods:
        get_properties
        get_children
        get_child
        get_path
        create_content
        upload_stream
        upload_file
        download_stream
        download_file
        remove

    Public attributes:
        name: Name on the MTP device
        fullname: The full path name
        date_created: The file date
        size: The size of the file in bytes
        content_type: Type of the entry. One of the WPD_CONTENT_TYPE_ constants

    Exceptions:
        comtypes.COMError: If something went wrong
    """

    # class variable
    _properties_to_read: Optional[
        types.PortableDeviceKeyCollection  # pylint: disable=no-member # type: ignore
    ] = None

    _CoTaskMemFree = ctypes.windll.ole32.CoTaskMemFree
    _CoTaskMemFree.restype = None
    _CoTaskMemFree.argtypes = [ctypes.c_void_p]

    def __init__(
        self,
        object_id: Any,
        content: "PortableDeviceContent",
        properties: Optional[Any] = None,
    ) -> None:
        """ """

        self._object_id = object_id
        self._content = content
        self.name = ""
        self._plain_name = ""
        self.content_type = WPD_CONTENT_TYPE_UNDEFINED
        self.full_filename = ""
        self.size = -1
        self.date_created = datetime.datetime(1970, 1, 1)
        self._capacity = -1
        self._free_capacity = -1
        self._serialnumber = ""
        self._properties = properties or content.properties()  # type: ignore
        if PortableDeviceContent._properties_to_read is None:
            # We havn't set the roperties wie will read, so do it now
            PortableDeviceContent._properties_to_read = comtypes.client.CreateObject(
                types.PortableDeviceKeyCollection,  # pylint: disable=no-member, protected-access # type: ignore
                clsctx=comtypes.CLSCTX_INPROC_SERVER,  # pylint: disable=no-member, protected-access
                interface=port.IPortableDeviceKeyCollection,  # pylint: disable=no-member, protected-access # type: ignore
            )
            PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_NAME)  # type: ignore
            PortableDeviceContent._properties_to_read.Add(  # type: ignore
                WPD_OBJECT_ORIGINAL_FILE_NAME
            )
            PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_CONTENT_TYPE)  # type: ignore
            PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_SIZE)  # type: ignore
            PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_DATE_MODIFIED)  # type: ignore
            PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_DATE_CREATED)  # type: ignore
            PortableDeviceContent._properties_to_read.Add(WPD_STORAGE_CAPACITY)  # type: ignore
            PortableDeviceContent._properties_to_read.Add(  # type: ignore
                WPD_STORAGE_FREE_SPACE_IN_BYTES
            )
            PortableDeviceContent._properties_to_read.Add(WPD_DEVICE_SERIAL_NUMBER)  # type: ignore
        self.get_properties()

    def get_properties(
        self,
    ) -> Tuple[str, int, int, datetime.datetime, int, int, str]:
        """Get the properties of this content.

        Returns:
            name: The name for this content, normaly the file or directory name
            content_type: One of the content type values that descripe the type of the content
                        WPD_CONTENT_TYPE_UNDEFINED, WPD_CONTENT_TYPE_STORAGE,
                        WPD_CONTENT_TYPE_DIRECTORY, WPD_CONTENT_TYPE_FILE, WPD_CONTENT_TYPE_DEVICE
            size: The size of the file or 0 if content ist not a file
            date_created: The reation date of the file or directory
            capacity: The capacity of the storage, only valid if content_type is
                        WPD_CONTENT_TYPE_STORAGE
            free_capacity: The free capacity of the storage, only valid if content_type is
                        WPD_CONTENT_TYPE_STORAGE
            serialnumber: The serial number of the device, only valid if content_type is
                        WPD_CONTENT_TYPE_DEVICE

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> cont = dev[0].get_content()
            >>> cont.get_properties()
            ('HSG1316', 0, -1, datetime.datetime(1970, 1, 1, 0, 0), -1, -1, 'DQVSSCM799999999')
        """
        if self._plain_name:
            return (
                self.name,
                self.content_type,
                self.size,
                self.date_created,
                self._capacity,
                self._free_capacity,
                self._serialnumber,
            )
        if self._object_id is None:
            return (
                "",
                WPD_CONTENT_TYPE_UNDEFINED,
                -1,
                self.date_created,
                self._capacity,
                self._free_capacity,
                self._serialnumber,
            )
        propvalues = self._properties.GetValues(
            self._object_id, PortableDeviceContent._properties_to_read
        )
        self.content_type = WPD_CONTENT_TYPE_UNDEFINED
        try:
            self._plain_name = propvalues.GetStringValue(WPD_OBJECT_NAME)
        except comtypes.COMError:
            self.content_type = WPD_CONTENT_TYPE_DIRECTORY
            self.name = self._plain_name = ""
        try:
            self.name = self._plain_name = propvalues.GetStringValue(WPD_OBJECT_ORIGINAL_FILE_NAME)
        except comtypes.COMError:
            self.name = self._plain_name
        content_id = str(propvalues.GetGuidValue(WPD_OBJECT_CONTENT_TYPE))
        if content_id in {
            "{23F05BBC-15DE-4C2A-A55B-A9AF5CE412EF}",
            "{99ED0160-17FF-4C44-9D98-1D7A6F941921}",
        }:
            # It's a storage
            try:
                self._capacity = int(propvalues.GetUnsignedLargeIntegerValue(WPD_STORAGE_CAPACITY))
            except comtypes.COMError:
                self._capacity = -1
            try:
                self._free_capacity = int(
                    propvalues.GetUnsignedLargeIntegerValue(WPD_STORAGE_FREE_SPACE_IN_BYTES)
                )
            except comtypes.COMError:
                self._free_capacity = -1
            with contextlib.suppress(comtypes.COMError):
                self._serialnumber = propvalues.GetStringValue(WPD_DEVICE_SERIAL_NUMBER)
            self.content_type = WPD_CONTENT_TYPE_STORAGE
        elif content_id == "{27E2E392-A111-48E0-AB0C-E17705A05F85}":
            # It's a directory
            self.content_type = WPD_CONTENT_TYPE_DIRECTORY
        else:
            # it's not a folder or storage
            self.content_type = WPD_CONTENT_TYPE_FILE
            self.size = int(propvalues.GetUnsignedLargeIntegerValue(WPD_OBJECT_SIZE))
            filetime = propvalues.GetValue(WPD_OBJECT_DATE_MODIFIED).data.date
            days_since_1970 = (
                int(filetime)
                - (datetime.datetime(1970, 1, 1) - datetime.datetime(1899, 12, 30)).days
            )
            hours = (filetime - int(filetime)) * 24
            minutes = (hours - int(hours)) * 60
            seconds = (minutes - int(minutes)) * 60
            milliseconds = round((seconds - int(seconds)) * 1000)
            self.date_created = datetime.datetime(1970, 1, 1) + datetime.timedelta(
                days=days_since_1970,
                hours=int(hours),
                minutes=int(minutes),
                seconds=int(seconds),
                milliseconds=milliseconds,
            )
        propvalues.Clear()
        return (
            self.name,
            self.content_type,
            self.size,
            self.date_created,
            self._capacity,
            self._free_capacity,
            self._serialnumber,
        )

    def get_children(self) -> list["PortableDeviceContent"]:
        """Get the child items of a folder.

        Returns:
            A list of PortableDeviceContent instances each representing a child entry.

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> cont = dev[0].get_content()
            >>> str(cont.get_children()[0])[:58]
            "<PortableDeviceContent s10001: ('Interner Speicher', 0, -1"
        """
        ret_objs = []
        enumobject_ids = self._content.EnumObjects(  # type: ignore
            ctypes.c_ulong(0),
            self._object_id,
            ctypes.POINTER(
                port.IPortableDeviceValues  # pylint: disable=no-member # type: ignore
            )(),
        )
        while True:
            num_objects = ctypes.c_ulong(16)  # block size, so to speak
            object_id_array = (ctypes.c_wchar_p * num_objects.value)()
            num_fetched = ctypes.pointer(ctypes.c_ulong(0))
            # be sure to change the IEnumPortableDeviceobject_ids 'Next'
            # function in the generated code to have object_ids as inout
            enumobject_ids.Next(
                num_objects,
                ctypes.cast(object_id_array, ctypes.POINTER(ctypes.c_wchar_p)),
                num_fetched,
            )
            if num_fetched.contents.value == 0:
                break
            for index in range(num_fetched.contents.value):
                curobject_id = object_id_array[index]
                value = PortableDeviceContent(curobject_id, self._content, self._properties)
                ret_objs.append(value)
                # Free memory
                address = (
                    ctypes.addressof(object_id_array) + ctypes.sizeof(ctypes.c_wchar_p) * index
                )
                ptr = ctypes.pointer(ctypes.c_wchar_p.from_address(address))
                ctypes.windll.ole32.CoTaskMemFree(ptr.contents)
        ret_objs.sort(key=lambda entry: entry.date_created)
        return ret_objs

    def get_child(self, name: str) -> Optional["PortableDeviceContent"]:
        """Returns a PortableDeviceContent for one child whos name is known.
        The search is case sensitive.

        Args:
            name: The name of the file or directory to search

        Returns:
            The PortableDeviceContent instance of the child or None if the child could not be
            found.

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> cont = dev[0].get_content()
            >>> str(cont.get_child("Interner Speicher"))[:58]
            "<PortableDeviceContent s10001: ('Interner Speicher', 0, -1"
        """
        matches = [c for c in self.get_children() if c.name == name]
        return matches[0] if matches else None

    def get_path(self, path: str) -> Optional["PortableDeviceContent"]:
        """Returns a PortableDeviceContent for a child whos path in the tree is known

        Args:
            path: The pathname to the child. Each path entry must be separated by the
                    os.path.sep character.

        Returns:
            The PortableDeviceContent instance of the child or None if the child could not be
            found.

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> cont = dev[0].get_content()
            >>> str(cont.get_path("Interner Speicher\\Android\\data"))[:41]
            "<PortableDeviceContent oE: ('data', 1, -1"
        """
        cur: Optional["PortableDeviceContent"] = self
        for part in path.split(os.path.sep):
            if not cur:
                return None
            cur = cur.get_child(part)
        return cur

    def __repr__(self) -> str:
        """ """
        return f"<PortableDeviceContent {self._object_id}: {self.get_properties()}>"

    def create_content(self, dirname: str) -> None:
        """Creates an empty directory content in this content.

        Args:
            dirname: Name of the directory that shall be created

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> cont = dev[0].get_content()
            >>> mycont = cont.get_path("Interner Speicher\\Music\\MyMusic")
            >>> if mycont: _ = mycont.remove()
            >>> cont = cont.get_path("Interner Speicher\\Music")
            >>> cont.create_content("MyMusic")
        """
        object_properties = comtypes.client.CreateObject(
            types.PortableDeviceValues,  # pylint: disable=no-member # type: ignore
            clsctx=comtypes.CLSCTX_INPROC_SERVER,
            interface=port.IPortableDeviceValues,  # pylint: disable=no-member # type: ignore
        )
        object_properties.SetStringValue(WPD_OBJECT_PARENT_ID, self._object_id)  # type: ignore
        object_properties.SetStringValue(WPD_OBJECT_NAME, dirname)  # type: ignore
        object_properties.SetStringValue(WPD_OBJECT_ORIGINAL_FILE_NAME, dirname)  # type: ignore
        object_properties.SetGuidValue(  # type: ignore
            WPD_OBJECT_CONTENT_TYPE, WPD_CONTENT_TYPE_FOLDER_GUID
        )
        self._content.CreateObjectWithPropertiesOnly(  # type: ignore
            object_properties, ctypes.POINTER(ctypes.c_wchar_p)()
        )

    def upload_stream(self, filename: str, inputstream: Any, stream_len: int) -> None:
        """Upload a steam to a file on the MTP device.
        For an easier usage use upload_file

        Args:
            filename: Name of the new file on the MTP device
            inputstream: open python file
            stream_len: length of the file to upload

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> cont = dev[0].get_content()
            >>> mycont = cont.get_path("Interner Speicher\\Music\\Test.mp3")
            >>> if mycont: _ = mycont.remove()
            >>> cont = cont.get_path("Interner Speicher\\Music")
            >>> name = '..\\..\\Tests\\OnFire.mp3'
            >>> size = os.path.getsize(name)
            >>> inp = open(name, "rb")
            >>> cont.upload_stream("Test.mp3", inp, size)
            >>> inp.close()
        """
        object_properties = comtypes.client.CreateObject(
            types.PortableDeviceValues,  # pylint: disable=no-member # type: ignore
            clsctx=comtypes.CLSCTX_INPROC_SERVER,
            interface=port.IPortableDeviceValues,  # pylint: disable=no-member # type: ignore
        )
        object_properties.SetStringValue(WPD_OBJECT_PARENT_ID, self._object_id)  # type: ignore
        object_properties.SetUnsignedLargeIntegerValue(WPD_OBJECT_SIZE, stream_len)  # type: ignore
        object_properties.SetStringValue(WPD_OBJECT_ORIGINAL_FILE_NAME, filename)  # type: ignore
        object_properties.SetStringValue(WPD_OBJECT_NAME, filename)  # type: ignore
        optimal_transfer_size_bytes = ctypes.pointer(ctypes.c_ulong(0))
        p_filestream = ctypes.POINTER(port.IStream)()  # pylint: disable=no-member # type: ignore
        # be sure to change the IPortableDeviceContent
        # 'CreateObjectWithPropertiesAndData' function in the generated code to
        # have IStream ppData as 'in','out'
        filestream, _, _ = self._content.CreateObjectWithPropertiesAndData(  # type: ignore
            object_properties,
            p_filestream,
            optimal_transfer_size_bytes,
            ctypes.POINTER(ctypes.c_wchar_p)(),
        )
        # filestream = filestream.value
        blocksize = optimal_transfer_size_bytes.contents.value
        cur_written = 0
        while True:
            to_read = stream_len - cur_written
            block = inputstream.read(to_read if to_read < blocksize else blocksize)
            if len(block) <= 0:
                break
            string_buf = ctypes.create_string_buffer(block)
            written = filestream.RemoteWrite(
                ctypes.cast(string_buf, ctypes.POINTER(ctypes.c_ubyte)),
                len(block),
            )
            cur_written += written
            if cur_written >= stream_len:
                break
        stgc_default = 0
        filestream.Commit(stgc_default)

    def upload_file(self, filename: str, inputfilename: str) -> None:
        """Upload of a file to MTP device.

        Args:
            filename: Name of the new file on the MTP device
            inputfilename: Name of the file that shall be uploaded

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> cont = dev[0].get_content()
            >>> mycont = cont.get_path("Interner Speicher\\Music\\Test.mp3")
            >>> if mycont: _ = mycont.remove()
            >>> cont = cont.get_path("Interner Speicher\\Music")
            >>> name = '..\\..\\Tests\\OnFire.mp3'
            >>> cont.upload_file("Test.mp3", name)
        """
        length = os.path.getsize(inputfilename)
        with open(inputfilename, "rb") as input_stream:
            self.upload_stream(filename, input_stream, length)

    def download_stream(self, outputstream: Any) -> None:
        """Download a file from MTP device.
        The used ProtableDeviceContent instance must be a file!
        For easier usage use download_file

        Args:
            outputstream: Open python file for writing

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> cont = dev[0].get_content()
            >>> cont = cont.get_path("Interner Speicher\\Ringtones\\hangouts_incoming_call.ogg")
            >>> name = '..\\..\\Tests\\hangouts_incoming_call.ogg'
            >>> outp = open(name, "wb")
            >>> cont.download_stream(outp)
            >>> outp.close()
        """
        try:
            resources = self._content.Transfer()  # type: ignore
            stgm_read = ctypes.c_uint(0)
            optimal_transfer_size_bytes = ctypes.pointer(ctypes.c_ulong(0))
            p_filestream = ctypes.POINTER(
                port.IStream  # pylint: disable=no-member # type: ignore
            )()
            optimal_transfer_size_bytes, q_filestream = resources.GetStream(
                self._object_id,
                WPD_RESOURCE_DEFAULT,
                stgm_read,
                optimal_transfer_size_bytes,
                p_filestream,
            )
            blocksize = optimal_transfer_size_bytes.contents.value
            filestream = q_filestream.value
            buf = (ctypes.c_ubyte * blocksize)()
            # make sure all RemoteRead parameters are in
            while True:
                buf, length = filestream.RemoteRead(buf, ctypes.c_ulong(blocksize))
                if length == 0:
                    break
                outputstream.write(bytearray(buf[:length]))
        except comtypes.COMError as err:
            raise IOError from err

    def download_file(self, outputfilename: str) -> None:
        """Download of a file from MTP device
        The used ProtableDeviceContent instance must be a file!

        Args:
            outputfilename: Name of the file the MTP file shall be written to. Any existing
                            content will be replaced.

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> cont = dev[0].get_content()
            >>> cont = cont.get_path("Interner Speicher\\Ringtones\\hangouts_incoming_call.ogg")
            >>> name = '..\\..\\Tests\\hangouts_incoming_call.ogg'
            >>> cont.download_file(name)
        """
        with open(outputfilename, "wb") as output_stream:
            self.download_stream(output_stream)

    def remove(self) -> int:
        """Deletes the current directory or file.

        Return:
            0 on OK, else a windows errorcode

        Examples:
            >>> import win_mtp.mtp_access
            >>> dev = win_mtp.mtp_access.get_portable_devices()
            >>> cont = dev[0].get_content()
            >>> mycont = cont.get_path("Interner Speicher\\Music\\Test.mp3")
            >>> if mycont: _ = mycont.remove()
            >>> cont = cont.get_path("Interner Speicher\\Music")
            >>> name = '..\\..\\Tests\\OnFire.mp3'
            >>> cont.upload_file("Test.mp3", name)
            >>> cont = dev[0].get_content()
            >>> mycont = cont.get_path("Interner Speicher\\Music\\Test.mp3")
            >>> mycont.remove()
            0
        """
        objects_to_delete = comtypes.client.CreateObject(
            types.PortableDevicePropVariantCollection,  # pylint: disable=no-member, protected-access # type: ignore
            clsctx=comtypes.CLSCTX_INPROC_SERVER,  # pylint: disable=no-member, protected-access
            interface=port.IPortableDevicePropVariantCollection,  # pylint: disable=no-member, protected-access # type: ignore
        )
        pvar = port.tag_inner_PROPVARIANT()  # pylint: disable=no-member # type: ignore
        pvar.vt = comtypes.automation.VT_LPWSTR
        pvar.data.pwszVal = ctypes.c_wchar_p(self._object_id)
        objects_to_delete.Add(pvar)  # type: ignore
        errors = comtypes.client.CreateObject(
            types.PortableDevicePropVariantCollection,  # pylint: disable=no-member, protected-access # type: ignore
            clsctx=comtypes.CLSCTX_INPROC_SERVER,  # pylint: disable=no-member, protected-access
            interface=port.IPortableDevicePropVariantCollection,  # pylint: disable=no-member, protected-access # type: ignore
        )
        try:
            self._content.Delete(  # type: ignore
                WPD_DELETE_WITH_RECURSION, objects_to_delete, errors
            )
        except comtypes.COMError:
            return 777
        count = ctypes.c_ulong()
        errors.GetCount(ctypes.pointer(count))  # type: ignore
        for i in range(count.value):
            index = ctypes.c_ulong(i)
            pvar = port.tag_inner_PROPVARIANT()  # pylint: disable=no-member # type: ignore
            errors.GetAt(index, ctypes.pointer(pvar))  # type: ignore
            if pvar.data.uintVal != 0:
                return pvar.data.uintVal
        return 0

__init__(object_id, content, properties=None)

Source code in win_mtp\access.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def __init__(
    self,
    object_id: Any,
    content: "PortableDeviceContent",
    properties: Optional[Any] = None,
) -> None:
    """ """

    self._object_id = object_id
    self._content = content
    self.name = ""
    self._plain_name = ""
    self.content_type = WPD_CONTENT_TYPE_UNDEFINED
    self.full_filename = ""
    self.size = -1
    self.date_created = datetime.datetime(1970, 1, 1)
    self._capacity = -1
    self._free_capacity = -1
    self._serialnumber = ""
    self._properties = properties or content.properties()  # type: ignore
    if PortableDeviceContent._properties_to_read is None:
        # We havn't set the roperties wie will read, so do it now
        PortableDeviceContent._properties_to_read = comtypes.client.CreateObject(
            types.PortableDeviceKeyCollection,  # pylint: disable=no-member, protected-access # type: ignore
            clsctx=comtypes.CLSCTX_INPROC_SERVER,  # pylint: disable=no-member, protected-access
            interface=port.IPortableDeviceKeyCollection,  # pylint: disable=no-member, protected-access # type: ignore
        )
        PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_NAME)  # type: ignore
        PortableDeviceContent._properties_to_read.Add(  # type: ignore
            WPD_OBJECT_ORIGINAL_FILE_NAME
        )
        PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_CONTENT_TYPE)  # type: ignore
        PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_SIZE)  # type: ignore
        PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_DATE_MODIFIED)  # type: ignore
        PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_DATE_CREATED)  # type: ignore
        PortableDeviceContent._properties_to_read.Add(WPD_STORAGE_CAPACITY)  # type: ignore
        PortableDeviceContent._properties_to_read.Add(  # type: ignore
            WPD_STORAGE_FREE_SPACE_IN_BYTES
        )
        PortableDeviceContent._properties_to_read.Add(WPD_DEVICE_SERIAL_NUMBER)  # type: ignore
    self.get_properties()

__repr__()

Source code in win_mtp\access.py
449
450
451
def __repr__(self) -> str:
    """ """
    return f"<PortableDeviceContent {self._object_id}: {self.get_properties()}>"

create_content(dirname)

Creates an empty directory content in this content.

Parameters:

Name Type Description Default
dirname str

Name of the directory that shall be created

required

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> cont = dev[0].get_content()
>>> mycont = cont.get_path("Interner Speicher\Music\MyMusic")
>>> if mycont: _ = mycont.remove()
>>> cont = cont.get_path("Interner Speicher\Music")
>>> cont.create_content("MyMusic")
Source code in win_mtp\access.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
def create_content(self, dirname: str) -> None:
    """Creates an empty directory content in this content.

    Args:
        dirname: Name of the directory that shall be created

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> cont = dev[0].get_content()
        >>> mycont = cont.get_path("Interner Speicher\\Music\\MyMusic")
        >>> if mycont: _ = mycont.remove()
        >>> cont = cont.get_path("Interner Speicher\\Music")
        >>> cont.create_content("MyMusic")
    """
    object_properties = comtypes.client.CreateObject(
        types.PortableDeviceValues,  # pylint: disable=no-member # type: ignore
        clsctx=comtypes.CLSCTX_INPROC_SERVER,
        interface=port.IPortableDeviceValues,  # pylint: disable=no-member # type: ignore
    )
    object_properties.SetStringValue(WPD_OBJECT_PARENT_ID, self._object_id)  # type: ignore
    object_properties.SetStringValue(WPD_OBJECT_NAME, dirname)  # type: ignore
    object_properties.SetStringValue(WPD_OBJECT_ORIGINAL_FILE_NAME, dirname)  # type: ignore
    object_properties.SetGuidValue(  # type: ignore
        WPD_OBJECT_CONTENT_TYPE, WPD_CONTENT_TYPE_FOLDER_GUID
    )
    self._content.CreateObjectWithPropertiesOnly(  # type: ignore
        object_properties, ctypes.POINTER(ctypes.c_wchar_p)()
    )

download_file(outputfilename)

Download of a file from MTP device The used ProtableDeviceContent instance must be a file!

Parameters:

Name Type Description Default
outputfilename str

Name of the file the MTP file shall be written to. Any existing content will be replaced.

required

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> cont = dev[0].get_content()
>>> cont = cont.get_path("Interner Speicher\Ringtones\hangouts_incoming_call.ogg")
>>> name = '..\..\Tests\hangouts_incoming_call.ogg'
>>> cont.download_file(name)
Source code in win_mtp\access.py
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
def download_file(self, outputfilename: str) -> None:
    """Download of a file from MTP device
    The used ProtableDeviceContent instance must be a file!

    Args:
        outputfilename: Name of the file the MTP file shall be written to. Any existing
                        content will be replaced.

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> cont = dev[0].get_content()
        >>> cont = cont.get_path("Interner Speicher\\Ringtones\\hangouts_incoming_call.ogg")
        >>> name = '..\\..\\Tests\\hangouts_incoming_call.ogg'
        >>> cont.download_file(name)
    """
    with open(outputfilename, "wb") as output_stream:
        self.download_stream(output_stream)

download_stream(outputstream)

Download a file from MTP device. The used ProtableDeviceContent instance must be a file! For easier usage use download_file

Parameters:

Name Type Description Default
outputstream Any

Open python file for writing

required

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> cont = dev[0].get_content()
>>> cont = cont.get_path("Interner Speicher\Ringtones\hangouts_incoming_call.ogg")
>>> name = '..\..\Tests\hangouts_incoming_call.ogg'
>>> outp = open(name, "wb")
>>> cont.download_stream(outp)
>>> outp.close()
Source code in win_mtp\access.py
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
def download_stream(self, outputstream: Any) -> None:
    """Download a file from MTP device.
    The used ProtableDeviceContent instance must be a file!
    For easier usage use download_file

    Args:
        outputstream: Open python file for writing

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> cont = dev[0].get_content()
        >>> cont = cont.get_path("Interner Speicher\\Ringtones\\hangouts_incoming_call.ogg")
        >>> name = '..\\..\\Tests\\hangouts_incoming_call.ogg'
        >>> outp = open(name, "wb")
        >>> cont.download_stream(outp)
        >>> outp.close()
    """
    try:
        resources = self._content.Transfer()  # type: ignore
        stgm_read = ctypes.c_uint(0)
        optimal_transfer_size_bytes = ctypes.pointer(ctypes.c_ulong(0))
        p_filestream = ctypes.POINTER(
            port.IStream  # pylint: disable=no-member # type: ignore
        )()
        optimal_transfer_size_bytes, q_filestream = resources.GetStream(
            self._object_id,
            WPD_RESOURCE_DEFAULT,
            stgm_read,
            optimal_transfer_size_bytes,
            p_filestream,
        )
        blocksize = optimal_transfer_size_bytes.contents.value
        filestream = q_filestream.value
        buf = (ctypes.c_ubyte * blocksize)()
        # make sure all RemoteRead parameters are in
        while True:
            buf, length = filestream.RemoteRead(buf, ctypes.c_ulong(blocksize))
            if length == 0:
                break
            outputstream.write(bytearray(buf[:length]))
    except comtypes.COMError as err:
        raise IOError from err

get_child(name)

Returns a PortableDeviceContent for one child whos name is known. The search is case sensitive.

Parameters:

Name Type Description Default
name str

The name of the file or directory to search

required

Returns:

Type Description
Optional[PortableDeviceContent]

The PortableDeviceContent instance of the child or None if the child could not be

Optional[PortableDeviceContent]

found.

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> cont = dev[0].get_content()
>>> str(cont.get_child("Interner Speicher"))[:58]
"<PortableDeviceContent s10001: ('Interner Speicher', 0, -1"
Source code in win_mtp\access.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def get_child(self, name: str) -> Optional["PortableDeviceContent"]:
    """Returns a PortableDeviceContent for one child whos name is known.
    The search is case sensitive.

    Args:
        name: The name of the file or directory to search

    Returns:
        The PortableDeviceContent instance of the child or None if the child could not be
        found.

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> cont = dev[0].get_content()
        >>> str(cont.get_child("Interner Speicher"))[:58]
        "<PortableDeviceContent s10001: ('Interner Speicher', 0, -1"
    """
    matches = [c for c in self.get_children() if c.name == name]
    return matches[0] if matches else None

get_children()

Get the child items of a folder.

Returns:

Type Description
list[PortableDeviceContent]

A list of PortableDeviceContent instances each representing a child entry.

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> cont = dev[0].get_content()
>>> str(cont.get_children()[0])[:58]
"<PortableDeviceContent s10001: ('Interner Speicher', 0, -1"
Source code in win_mtp\access.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
def get_children(self) -> list["PortableDeviceContent"]:
    """Get the child items of a folder.

    Returns:
        A list of PortableDeviceContent instances each representing a child entry.

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> cont = dev[0].get_content()
        >>> str(cont.get_children()[0])[:58]
        "<PortableDeviceContent s10001: ('Interner Speicher', 0, -1"
    """
    ret_objs = []
    enumobject_ids = self._content.EnumObjects(  # type: ignore
        ctypes.c_ulong(0),
        self._object_id,
        ctypes.POINTER(
            port.IPortableDeviceValues  # pylint: disable=no-member # type: ignore
        )(),
    )
    while True:
        num_objects = ctypes.c_ulong(16)  # block size, so to speak
        object_id_array = (ctypes.c_wchar_p * num_objects.value)()
        num_fetched = ctypes.pointer(ctypes.c_ulong(0))
        # be sure to change the IEnumPortableDeviceobject_ids 'Next'
        # function in the generated code to have object_ids as inout
        enumobject_ids.Next(
            num_objects,
            ctypes.cast(object_id_array, ctypes.POINTER(ctypes.c_wchar_p)),
            num_fetched,
        )
        if num_fetched.contents.value == 0:
            break
        for index in range(num_fetched.contents.value):
            curobject_id = object_id_array[index]
            value = PortableDeviceContent(curobject_id, self._content, self._properties)
            ret_objs.append(value)
            # Free memory
            address = (
                ctypes.addressof(object_id_array) + ctypes.sizeof(ctypes.c_wchar_p) * index
            )
            ptr = ctypes.pointer(ctypes.c_wchar_p.from_address(address))
            ctypes.windll.ole32.CoTaskMemFree(ptr.contents)
    ret_objs.sort(key=lambda entry: entry.date_created)
    return ret_objs

get_path(path)

Returns a PortableDeviceContent for a child whos path in the tree is known

Parameters:

Name Type Description Default
path str

The pathname to the child. Each path entry must be separated by the os.path.sep character.

required

Returns:

Type Description
Optional[PortableDeviceContent]

The PortableDeviceContent instance of the child or None if the child could not be

Optional[PortableDeviceContent]

found.

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> cont = dev[0].get_content()
>>> str(cont.get_path("Interner Speicher\Android\data"))[:41]
"<PortableDeviceContent oE: ('data', 1, -1"
Source code in win_mtp\access.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
def get_path(self, path: str) -> Optional["PortableDeviceContent"]:
    """Returns a PortableDeviceContent for a child whos path in the tree is known

    Args:
        path: The pathname to the child. Each path entry must be separated by the
                os.path.sep character.

    Returns:
        The PortableDeviceContent instance of the child or None if the child could not be
        found.

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> cont = dev[0].get_content()
        >>> str(cont.get_path("Interner Speicher\\Android\\data"))[:41]
        "<PortableDeviceContent oE: ('data', 1, -1"
    """
    cur: Optional["PortableDeviceContent"] = self
    for part in path.split(os.path.sep):
        if not cur:
            return None
        cur = cur.get_child(part)
    return cur

get_properties()

Get the properties of this content.

Returns:

Name Type Description
name str

The name for this content, normaly the file or directory name

content_type int

One of the content type values that descripe the type of the content WPD_CONTENT_TYPE_UNDEFINED, WPD_CONTENT_TYPE_STORAGE, WPD_CONTENT_TYPE_DIRECTORY, WPD_CONTENT_TYPE_FILE, WPD_CONTENT_TYPE_DEVICE

size int

The size of the file or 0 if content ist not a file

date_created datetime

The reation date of the file or directory

capacity int

The capacity of the storage, only valid if content_type is WPD_CONTENT_TYPE_STORAGE

free_capacity int

The free capacity of the storage, only valid if content_type is WPD_CONTENT_TYPE_STORAGE

serialnumber str

The serial number of the device, only valid if content_type is WPD_CONTENT_TYPE_DEVICE

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> cont = dev[0].get_content()
>>> cont.get_properties()
('HSG1316', 0, -1, datetime.datetime(1970, 1, 1, 0, 0), -1, -1, 'DQVSSCM799999999')
Source code in win_mtp\access.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
def get_properties(
    self,
) -> Tuple[str, int, int, datetime.datetime, int, int, str]:
    """Get the properties of this content.

    Returns:
        name: The name for this content, normaly the file or directory name
        content_type: One of the content type values that descripe the type of the content
                    WPD_CONTENT_TYPE_UNDEFINED, WPD_CONTENT_TYPE_STORAGE,
                    WPD_CONTENT_TYPE_DIRECTORY, WPD_CONTENT_TYPE_FILE, WPD_CONTENT_TYPE_DEVICE
        size: The size of the file or 0 if content ist not a file
        date_created: The reation date of the file or directory
        capacity: The capacity of the storage, only valid if content_type is
                    WPD_CONTENT_TYPE_STORAGE
        free_capacity: The free capacity of the storage, only valid if content_type is
                    WPD_CONTENT_TYPE_STORAGE
        serialnumber: The serial number of the device, only valid if content_type is
                    WPD_CONTENT_TYPE_DEVICE

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> cont = dev[0].get_content()
        >>> cont.get_properties()
        ('HSG1316', 0, -1, datetime.datetime(1970, 1, 1, 0, 0), -1, -1, 'DQVSSCM799999999')
    """
    if self._plain_name:
        return (
            self.name,
            self.content_type,
            self.size,
            self.date_created,
            self._capacity,
            self._free_capacity,
            self._serialnumber,
        )
    if self._object_id is None:
        return (
            "",
            WPD_CONTENT_TYPE_UNDEFINED,
            -1,
            self.date_created,
            self._capacity,
            self._free_capacity,
            self._serialnumber,
        )
    propvalues = self._properties.GetValues(
        self._object_id, PortableDeviceContent._properties_to_read
    )
    self.content_type = WPD_CONTENT_TYPE_UNDEFINED
    try:
        self._plain_name = propvalues.GetStringValue(WPD_OBJECT_NAME)
    except comtypes.COMError:
        self.content_type = WPD_CONTENT_TYPE_DIRECTORY
        self.name = self._plain_name = ""
    try:
        self.name = self._plain_name = propvalues.GetStringValue(WPD_OBJECT_ORIGINAL_FILE_NAME)
    except comtypes.COMError:
        self.name = self._plain_name
    content_id = str(propvalues.GetGuidValue(WPD_OBJECT_CONTENT_TYPE))
    if content_id in {
        "{23F05BBC-15DE-4C2A-A55B-A9AF5CE412EF}",
        "{99ED0160-17FF-4C44-9D98-1D7A6F941921}",
    }:
        # It's a storage
        try:
            self._capacity = int(propvalues.GetUnsignedLargeIntegerValue(WPD_STORAGE_CAPACITY))
        except comtypes.COMError:
            self._capacity = -1
        try:
            self._free_capacity = int(
                propvalues.GetUnsignedLargeIntegerValue(WPD_STORAGE_FREE_SPACE_IN_BYTES)
            )
        except comtypes.COMError:
            self._free_capacity = -1
        with contextlib.suppress(comtypes.COMError):
            self._serialnumber = propvalues.GetStringValue(WPD_DEVICE_SERIAL_NUMBER)
        self.content_type = WPD_CONTENT_TYPE_STORAGE
    elif content_id == "{27E2E392-A111-48E0-AB0C-E17705A05F85}":
        # It's a directory
        self.content_type = WPD_CONTENT_TYPE_DIRECTORY
    else:
        # it's not a folder or storage
        self.content_type = WPD_CONTENT_TYPE_FILE
        self.size = int(propvalues.GetUnsignedLargeIntegerValue(WPD_OBJECT_SIZE))
        filetime = propvalues.GetValue(WPD_OBJECT_DATE_MODIFIED).data.date
        days_since_1970 = (
            int(filetime)
            - (datetime.datetime(1970, 1, 1) - datetime.datetime(1899, 12, 30)).days
        )
        hours = (filetime - int(filetime)) * 24
        minutes = (hours - int(hours)) * 60
        seconds = (minutes - int(minutes)) * 60
        milliseconds = round((seconds - int(seconds)) * 1000)
        self.date_created = datetime.datetime(1970, 1, 1) + datetime.timedelta(
            days=days_since_1970,
            hours=int(hours),
            minutes=int(minutes),
            seconds=int(seconds),
            milliseconds=milliseconds,
        )
    propvalues.Clear()
    return (
        self.name,
        self.content_type,
        self.size,
        self.date_created,
        self._capacity,
        self._free_capacity,
        self._serialnumber,
    )

remove()

Deletes the current directory or file.

Return

0 on OK, else a windows errorcode

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> cont = dev[0].get_content()
>>> mycont = cont.get_path("Interner Speicher\Music\Test.mp3")
>>> if mycont: _ = mycont.remove()
>>> cont = cont.get_path("Interner Speicher\Music")
>>> name = '..\..\Tests\OnFire.mp3'
>>> cont.upload_file("Test.mp3", name)
>>> cont = dev[0].get_content()
>>> mycont = cont.get_path("Interner Speicher\Music\Test.mp3")
>>> mycont.remove()
0
Source code in win_mtp\access.py
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
def remove(self) -> int:
    """Deletes the current directory or file.

    Return:
        0 on OK, else a windows errorcode

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> cont = dev[0].get_content()
        >>> mycont = cont.get_path("Interner Speicher\\Music\\Test.mp3")
        >>> if mycont: _ = mycont.remove()
        >>> cont = cont.get_path("Interner Speicher\\Music")
        >>> name = '..\\..\\Tests\\OnFire.mp3'
        >>> cont.upload_file("Test.mp3", name)
        >>> cont = dev[0].get_content()
        >>> mycont = cont.get_path("Interner Speicher\\Music\\Test.mp3")
        >>> mycont.remove()
        0
    """
    objects_to_delete = comtypes.client.CreateObject(
        types.PortableDevicePropVariantCollection,  # pylint: disable=no-member, protected-access # type: ignore
        clsctx=comtypes.CLSCTX_INPROC_SERVER,  # pylint: disable=no-member, protected-access
        interface=port.IPortableDevicePropVariantCollection,  # pylint: disable=no-member, protected-access # type: ignore
    )
    pvar = port.tag_inner_PROPVARIANT()  # pylint: disable=no-member # type: ignore
    pvar.vt = comtypes.automation.VT_LPWSTR
    pvar.data.pwszVal = ctypes.c_wchar_p(self._object_id)
    objects_to_delete.Add(pvar)  # type: ignore
    errors = comtypes.client.CreateObject(
        types.PortableDevicePropVariantCollection,  # pylint: disable=no-member, protected-access # type: ignore
        clsctx=comtypes.CLSCTX_INPROC_SERVER,  # pylint: disable=no-member, protected-access
        interface=port.IPortableDevicePropVariantCollection,  # pylint: disable=no-member, protected-access # type: ignore
    )
    try:
        self._content.Delete(  # type: ignore
            WPD_DELETE_WITH_RECURSION, objects_to_delete, errors
        )
    except comtypes.COMError:
        return 777
    count = ctypes.c_ulong()
    errors.GetCount(ctypes.pointer(count))  # type: ignore
    for i in range(count.value):
        index = ctypes.c_ulong(i)
        pvar = port.tag_inner_PROPVARIANT()  # pylint: disable=no-member # type: ignore
        errors.GetAt(index, ctypes.pointer(pvar))  # type: ignore
        if pvar.data.uintVal != 0:
            return pvar.data.uintVal
    return 0

upload_file(filename, inputfilename)

Upload of a file to MTP device.

Parameters:

Name Type Description Default
filename str

Name of the new file on the MTP device

required
inputfilename str

Name of the file that shall be uploaded

required

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> cont = dev[0].get_content()
>>> mycont = cont.get_path("Interner Speicher\Music\Test.mp3")
>>> if mycont: _ = mycont.remove()
>>> cont = cont.get_path("Interner Speicher\Music")
>>> name = '..\..\Tests\OnFire.mp3'
>>> cont.upload_file("Test.mp3", name)
Source code in win_mtp\access.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
def upload_file(self, filename: str, inputfilename: str) -> None:
    """Upload of a file to MTP device.

    Args:
        filename: Name of the new file on the MTP device
        inputfilename: Name of the file that shall be uploaded

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> cont = dev[0].get_content()
        >>> mycont = cont.get_path("Interner Speicher\\Music\\Test.mp3")
        >>> if mycont: _ = mycont.remove()
        >>> cont = cont.get_path("Interner Speicher\\Music")
        >>> name = '..\\..\\Tests\\OnFire.mp3'
        >>> cont.upload_file("Test.mp3", name)
    """
    length = os.path.getsize(inputfilename)
    with open(inputfilename, "rb") as input_stream:
        self.upload_stream(filename, input_stream, length)

upload_stream(filename, inputstream, stream_len)

Upload a steam to a file on the MTP device. For an easier usage use upload_file

Parameters:

Name Type Description Default
filename str

Name of the new file on the MTP device

required
inputstream Any

open python file

required
stream_len int

length of the file to upload

required

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> cont = dev[0].get_content()
>>> mycont = cont.get_path("Interner Speicher\Music\Test.mp3")
>>> if mycont: _ = mycont.remove()
>>> cont = cont.get_path("Interner Speicher\Music")
>>> name = '..\..\Tests\OnFire.mp3'
>>> size = os.path.getsize(name)
>>> inp = open(name, "rb")
>>> cont.upload_stream("Test.mp3", inp, size)
>>> inp.close()
Source code in win_mtp\access.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
def upload_stream(self, filename: str, inputstream: Any, stream_len: int) -> None:
    """Upload a steam to a file on the MTP device.
    For an easier usage use upload_file

    Args:
        filename: Name of the new file on the MTP device
        inputstream: open python file
        stream_len: length of the file to upload

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> cont = dev[0].get_content()
        >>> mycont = cont.get_path("Interner Speicher\\Music\\Test.mp3")
        >>> if mycont: _ = mycont.remove()
        >>> cont = cont.get_path("Interner Speicher\\Music")
        >>> name = '..\\..\\Tests\\OnFire.mp3'
        >>> size = os.path.getsize(name)
        >>> inp = open(name, "rb")
        >>> cont.upload_stream("Test.mp3", inp, size)
        >>> inp.close()
    """
    object_properties = comtypes.client.CreateObject(
        types.PortableDeviceValues,  # pylint: disable=no-member # type: ignore
        clsctx=comtypes.CLSCTX_INPROC_SERVER,
        interface=port.IPortableDeviceValues,  # pylint: disable=no-member # type: ignore
    )
    object_properties.SetStringValue(WPD_OBJECT_PARENT_ID, self._object_id)  # type: ignore
    object_properties.SetUnsignedLargeIntegerValue(WPD_OBJECT_SIZE, stream_len)  # type: ignore
    object_properties.SetStringValue(WPD_OBJECT_ORIGINAL_FILE_NAME, filename)  # type: ignore
    object_properties.SetStringValue(WPD_OBJECT_NAME, filename)  # type: ignore
    optimal_transfer_size_bytes = ctypes.pointer(ctypes.c_ulong(0))
    p_filestream = ctypes.POINTER(port.IStream)()  # pylint: disable=no-member # type: ignore
    # be sure to change the IPortableDeviceContent
    # 'CreateObjectWithPropertiesAndData' function in the generated code to
    # have IStream ppData as 'in','out'
    filestream, _, _ = self._content.CreateObjectWithPropertiesAndData(  # type: ignore
        object_properties,
        p_filestream,
        optimal_transfer_size_bytes,
        ctypes.POINTER(ctypes.c_wchar_p)(),
    )
    # filestream = filestream.value
    blocksize = optimal_transfer_size_bytes.contents.value
    cur_written = 0
    while True:
        to_read = stream_len - cur_written
        block = inputstream.read(to_read if to_read < blocksize else blocksize)
        if len(block) <= 0:
            break
        string_buf = ctypes.create_string_buffer(block)
        written = filestream.RemoteWrite(
            ctypes.cast(string_buf, ctypes.POINTER(ctypes.c_ubyte)),
            len(block),
        )
        cur_written += written
        if cur_written >= stream_len:
            break
    stgc_default = 0
    filestream.Commit(stgc_default)

get_content_from_device_path(dev, path)

Get the content of a path.

Parameters:

Name Type Description Default
dev PortableDevice

The instance of PortableDevice where the path is searched

required
path str

The pathname of the file or directory

required

Returns:

Type Description
Optional[PortableDeviceContent]

An instance of PortableDeviceContent if the path is an existing file or directory else None is returned.

Raises:

Type Description
COMError

If something went wrong

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> n = "HSG1316\Interner Speicher\Ringtones"
>>> w =win_mtp.mtp_access.get_content_from_device_path(dev[0], n)
>>> str(w)[:46]
"<PortableDeviceContent o3: ('Ringtones', 1, -1"
Source code in win_mtp\access.py
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
def get_content_from_device_path(dev: PortableDevice, path: str) -> Optional[PortableDeviceContent]:
    """Get the content of a path.

    Args:
        dev: The instance of PortableDevice where the path is searched
        path: The pathname of the file or directory

    Returns:
        An instance of PortableDeviceContent if the path is an existing file or directory
            else None is returned.

    Exceptions:
        comtypes.COMError: If something went wrong

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> n = "HSG1316\\Interner Speicher\\Ringtones"
        >>> w =win_mtp.mtp_access.get_content_from_device_path(dev[0], n)
        >>> str(w)[:46]
        "<PortableDeviceContent o3: ('Ringtones', 1, -1"
    """
    path = path.replace("\\", os.path.sep).replace("/", os.path.sep)
    path_parts = path.split(os.path.sep)
    if path_parts[0] == dev.get_description()[0]:
        return (
            dev.get_content().get_path(os.path.sep.join(path_parts[1:]))
            if len(path_parts) > 1
            else dev.get_content()
        )
    return None

get_portable_devices()

Get all attached portable devices.

Returns:

Type Description
list[PortableDevice]

A list of PortableDevice one for each found MTP device. The list is empty if no device was found.

Raises:

Type Description
COMError

If something went wrong

Examples:

>>> import win_mtp.mtp_access
>>> win_mtp.mtp_access.get_portable_devices()
[<PortableDevice: ('HSG1316', 'HSG1316')>]
Source code in win_mtp\access.py
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
def get_portable_devices() -> list[PortableDevice]:
    """Get all attached portable devices.

    Returns:
        A list of PortableDevice one for each found MTP device. The list is empty if no device
            was found.

    Exceptions:
        comtypes.COMError: If something went wrong

    Examples:
        >>> import win_mtp.mtp_access
        >>> win_mtp.mtp_access.get_portable_devices()
        [<PortableDevice: ('HSG1316', 'HSG1316')>]
    """
    global DEVICE_MANAGER  # pylint: disable=global-statement

    if DEVICE_MANAGER is None:
        comtypes.CoInitialize()
        DEVICE_MANAGER = comtypes.client.CreateObject(
            port.PortableDeviceManager,  # pylint: disable=no-member  # type: ignore
            clsctx=comtypes.CLSCTX_INPROC_SERVER,
            interface=port.IPortableDeviceManager,  # pylint: disable=no-member  # type: ignore
        )
    pnp_device_id_count = ctypes.pointer(ctypes.c_ulong(0))
    DEVICE_MANAGER.GetDevices(ctypes.POINTER(ctypes.c_wchar_p)(), pnp_device_id_count)
    if pnp_device_id_count.contents.value == 0:
        return []
    pnp_device_ids = (ctypes.c_wchar_p * pnp_device_id_count.contents.value)()
    DEVICE_MANAGER.GetDevices(  # pylint: disable=no-member  # type: ignore
        ctypes.cast(pnp_device_ids, ctypes.POINTER(ctypes.c_wchar_p)),
        pnp_device_id_count,
    )
    return [PortableDevice(cur_id) for cur_id in pnp_device_ids if cur_id is not None]

makedirs(dev, path)

Creates the directories in path on the MTP device if they don't exist.

Parameters:

Name Type Description Default
dev PortableDevice

Portable device to create the dirs on

required
path str

pathname of the dir to create. Any directoriues in path that don't exist will e created automatically.

required

Exceptions: comtypes.COMError: If something went wrong

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> n = "HSG1316\Interner Speicher\Music\MyMusic\Test1"
>>> str(win_mtp.mtp_access.makedirs(dev[0], n))[:22]
'<PortableDeviceContent'
Source code in win_mtp\access.py
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
def makedirs(dev: PortableDevice, path: str) -> Optional[PortableDeviceContent]:
    """Creates the directories in path on the MTP device if they don't exist.

    Args:
        dev: Portable device to create the dirs on
        path: pathname of the dir to create. Any directoriues in path that don't exist
            will e created automatically.
    Exceptions:
        comtypes.COMError: If something went wrong

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> n = "HSG1316\\Interner Speicher\\Music\\MyMusic\\Test1"
        >>> str(win_mtp.mtp_access.makedirs(dev[0], n))[:22]
        '<PortableDeviceContent'
    """
    path_int = ""
    content: Optional[PortableDeviceContent] = dev.get_content()
    for dirname in path.split(os.path.sep):
        if dirname == "":
            continue
        path_int = os.path.join(path_int, dirname)
        ziel_content = get_content_from_device_path(dev, path_int)
        if not ziel_content:
            if not content:
                return None
            content.create_content(dirname)
            ziel_content = get_content_from_device_path(dev, path_int)
        content = ziel_content
    return content

walk(dev, path)

Iterates ower all files in a tree just like os.walk

Parameters:

Name Type Description Default
dev PortableDevice

Portable device to iterate in

required
path str

path from witch to iterate

required

Returns:

Type Description
Generator[tuple[str, list[PortableDeviceContent], list[PortableDeviceContent]], None, None]

A tuple with this content: A string with the root directory A list of PortableDeviceContent for the directories in the directory A list of PortableDeviceContent for the files in the directory

Raises:

Type Description
COMError

If something went wrong

Examples:

>>> import win_mtp.mtp_access
>>> dev = win_mtp.mtp_access.get_portable_devices()
>>> n = "HSG1316\Interner Speicher\Ringtones"
>>> for r, d, f in win_mtp.mtp_access.walk(dev[0], n):
...     for f1 in f:
...             print(f1.name)
...
hangouts_message.ogg
hangouts_incoming_call.ogg
Source code in win_mtp\access.py
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
def walk(
    dev: PortableDevice, path: str
) -> Generator[tuple[str, list[PortableDeviceContent], list[PortableDeviceContent]], None, None,]:
    """Iterates ower all files in a tree just like os.walk

    Args:
        dev: Portable device to iterate in
        path: path from witch to iterate

    Returns:
        A tuple with this content:
            A string with the root directory
            A list of PortableDeviceContent for the directories  in the directory
            A list of PortableDeviceContent for the files in the directory

    Exceptions:
        comtypes.COMError: If something went wrong

    Examples:
        >>> import win_mtp.mtp_access
        >>> dev = win_mtp.mtp_access.get_portable_devices()
        >>> n = "HSG1316\\Interner Speicher\\Ringtones"
        >>> for r, d, f in win_mtp.mtp_access.walk(dev[0], n):
        ...     for f1 in f:
        ...             print(f1.name)
        ...
        hangouts_message.ogg
        hangouts_incoming_call.ogg
    """
    if not (cont := get_content_from_device_path(dev, path)):
        return
    cont.full_filename = path
    walk_cont: list[PortableDeviceContent] = [cont]
    while walk_cont:
        cont = walk_cont[0]
        del walk_cont[0]
        directories: list[PortableDeviceContent] = []
        files: list[PortableDeviceContent] = []
        for child in cont.get_children():
            (name, contenttype, _, _, _, _, _) = child.get_properties()
            if contenttype in [
                WPD_CONTENT_TYPE_STORAGE,
                WPD_CONTENT_TYPE_DIRECTORY,
            ]:
                child.full_filename = os.path.join(cont.full_filename, name)
                directories.append(child)
            elif contenttype == WPD_CONTENT_TYPE_FILE:
                child.full_filename = os.path.join(cont.full_filename, name)
                files.append(child)
        yield cont.full_filename, directories, files
        walk_cont.extend(directories)