python-didl-lite 1.5.0__tar.gz → 1.5.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-didl-lite
3
- Version: 1.5.0
3
+ Version: 1.5.2
4
4
  Summary: DIDL-Lite (Digital Item Declaration Language) tools for Python
5
5
  Author-email: Steven Looman <steven.looman@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -9,18 +9,16 @@ Keywords: DIDL,DIDL-lite
9
9
  Classifier: Development Status :: 5 - Production/Stable
10
10
  Classifier: Intended Audience :: Developers
11
11
  Classifier: Programming Language :: Python
12
- Classifier: Programming Language :: Python :: 3.10
13
12
  Classifier: Programming Language :: Python :: 3.11
14
13
  Classifier: Programming Language :: Python :: 3.12
15
14
  Classifier: Programming Language :: Python :: 3.13
16
15
  Classifier: Programming Language :: Python :: 3.14
17
- Requires-Python: >=3.10
16
+ Classifier: Programming Language :: Python :: 3.15
17
+ Requires-Python: >=3.11
18
18
  Description-Content-Type: text/x-rst
19
- License-File: LICENSE.md
20
19
  Requires-Dist: defusedxml>=0.6.0
21
20
  Provides-Extra: test
22
- Requires-Dist: pytest==9.0.2; extra == "test"
23
- Dynamic: license-file
21
+ Requires-Dist: pytest==9.1.1; extra == "test"
24
22
 
25
23
  DIDL-Lite (Digital Item Declaration Language) tools for Python
26
24
  ==============================================================
@@ -51,7 +49,7 @@ Releasing
51
49
 
52
50
  Steps for releasing:
53
51
 
54
- - Switch to development: ``git checkout master``
52
+ - Switch to master: ``git checkout master``
55
53
  - Do a pull: ``git pull``
56
54
  - Run towncrier: ``towncrier build --version <version>``
57
55
  - Commit towncrier results: ``git commit -m "Towncrier"``
@@ -27,7 +27,7 @@ Releasing
27
27
 
28
28
  Steps for releasing:
29
29
 
30
- - Switch to development: ``git checkout master``
30
+ - Switch to master: ``git checkout master``
31
31
  - Do a pull: ``git pull``
32
32
  - Run towncrier: ``towncrier build --version <version>``
33
33
  - Commit towncrier results: ``git commit -m "Towncrier"``
@@ -1,6 +1,5 @@
1
- # -*- coding: utf-8 -*-
2
1
  """DIDL-Lite (Digital Item Declaration Language) tools for Python."""
3
2
 
4
3
  from didl_lite import didl_lite # noqa: F401
5
4
 
6
- __version__ = "1.5.0"
5
+ __version__ = "1.5.2"
@@ -1,21 +1,9 @@
1
- # -*- coding: utf-8 -*-
2
1
  """DIDL-Lite (Digital Item Declaration Language) tools for Python."""
3
2
  # pylint: disable=too-many-lines
4
3
 
5
4
  import re
6
- from typing import (
7
- Any,
8
- Dict,
9
- Iterable,
10
- List,
11
- Mapping,
12
- Optional,
13
- Sequence,
14
- Tuple,
15
- Type,
16
- TypeVar,
17
- Union,
18
- )
5
+ from collections.abc import Iterable, Mapping, Sequence
6
+ from typing import Any, Self
19
7
  from xml.etree import ElementTree as ET
20
8
 
21
9
  import defusedxml.ElementTree
@@ -29,11 +17,6 @@ from .utils import (
29
17
  to_camel_case,
30
18
  )
31
19
 
32
- TDO = TypeVar("TDO", bound="DidlObject") # pylint: disable=invalid-name
33
- TC = TypeVar("TC", bound="Container") # pylint: disable=invalid-name
34
- TD = TypeVar("TD", bound="Descriptor") # pylint: disable=invalid-name
35
- TR = TypeVar("TR", bound="Resource") # pylint: disable=invalid-name
36
-
37
20
 
38
21
  class DidlLiteException(Exception):
39
22
  """DIDL Lite Exception."""
@@ -42,16 +25,16 @@ class DidlLiteException(Exception):
42
25
  # region: DidlObjects
43
26
 
44
27
  # upnp_class to python type mapping
45
- _upnp_class_map: Dict[str, Type["DidlObject"]] = {}
46
- _upnp_class_map_lowercase: Dict[str, Type["DidlObject"]] = {}
28
+ _upnp_class_map: dict[str, type["DidlObject"]] = {}
29
+ _upnp_class_map_lowercase: dict[str, type["DidlObject"]] = {}
47
30
 
48
31
 
49
32
  class DidlObject:
50
33
  """DIDL Object."""
51
34
 
52
- tag: Optional[str] = None
35
+ tag: str | None = None
53
36
  upnp_class: str = "object"
54
- didl_properties_defs: List[Tuple[str, str, str]] = [
37
+ didl_properties_defs: list[tuple[str, str, str]] = [
55
38
  ("didl_lite", "@id", "R"),
56
39
  ("didl_lite", "@parentID", "R"),
57
40
  ("didl_lite", "@restricted", "R"),
@@ -64,12 +47,12 @@ class DidlObject:
64
47
 
65
48
  id: str
66
49
  parent_id: str
67
- res: List["Resource"]
68
- xml_el: Optional[ET.Element]
50
+ res: list["Resource"]
51
+ xml_el: ET.Element | None
69
52
  descriptors: Sequence["Descriptor"]
70
53
 
71
54
  @classmethod
72
- def __init_subclass__(cls: Type["DidlObject"], **kwargs: Any) -> None:
55
+ def __init_subclass__(cls: type["DidlObject"], **kwargs: Any) -> None:
73
56
  """Create mapping of upnp_class to Python type for fast lookup."""
74
57
  super().__init_subclass__(**kwargs)
75
58
  assert cls.upnp_class not in _upnp_class_map
@@ -81,8 +64,8 @@ class DidlObject:
81
64
  self,
82
65
  id: str = "",
83
66
  parent_id: str = "",
84
- descriptors: Optional[Sequence["Descriptor"]] = None,
85
- xml_el: Optional[ET.Element] = None,
67
+ descriptors: Sequence["Descriptor"] | None = None,
68
+ xml_el: ET.Element | None = None,
86
69
  strict: bool = True,
87
70
  **properties: Any,
88
71
  ) -> None:
@@ -101,9 +84,7 @@ class DidlObject:
101
84
  self.xml_el = xml_el
102
85
  self.descriptors = descriptors if descriptors else []
103
86
 
104
- def _ensure_required_properties(
105
- self, strict: bool, properties: Mapping[str, Any]
106
- ) -> None:
87
+ def _ensure_required_properties(self, strict: bool, properties: Mapping[str, Any]) -> None:
107
88
  """Check if all required properties are given."""
108
89
  if not strict:
109
90
  return
@@ -127,14 +108,14 @@ class DidlObject:
127
108
  setattr(self, key, value)
128
109
 
129
110
  @classmethod
130
- def from_xml(cls: Type[TDO], xml_el: ET.Element, strict: bool = True) -> TDO:
111
+ def from_xml(cls, xml_el: ET.Element, strict: bool = True) -> Self:
131
112
  """
132
113
  Initialize from an XML node.
133
114
 
134
115
  I.e., parse XML and return instance.
135
116
  """
136
117
  # pylint: disable=too-many-locals
137
- properties = {} # type: Dict[str, Any]
118
+ properties: dict[str, Any] = {}
138
119
 
139
120
  # attributes
140
121
  for attr_key, attr_value in xml_el.attrib.items():
@@ -184,9 +165,7 @@ class DidlObject:
184
165
  continue
185
166
  key = didl_property_def_key(property_def)
186
167
 
187
- if (
188
- getattr(self, key) is None or key == "res"
189
- ): # no resources, handled later on
168
+ if getattr(self, key) is None or key == "res": # no resources, handled later on
190
169
  continue
191
170
 
192
171
  tag = property_def[0] + ":" + property_def[1]
@@ -245,11 +224,7 @@ class DidlObject:
245
224
  def __repr__(self) -> str:
246
225
  """Evaluatable string representation of this object."""
247
226
  class_name = type(self).__name__
248
- attr = ", ".join(
249
- f"{key}={val!r}"
250
- for key, val in self.__dict__.items()
251
- if key not in ("class", "xml_el")
252
- )
227
+ attr = ", ".join(f"{key}={val!r}" for key, val in self.__dict__.items() if key not in ("class", "xml_el"))
253
228
  return f"{class_name}({attr})"
254
229
 
255
230
 
@@ -321,6 +296,7 @@ class MusicTrack(AudioItem):
321
296
  didl_properties_defs = AudioItem.didl_properties_defs + [
322
297
  ("upnp", "artist", "O"),
323
298
  ("upnp", "album", "O"),
299
+ ("upnp", "albumArtURI", "O"),
324
300
  ("upnp", "originalTrackNumber", "O"),
325
301
  ("upnp", "playlist", "O"),
326
302
  ("upnp", "storageMedium", "O"),
@@ -621,8 +597,8 @@ class Container(DidlObject, list):
621
597
  self,
622
598
  id: str = "",
623
599
  parent_id: str = "",
624
- descriptors: Optional[Sequence["Descriptor"]] = None,
625
- xml_el: Optional[ET.Element] = None,
600
+ descriptors: Sequence["Descriptor"] | None = None,
601
+ xml_el: ET.Element | None = None,
626
602
  strict: bool = True,
627
603
  children: Iterable[DidlObject] = (),
628
604
  **properties: Any,
@@ -633,7 +609,7 @@ class Container(DidlObject, list):
633
609
  self.extend(children)
634
610
 
635
611
  @classmethod
636
- def from_xml(cls: Type[TC], xml_el: ET.Element, strict: bool = True) -> TC:
612
+ def from_xml(cls, xml_el: ET.Element, strict: bool = True) -> Self:
637
613
  """
638
614
  Initialize from an XML node.
639
615
 
@@ -660,11 +636,7 @@ class Container(DidlObject, list):
660
636
  def __repr__(self) -> str:
661
637
  """Evaluatable string representation of this object."""
662
638
  class_name = type(self).__name__
663
- attr = ", ".join(
664
- f"{key}={val!r}"
665
- for key, val in self.__dict__.items()
666
- if key not in ("class", "xml_el")
667
- )
639
+ attr = ", ".join(f"{key}={val!r}" for key, val in self.__dict__.items() if key not in ("class", "xml_el"))
668
640
  children_repr = ", ".join(repr(child) for child in self)
669
641
  return f"{class_name}({attr}, children=[{children_repr}])"
670
642
 
@@ -915,19 +887,19 @@ class Resource:
915
887
 
916
888
  def __init__(
917
889
  self,
918
- uri: Optional[str],
919
- protocol_info: Optional[str],
920
- import_uri: Optional[str] = None,
921
- size: Optional[str] = None,
922
- duration: Optional[str] = None,
923
- bitrate: Optional[str] = None,
924
- sample_frequency: Optional[str] = None,
925
- bits_per_sample: Optional[str] = None,
926
- nr_audio_channels: Optional[str] = None,
927
- resolution: Optional[str] = None,
928
- color_depth: Optional[str] = None,
929
- protection: Optional[str] = None,
930
- xml_el: Optional[ET.Element] = None,
890
+ uri: str | None,
891
+ protocol_info: str | None,
892
+ import_uri: str | None = None,
893
+ size: str | None = None,
894
+ duration: str | None = None,
895
+ bitrate: str | None = None,
896
+ sample_frequency: str | None = None,
897
+ bits_per_sample: str | None = None,
898
+ nr_audio_channels: str | None = None,
899
+ resolution: str | None = None,
900
+ color_depth: str | None = None,
901
+ protection: str | None = None,
902
+ xml_el: ET.Element | None = None,
931
903
  ) -> None:
932
904
  """Initialize."""
933
905
  # pylint: disable=too-many-arguments,too-many-positional-arguments
@@ -946,7 +918,7 @@ class Resource:
946
918
  self.xml_el = xml_el
947
919
 
948
920
  @classmethod
949
- def from_xml(cls: Type[TR], xml_el: ET.Element) -> TR:
921
+ def from_xml(cls, xml_el: ET.Element) -> Self:
950
922
  """Initialize from an XML node."""
951
923
  uri = xml_el.text
952
924
  protocol_info = xml_el.attrib.get("protocolInfo")
@@ -988,11 +960,7 @@ class Resource:
988
960
  def __repr__(self) -> str:
989
961
  """Evaluatable string representation of this object."""
990
962
  class_name = type(self).__name__
991
- attr = ", ".join(
992
- f"{key}={val!r}"
993
- for key, val in self.__dict__.items()
994
- if val is not None and key != "xml_el"
995
- )
963
+ attr = ", ".join(f"{key}={val!r}" for key, val in self.__dict__.items() if val is not None and key != "xml_el")
996
964
  return f"{class_name}({attr})"
997
965
 
998
966
 
@@ -1003,9 +971,9 @@ class Descriptor:
1003
971
  self,
1004
972
  id: str,
1005
973
  name_space: str,
1006
- type: Optional[str] = None,
1007
- text: Optional[str] = None,
1008
- xml_el: Optional[ET.Element] = None,
974
+ type: str | None = None,
975
+ text: str | None = None,
976
+ xml_el: ET.Element | None = None,
1009
977
  ) -> None:
1010
978
  """Initialize."""
1011
979
  # pylint: disable=invalid-name,redefined-builtin,too-many-arguments,too-many-positional-arguments
@@ -1016,7 +984,7 @@ class Descriptor:
1016
984
  self.xml_el = xml_el
1017
985
 
1018
986
  @classmethod
1019
- def from_xml(cls: Type[TD], xml_el: ET.Element) -> TD:
987
+ def from_xml(cls, xml_el: ET.Element) -> Self:
1020
988
  """Initialize from an XML node."""
1021
989
  id_ = xml_el.attrib["id"]
1022
990
  name_space = xml_el.attrib["nameSpace"]
@@ -1045,11 +1013,7 @@ class Descriptor:
1045
1013
  def __repr__(self) -> str:
1046
1014
  """Evaluatable string representation of this object."""
1047
1015
  class_name = type(self).__name__
1048
- attr = ", ".join(
1049
- f"{key}={val!r}"
1050
- for key, val in self.__dict__.items()
1051
- if val is not None and key != "xml_el"
1052
- )
1016
+ attr = ", ".join(f"{key}={val!r}" for key, val in self.__dict__.items() if val is not None and key != "xml_el")
1053
1017
  return f"{class_name}({attr})"
1054
1018
 
1055
1019
 
@@ -1071,45 +1035,51 @@ def to_xml_string(*objects: DidlObject) -> bytes:
1071
1035
  return ET.tostring(root_el)
1072
1036
 
1073
1037
 
1074
- def from_xml_string(
1075
- xml_string: str, strict: bool = True
1076
- ) -> List[Union[DidlObject, Descriptor]]:
1038
+ def from_xml_string(xml_string: str, strict: bool = True) -> list[DidlObject | Descriptor]:
1077
1039
  """Parse DIDL-Lite XML string."""
1078
1040
  if not strict:
1079
1041
  # Find all prefixes used in tags, e.g., <prefix:tag ...>
1080
- used_prefixes = set(re.findall(r"<([a-zA-Z0-9]+):", xml_string))
1042
+ used_prefixes = set(re.findall(r"<([A-Za-z_][\w.-]*):", xml_string))
1081
1043
 
1082
1044
  # Find all defined namespaces, e.g., xmlns:prefix=...
1083
- defined_prefixes = set(re.findall(r"xmlns:([a-zA-Z0-9]+)=", xml_string))
1045
+ defined_prefixes = set(re.findall(r"xmlns:([A-Za-z_][\w.-]*)=", xml_string))
1084
1046
 
1085
1047
  # Identify prefixes used but not defined.
1086
- missing_prefixes = (
1087
- used_prefixes - defined_prefixes - {"DIDL-Lite", "dc", "upnp", "dlna"}
1088
- )
1089
-
1090
- # Remove the "if missing_prefixes:" line and just keep the for loop
1091
- for prefix in missing_prefixes:
1092
- dlna_ns = 'xmlns:dlna="urn:schemas-dlna-org:metadata-1-0/"'
1093
- if dlna_ns in xml_string:
1094
- replacement = f'{dlna_ns} xmlns:{prefix}="http://tempuri.org/{prefix}/"'
1095
- xml_string = xml_string.replace(dlna_ns, replacement)
1048
+ missing_prefixes = used_prefixes - defined_prefixes - {"DIDL-Lite", "dc", "upnp", "dlna"}
1049
+
1050
+ if missing_prefixes:
1051
+ # Inject temporary namespace declarations into the DIDL-Lite root
1052
+ # opening tag. Anchoring on the root element (always present in
1053
+ # valid DIDL-Lite documents) instead of an optional `xmlns:dlna`
1054
+ # allows us to recover XML from devices that omit the dlna
1055
+ # namespace declaration entirely (observed on JBL Authentics and
1056
+ # WiiM/LinkPlay players sending `<song:*>` without `xmlns:dlna`).
1057
+ # The root itself may carry a prefix, as in `<didl:DIDL-Lite>`, so
1058
+ # the match is captured and written back unchanged.
1059
+ injections = " ".join(
1060
+ f'xmlns:{prefix}="http://tempuri.org/{prefix}/"' for prefix in sorted(missing_prefixes)
1061
+ )
1062
+ xml_string = re.sub(
1063
+ r"<((?:[A-Za-z_][\w.-]*:)?DIDL-Lite)\b",
1064
+ lambda match: f"<{match.group(1)} {injections}",
1065
+ xml_string,
1066
+ count=1,
1067
+ )
1096
1068
 
1097
1069
  # Proceed with parsing using the (potentially) patched xml_string
1098
1070
  xml_el = defusedxml.ElementTree.fromstring(xml_string)
1099
1071
  return from_xml_el(xml_el, strict)
1100
1072
 
1101
1073
 
1102
- def from_xml_el(
1103
- xml_el: ET.Element, strict: bool = True
1104
- ) -> List[Union[DidlObject, Descriptor]]:
1074
+ def from_xml_el(xml_el: ET.Element, strict: bool = True) -> list[DidlObject | Descriptor]:
1105
1075
  """Convert XML Element to DIDL Objects."""
1106
- didl_objects = [] # type: List[Union[DidlObject, Descriptor]]
1076
+ didl_objects: list[DidlObject | Descriptor] = []
1107
1077
 
1108
1078
  # items and containers, in order
1109
1079
  for child_el in xml_el:
1110
- if child_el.tag != expand_namespace_tag(
1111
- "didl_lite:item"
1112
- ) and child_el.tag != expand_namespace_tag("didl_lite:container"):
1080
+ if child_el.tag != expand_namespace_tag("didl_lite:item") and child_el.tag != expand_namespace_tag(
1081
+ "didl_lite:container"
1082
+ ):
1113
1083
  continue
1114
1084
 
1115
1085
  # construct item
@@ -1139,9 +1109,7 @@ def from_xml_el(
1139
1109
 
1140
1110
 
1141
1111
  # upnp_class to python type mapping
1142
- def type_by_upnp_class(
1143
- upnp_class: str, strict: bool = True
1144
- ) -> Optional[Type[DidlObject]]:
1112
+ def type_by_upnp_class(upnp_class: str, strict: bool = True) -> type[DidlObject] | None:
1145
1113
  """Get DidlObject-type by upnp_class.
1146
1114
 
1147
1115
  When strict is False, the upnp_class lookup will be done ignoring string
@@ -1,7 +1,7 @@
1
1
  """Utilities."""
2
2
 
3
+ import functools
3
4
  import re
4
- from typing import Optional, Tuple
5
5
 
6
6
  NAMESPACES = {
7
7
  "didl_lite": "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/",
@@ -27,7 +27,7 @@ def expand_namespace_tag(tag: str) -> str:
27
27
  return f"{{{namespace_uri}}}{tag}"
28
28
 
29
29
 
30
- def split_namespace_tag(namespaced_tag: str) -> Tuple[Optional[str], str]:
30
+ def split_namespace_tag(namespaced_tag: str) -> tuple[str | None, str]:
31
31
  """
32
32
  Extract namespace and tag from namespaced-tag.
33
33
 
@@ -43,6 +43,10 @@ def split_namespace_tag(namespaced_tag: str) -> Tuple[Optional[str], str]:
43
43
  return namespace, tag
44
44
 
45
45
 
46
+ # Cached: called for every attribute set on a DidlObject, with a small closed
47
+ # set of property names. Bounded, as from_xml also passes names read from
48
+ # documents received from other devices.
49
+ @functools.lru_cache(maxsize=256)
46
50
  def to_camel_case(name: str) -> str:
47
51
  """Get camel case of name."""
48
52
  sub1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
@@ -61,7 +65,7 @@ def didl_property_key(didl_property_name: str) -> str:
61
65
  return to_camel_case(didl_property_name.replace("@", "_"))
62
66
 
63
67
 
64
- def didl_property_def_key(didl_property_def: Tuple[str, ...]) -> str:
68
+ def didl_property_def_key(didl_property_def: tuple[str, ...]) -> str:
65
69
  """Get Python property key for didl_property_def."""
66
70
  if didl_property_def[1].startswith("@"):
67
71
  return to_camel_case(didl_property_def[1].replace("@", ""))
@@ -17,13 +17,13 @@ classifiers = [
17
17
  "Development Status :: 5 - Production/Stable",
18
18
  "Intended Audience :: Developers",
19
19
  "Programming Language :: Python",
20
- "Programming Language :: Python :: 3.10",
21
20
  "Programming Language :: Python :: 3.11",
22
21
  "Programming Language :: Python :: 3.12",
23
22
  "Programming Language :: Python :: 3.13",
24
23
  "Programming Language :: Python :: 3.14",
24
+ "Programming Language :: Python :: 3.15",
25
25
  ]
26
- requires-python = ">=3.10"
26
+ requires-python = ">=3.11"
27
27
  dependencies = [
28
28
  "defusedxml>=0.6.0",
29
29
  ]
@@ -34,7 +34,7 @@ dynamic = ["version"]
34
34
 
35
35
  [project.optional-dependencies]
36
36
  test = [
37
- "pytest==9.0.2",
37
+ "pytest==9.1.1",
38
38
  ]
39
39
 
40
40
  [tool.setuptools]
@@ -46,10 +46,8 @@ version = { attr = "didl_lite.__version__" }
46
46
  [tool.setuptools.package-data]
47
47
  didl_lite = ["py.typed"]
48
48
 
49
- [tool.flake8]
50
- max-line-length = 99
51
-
52
49
  [tool.mypy]
50
+ python_version = "3.11"
53
51
  check_untyped_defs = true
54
52
  disallow_untyped_calls = true
55
53
  disallow_untyped_defs = true
@@ -61,3 +59,37 @@ warn_redundant_casts = true
61
59
  warn_return_any = true
62
60
  warn_unused_configs = true
63
61
  warn_unused_ignores = true
62
+
63
+ [tool.ruff]
64
+ line-length = 119
65
+
66
+ [tool.ruff.lint]
67
+ select = ["C901", "D", "E", "F", "I", "W"]
68
+ ignore = ["D202"]
69
+
70
+ [tool.ruff.lint.mccabe]
71
+ max-complexity = 25
72
+
73
+ [tool.ruff.lint.pydocstyle]
74
+ convention = "pep257"
75
+
76
+ [tool.ruff.lint.isort]
77
+ known-first-party = ["didl_lite"]
78
+
79
+ [tool.deptry]
80
+ package_module_name_map = { "pytest" = "pytest" }
81
+
82
+ [tool.deptry.per_rule_ignores]
83
+ DEP002 = ["pytest"]
84
+
85
+ [tool.pylint.format]
86
+ max-line-length = 119
87
+
88
+ [tool.pylint.basic]
89
+ good-names = ["otherItem", "storageMedium"]
90
+
91
+ [tool.codespell]
92
+ ignore-words-list = "wan"
93
+
94
+ [tool.coverage.run]
95
+ source = ["didl_lite"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-didl-lite
3
- Version: 1.5.0
3
+ Version: 1.5.2
4
4
  Summary: DIDL-Lite (Digital Item Declaration Language) tools for Python
5
5
  Author-email: Steven Looman <steven.looman@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -9,18 +9,16 @@ Keywords: DIDL,DIDL-lite
9
9
  Classifier: Development Status :: 5 - Production/Stable
10
10
  Classifier: Intended Audience :: Developers
11
11
  Classifier: Programming Language :: Python
12
- Classifier: Programming Language :: Python :: 3.10
13
12
  Classifier: Programming Language :: Python :: 3.11
14
13
  Classifier: Programming Language :: Python :: 3.12
15
14
  Classifier: Programming Language :: Python :: 3.13
16
15
  Classifier: Programming Language :: Python :: 3.14
17
- Requires-Python: >=3.10
16
+ Classifier: Programming Language :: Python :: 3.15
17
+ Requires-Python: >=3.11
18
18
  Description-Content-Type: text/x-rst
19
- License-File: LICENSE.md
20
19
  Requires-Dist: defusedxml>=0.6.0
21
20
  Provides-Extra: test
22
- Requires-Dist: pytest==9.0.2; extra == "test"
23
- Dynamic: license-file
21
+ Requires-Dist: pytest==9.1.1; extra == "test"
24
22
 
25
23
  DIDL-Lite (Digital Item Declaration Language) tools for Python
26
24
  ==============================================================
@@ -51,7 +49,7 @@ Releasing
51
49
 
52
50
  Steps for releasing:
53
51
 
54
- - Switch to development: ``git checkout master``
52
+ - Switch to master: ``git checkout master``
55
53
  - Do a pull: ``git pull``
56
54
  - Run towncrier: ``towncrier build --version <version>``
57
55
  - Commit towncrier results: ``git commit -m "Towncrier"``
@@ -1,4 +1,3 @@
1
- LICENSE.md
2
1
  README.rst
3
2
  pyproject.toml
4
3
  setup.cfg
@@ -1,4 +1,4 @@
1
1
  defusedxml>=0.6.0
2
2
 
3
3
  [test]
4
- pytest==9.0.2
4
+ pytest==9.1.1
@@ -0,0 +1,14 @@
1
+ [bumpversion]
2
+ current_version = 1.5.2
3
+ commit = True
4
+ tag = False
5
+ tag_name = {new_version}
6
+
7
+ [bumpversion:file:didl_lite/__init__.py]
8
+ search = __version__ = "{current_version}"
9
+ replace = __version__ = "{new_version}"
10
+
11
+ [egg_info]
12
+ tag_build =
13
+ tag_date = 0
14
+
@@ -1,10 +1,9 @@
1
- # -*- coding: utf-8 -*-
2
1
  """Unit tests for didl_lite."""
3
2
 
4
3
  import pytest
5
4
  from defusedxml import ElementTree as ET
6
5
 
7
- from didl_lite import didl_lite
6
+ from didl_lite import didl_lite, utils
8
7
 
9
8
  NAMESPACES = {
10
9
  "didl_lite": "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/",
@@ -234,9 +233,7 @@ class TestDidlLite:
234
233
 
235
234
  def test_container_to_xml(self) -> None:
236
235
  """Test container to XML."""
237
- container = didl_lite.Album(
238
- id="0", parent_id="0", title="Audio Item Title", restricted="1"
239
- )
236
+ container = didl_lite.Album(id="0", parent_id="0", title="Audio Item Title", restricted="1")
240
237
  resource = didl_lite.Resource("url", "protocol_info")
241
238
  item = didl_lite.AudioItem(
242
239
  id="0",
@@ -285,9 +282,7 @@ class TestDidlLite:
285
282
  # pylint: disable=import-outside-toplevel
286
283
  from didl_lite.didl_lite import Album, AudioItem, Resource
287
284
 
288
- container = Album(
289
- id="0", parent_id="0", title="Audio Item Title", restricted="1"
290
- )
285
+ container = Album(id="0", parent_id="0", title="Audio Item Title", restricted="1")
291
286
  resource = Resource("url", "protocol_info")
292
287
  item = AudioItem(
293
288
  id="0",
@@ -427,9 +422,7 @@ class TestDidlLite:
427
422
 
428
423
  def test_descriptor_to_xml(self) -> None:
429
424
  """Test descriptor to XML."""
430
- descriptor = didl_lite.Descriptor(
431
- id="1", name_space="ns", type="type", text="Text"
432
- )
425
+ descriptor = didl_lite.Descriptor(id="1", name_space="ns", type="type", text="Text")
433
426
  item = didl_lite.AudioItem(
434
427
  id="0",
435
428
  parent_id="0",
@@ -468,9 +461,7 @@ class TestDidlLite:
468
461
 
469
462
  descriptor_repr = repr(descriptor)
470
463
  descriptor_remade = eval(descriptor_repr) # pylint: disable=eval-used
471
- assert ET.tostring(descriptor.to_xml()) == ET.tostring(
472
- descriptor_remade.to_xml()
473
- )
464
+ assert ET.tostring(descriptor.to_xml()) == ET.tostring(descriptor_remade.to_xml())
474
465
 
475
466
  def test_item_order(self) -> None:
476
467
  """Test item ordering."""
@@ -608,9 +599,7 @@ class TestDidlLite:
608
599
 
609
600
  def test_default_properties_set(self) -> None:
610
601
  """Test defaults for item properties."""
611
- item = didl_lite.VideoItem(
612
- id="0", parent_id="0", title="Video Item Title", restricted="1"
613
- )
602
+ item = didl_lite.VideoItem(id="0", parent_id="0", title="Video Item Title", restricted="1")
614
603
  assert hasattr(item, "genre_type") # property is set
615
604
 
616
605
  def test_property_case(self) -> None:
@@ -707,6 +696,88 @@ class TestDidlLite:
707
696
  assert objs[0].sub_title == "Test Subtitle"
708
697
  assert isinstance(objs[0], didl_lite.MusicTrack)
709
698
 
699
+ def test_from_xml_string_unbound_prefix_without_dlna_namespace(self) -> None:
700
+ """Test unbound prefix recovery when xmlns:dlna is absent.
701
+
702
+ Regression: the previous implementation anchored the namespace
703
+ injection on an existing `xmlns:dlna` declaration. Devices such as
704
+ JBL Authentics and WiiM/LinkPlay players emit `<song:*>` tags
705
+ without declaring `xmlns:dlna`, leaving the unbound prefix in place
706
+ and breaking parsing even with strict=False.
707
+ """
708
+ broken_xml = (
709
+ '<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" '
710
+ 'xmlns:dc="http://purl.org/dc/elements/1.1/" '
711
+ 'xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/">'
712
+ '<item id="1" parentID="0" restricted="1">'
713
+ "<dc:title>Test Title</dc:title>"
714
+ "<song:subTitle>Test Subtitle</song:subTitle>"
715
+ "<upnp:class>object.item.audioItem.musicTrack</upnp:class>"
716
+ "</item>"
717
+ "</DIDL-Lite>"
718
+ )
719
+
720
+ objs = didl_lite.from_xml_string(broken_xml, strict=False)
721
+
722
+ assert len(objs) == 1
723
+ assert objs[0].title == "Test Title"
724
+ assert "sub_title" in objs[0].__dict__
725
+ assert objs[0].sub_title == "Test Subtitle"
726
+ assert isinstance(objs[0], didl_lite.MusicTrack)
727
+
728
+ def test_from_xml_string_unbound_prefix_with_prefixed_root(self) -> None:
729
+ """Test unbound prefix recovery when the root element carries a prefix.
730
+
731
+ The DIDL-Lite root may be written as `<didl:DIDL-Lite>` rather than
732
+ `<DIDL-Lite>`. The namespace injection has to recognise that form and
733
+ write the matched name back unchanged, otherwise the opening tag no
734
+ longer matches its closing tag.
735
+ """
736
+ broken_xml = (
737
+ '<didl:DIDL-Lite xmlns:didl="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" '
738
+ 'xmlns:dc="http://purl.org/dc/elements/1.1/" '
739
+ 'xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/">'
740
+ '<didl:item id="1" parentID="0" restricted="1">'
741
+ "<dc:title>Test Title</dc:title>"
742
+ "<song:subTitle>Test Subtitle</song:subTitle>"
743
+ "<upnp:class>object.item.audioItem.musicTrack</upnp:class>"
744
+ "</didl:item>"
745
+ "</didl:DIDL-Lite>"
746
+ )
747
+
748
+ objs = didl_lite.from_xml_string(broken_xml, strict=False)
749
+
750
+ assert len(objs) == 1
751
+ assert objs[0].title == "Test Title"
752
+ assert objs[0].sub_title == "Test Subtitle"
753
+ assert isinstance(objs[0], didl_lite.MusicTrack)
754
+
755
+ def test_from_xml_string_unbound_prefix_with_ncname_characters(self) -> None:
756
+ """Test unbound prefix recovery for prefixes holding '-', '.' or '_'.
757
+
758
+ An XML namespace prefix is an NCName, so it may contain a hyphen, a
759
+ period or an underscore after its first character. Recovery has to
760
+ detect those prefixes as well, not only alphanumeric ones.
761
+ """
762
+ for prefix in ("my-song", "my.song", "my_song"):
763
+ broken_xml = (
764
+ '<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" '
765
+ 'xmlns:dc="http://purl.org/dc/elements/1.1/" '
766
+ 'xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/">'
767
+ '<item id="1" parentID="0" restricted="1">'
768
+ "<dc:title>Test Title</dc:title>"
769
+ f"<{prefix}:subTitle>Test Subtitle</{prefix}:subTitle>"
770
+ "<upnp:class>object.item.audioItem.musicTrack</upnp:class>"
771
+ "</item>"
772
+ "</DIDL-Lite>"
773
+ )
774
+
775
+ objs = didl_lite.from_xml_string(broken_xml, strict=False)
776
+
777
+ assert len(objs) == 1, f"prefix {prefix} was not recovered"
778
+ assert objs[0].title == "Test Title"
779
+ assert isinstance(objs[0], didl_lite.MusicTrack)
780
+
710
781
  def test_music_track_artist_and_genre(self) -> None:
711
782
  """Test MusicTrack artist and genre properties."""
712
783
  track = didl_lite.MusicTrack(
@@ -722,3 +793,13 @@ class TestDidlLite:
722
793
 
723
794
  assert b"<upnp:artist>My Artist</upnp:artist>" in xml
724
795
  assert b"<upnp:genre>My Genre</upnp:genre>" in xml
796
+
797
+ def test_to_camel_case_is_cached(self) -> None:
798
+ """Test to_camel_case is cached, and used cached through didl_lite."""
799
+ assert hasattr(utils.to_camel_case, "cache_info")
800
+ # didl_lite imports the name; it must be the cached function too.
801
+ assert didl_lite.to_camel_case is utils.to_camel_case
802
+
803
+ hits_before = utils.to_camel_case.cache_info().hits
804
+ didl_lite.MusicTrack(id="0", parent_id="0", title="Title", restricted="1")
805
+ assert utils.to_camel_case.cache_info().hits > hits_before
@@ -1,194 +0,0 @@
1
- Apache License
2
- ==============
3
-
4
- _Version 2.0, January 2004_
5
- _&lt;<http://www.apache.org/licenses/>&gt;_
6
-
7
- ### Terms and Conditions for use, reproduction, and distribution
8
-
9
- #### 1. Definitions
10
-
11
- “License” shall mean the terms and conditions for use, reproduction, and
12
- distribution as defined by Sections 1 through 9 of this document.
13
-
14
- “Licensor” shall mean the copyright owner or entity authorized by the copyright
15
- owner that is granting the License.
16
-
17
- “Legal Entity” shall mean the union of the acting entity and all other entities
18
- that control, are controlled by, or are under common control with that entity.
19
- For the purposes of this definition, “control” means **(i)** the power, direct or
20
- indirect, to cause the direction or management of such entity, whether by
21
- contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
22
- outstanding shares, or **(iii)** beneficial ownership of such entity.
23
-
24
- “You” (or “Your”) shall mean an individual or Legal Entity exercising
25
- permissions granted by this License.
26
-
27
- “Source” form shall mean the preferred form for making modifications, including
28
- but not limited to software source code, documentation source, and configuration
29
- files.
30
-
31
- “Object” form shall mean any form resulting from mechanical transformation or
32
- translation of a Source form, including but not limited to compiled object code,
33
- generated documentation, and conversions to other media types.
34
-
35
- “Work” shall mean the work of authorship, whether in Source or Object form, made
36
- available under the License, as indicated by a copyright notice that is included
37
- in or attached to the work (an example is provided in the Appendix below).
38
-
39
- “Derivative Works” shall mean any work, whether in Source or Object form, that
40
- is based on (or derived from) the Work and for which the editorial revisions,
41
- annotations, elaborations, or other modifications represent, as a whole, an
42
- original work of authorship. For the purposes of this License, Derivative Works
43
- shall not include works that remain separable from, or merely link (or bind by
44
- name) to the interfaces of, the Work and Derivative Works thereof.
45
-
46
- “Contribution” shall mean any work of authorship, including the original version
47
- of the Work and any modifications or additions to that Work or Derivative Works
48
- thereof, that is intentionally submitted to Licensor for inclusion in the Work
49
- by the copyright owner or by an individual or Legal Entity authorized to submit
50
- on behalf of the copyright owner. For the purposes of this definition,
51
- “submitted” means any form of electronic, verbal, or written communication sent
52
- to the Licensor or its representatives, including but not limited to
53
- communication on electronic mailing lists, source code control systems, and
54
- issue tracking systems that are managed by, or on behalf of, the Licensor for
55
- the purpose of discussing and improving the Work, but excluding communication
56
- that is conspicuously marked or otherwise designated in writing by the copyright
57
- owner as “Not a Contribution.”
58
-
59
- “Contributor” shall mean Licensor and any individual or Legal Entity on behalf
60
- of whom a Contribution has been received by Licensor and subsequently
61
- incorporated within the Work.
62
-
63
- #### 2. Grant of Copyright License
64
-
65
- Subject to the terms and conditions of this License, each Contributor hereby
66
- grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
67
- irrevocable copyright license to reproduce, prepare Derivative Works of,
68
- publicly display, publicly perform, sublicense, and distribute the Work and such
69
- Derivative Works in Source or Object form.
70
-
71
- #### 3. Grant of Patent License
72
-
73
- Subject to the terms and conditions of this License, each Contributor hereby
74
- grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
75
- irrevocable (except as stated in this section) patent license to make, have
76
- made, use, offer to sell, sell, import, and otherwise transfer the Work, where
77
- such license applies only to those patent claims licensable by such Contributor
78
- that are necessarily infringed by their Contribution(s) alone or by combination
79
- of their Contribution(s) with the Work to which such Contribution(s) was
80
- submitted. If You institute patent litigation against any entity (including a
81
- cross-claim or counterclaim in a lawsuit) alleging that the Work or a
82
- Contribution incorporated within the Work constitutes direct or contributory
83
- patent infringement, then any patent licenses granted to You under this License
84
- for that Work shall terminate as of the date such litigation is filed.
85
-
86
- #### 4. Redistribution
87
-
88
- You may reproduce and distribute copies of the Work or Derivative Works thereof
89
- in any medium, with or without modifications, and in Source or Object form,
90
- provided that You meet the following conditions:
91
-
92
- * **(a)** You must give any other recipients of the Work or Derivative Works a copy of
93
- this License; and
94
- * **(b)** You must cause any modified files to carry prominent notices stating that You
95
- changed the files; and
96
- * **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
97
- all copyright, patent, trademark, and attribution notices from the Source form
98
- of the Work, excluding those notices that do not pertain to any part of the
99
- Derivative Works; and
100
- * **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
101
- Derivative Works that You distribute must include a readable copy of the
102
- attribution notices contained within such NOTICE file, excluding those notices
103
- that do not pertain to any part of the Derivative Works, in at least one of the
104
- following places: within a NOTICE text file distributed as part of the
105
- Derivative Works; within the Source form or documentation, if provided along
106
- with the Derivative Works; or, within a display generated by the Derivative
107
- Works, if and wherever such third-party notices normally appear. The contents of
108
- the NOTICE file are for informational purposes only and do not modify the
109
- License. You may add Your own attribution notices within Derivative Works that
110
- You distribute, alongside or as an addendum to the NOTICE text from the Work,
111
- provided that such additional attribution notices cannot be construed as
112
- modifying the License.
113
-
114
- You may add Your own copyright statement to Your modifications and may provide
115
- additional or different license terms and conditions for use, reproduction, or
116
- distribution of Your modifications, or for any such Derivative Works as a whole,
117
- provided Your use, reproduction, and distribution of the Work otherwise complies
118
- with the conditions stated in this License.
119
-
120
- #### 5. Submission of Contributions
121
-
122
- Unless You explicitly state otherwise, any Contribution intentionally submitted
123
- for inclusion in the Work by You to the Licensor shall be under the terms and
124
- conditions of this License, without any additional terms or conditions.
125
- Notwithstanding the above, nothing herein shall supersede or modify the terms of
126
- any separate license agreement you may have executed with Licensor regarding
127
- such Contributions.
128
-
129
- #### 6. Trademarks
130
-
131
- This License does not grant permission to use the trade names, trademarks,
132
- service marks, or product names of the Licensor, except as required for
133
- reasonable and customary use in describing the origin of the Work and
134
- reproducing the content of the NOTICE file.
135
-
136
- #### 7. Disclaimer of Warranty
137
-
138
- Unless required by applicable law or agreed to in writing, Licensor provides the
139
- Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
140
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
141
- including, without limitation, any warranties or conditions of TITLE,
142
- NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
143
- solely responsible for determining the appropriateness of using or
144
- redistributing the Work and assume any risks associated with Your exercise of
145
- permissions under this License.
146
-
147
- #### 8. Limitation of Liability
148
-
149
- In no event and under no legal theory, whether in tort (including negligence),
150
- contract, or otherwise, unless required by applicable law (such as deliberate
151
- and grossly negligent acts) or agreed to in writing, shall any Contributor be
152
- liable to You for damages, including any direct, indirect, special, incidental,
153
- or consequential damages of any character arising as a result of this License or
154
- out of the use or inability to use the Work (including but not limited to
155
- damages for loss of goodwill, work stoppage, computer failure or malfunction, or
156
- any and all other commercial damages or losses), even if such Contributor has
157
- been advised of the possibility of such damages.
158
-
159
- #### 9. Accepting Warranty or Additional Liability
160
-
161
- While redistributing the Work or Derivative Works thereof, You may choose to
162
- offer, and charge a fee for, acceptance of support, warranty, indemnity, or
163
- other liability obligations and/or rights consistent with this License. However,
164
- in accepting such obligations, You may act only on Your own behalf and on Your
165
- sole responsibility, not on behalf of any other Contributor, and only if You
166
- agree to indemnify, defend, and hold each Contributor harmless for any liability
167
- incurred by, or claims asserted against, such Contributor by reason of your
168
- accepting any such warranty or additional liability.
169
-
170
- _END OF TERMS AND CONDITIONS_
171
-
172
- ### APPENDIX: How to apply the Apache License to your work
173
-
174
- To apply the Apache License to your work, attach the following boilerplate
175
- notice, with the fields enclosed by brackets `[]` replaced with your own
176
- identifying information. (Don't include the brackets!) The text should be
177
- enclosed in the appropriate comment syntax for the file format. We also
178
- recommend that a file or class name and description of purpose be included on
179
- the same “printed page” as the copyright notice for easier identification within
180
- third-party archives.
181
-
182
- Copyright [yyyy] [name of copyright owner]
183
-
184
- Licensed under the Apache License, Version 2.0 (the "License");
185
- you may not use this file except in compliance with the License.
186
- You may obtain a copy of the License at
187
-
188
- http://www.apache.org/licenses/LICENSE-2.0
189
-
190
- Unless required by applicable law or agreed to in writing, software
191
- distributed under the License is distributed on an "AS IS" BASIS,
192
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
193
- See the License for the specific language governing permissions and
194
- limitations under the License.
@@ -1,51 +0,0 @@
1
- [bumpversion]
2
- current_version = 1.5.0
3
- commit = True
4
- tag = False
5
- tag_name = {new_version}
6
-
7
- [bumpversion:file:didl_lite/__init__.py]
8
- search = __version__ = "{current_version}"
9
- replace = __version__ = "{new_version}"
10
-
11
- [bdist_wheel]
12
- python-tag = py3
13
-
14
- [metadata]
15
- license_file = LICENSE.md
16
-
17
- [flake8]
18
- exclude = .venv,.git,.tox,docs,venv,bin,lib,deps,build
19
- max-line-length = 119
20
- max-complexity = 25
21
- ignore =
22
- E501,
23
- W503,
24
- E203,
25
- D202,
26
- W504
27
- noqa-require-code = True
28
-
29
- [mypy]
30
- check_untyped_defs = true
31
- disallow_untyped_calls = true
32
- disallow_untyped_defs = true
33
- disallow_incomplete_defs = true
34
- disallow_untyped_decorators = true
35
- no_implicit_optional = true
36
- warn_incomplete_stub = true
37
- warn_redundant_casts = true
38
- warn_return_any = true
39
- warn_unused_configs = true
40
- warn_unused_ignores = true
41
-
42
- [codespell]
43
- ignore-words-list = wan
44
-
45
- [coverage:run]
46
- source = didl_lite
47
-
48
- [egg_info]
49
- tag_build =
50
- tag_date = 0
51
-