Debian Codegraph @

async_upnp_client/utils.py

raw symbols SCIP
1 """async_upnp_client.utils module."""
2
3 import asyncio
4 import re
5 import socket
6 from collections import defaultdict
7 from collections.abc import Mapping as abcMapping
8 from collections.abc import MutableMapping as abcMutableMapping
9 from datetime import datetime, timedelta, timezone
10 from socket import AddressFamily # pylint: disable=no-name-in-module
11 from typing import Any, Callable, Generator
12 from urllib.parse import urljoin, urlsplit
13
14 import defusedxml.ElementTree as DET
15 from voluptuous import Invalid
16
17 EXTERNAL_IP = "1.1.1.1"
18 EXTERNAL_PORT = 80
19
20 UTC = timezone(timedelta(hours=0))
21 _UNCOMPILED_MATCHERS: dict[str, Callable] = {
22 # date
23 r"\d{4}-\d{2}-\d{2}$": lambda value: datetime.strptime(value, "%Y-%m-%d").date(),
24 r"\d{2}:\d{2}:\d{2}$": lambda value: datetime.strptime(value, "%H:%M:%S").time(),
25 # datetime
26 r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$": lambda value: datetime.strptime(value, "%Y-%m-%dT%H:%M:%S"),
27 r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$": lambda value: datetime.strptime(value, "%Y-%m-%d %H:%M:%S"),
28 # time.tz
29 r"\d{2}:\d{2}:\d{2}[+-]\d{4}$": lambda value: datetime.strptime(value, "%H:%M:%S%z").timetz(),
30 r"\d{2}:\d{2}:\d{2} [+-]\d{4}$": lambda value: datetime.strptime(value, "%H:%M:%S %z").timetz(),
31 # datetime.tz
32 r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}z$": lambda value: datetime.strptime(value, "%Y-%m-%dT%H:%M:%Sz").replace(
33 tzinfo=UTC
34 ),
35 r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$": lambda value: datetime.strptime(value, "%Y-%m-%dT%H:%M:%Sz").replace(
36 tzinfo=UTC
37 ),
38 r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}$": lambda value: datetime.strptime(value, "%Y-%m-%dT%H:%M:%S%z"),
39 r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} [+-]\d{4}$": lambda value: datetime.strptime(value, "%Y-%m-%dT%H:%M:%S %z"),
40 }
41
42 COMPILED_MATCHERS: dict[re.Pattern, Callable] = {
43 re.compile(matcher): parser for matcher, parser in _UNCOMPILED_MATCHERS.items()
44 }
45
46 TIME_RE = re.compile(r"(?P<sign>[-+])?(?P<h>\d+):(?P<m>\d+):(?P<s>\d+)\.?(?P<ms>\d+)?")
47
48
49 class lowerstr(str): # pylint: disable=invalid-name
50 """A prelowered string."""
51
52
53 class CaseInsensitiveDict(abcMutableMapping):
54 """Case insensitive dict."""
55
56 __slots__ = ("_data", "_case_map")
57
58 def __init__(self, data: abcMapping | None = None, **kwargs: Any) -> None:
59 """Initialize."""
60 self._data: dict[Any, Any] = {**(data or {}), **kwargs}
61 self._case_map: dict[str, Any] = {
62 (
63 k
64 if type(k) is lowerstr # pylint: disable=unidiomatic-typecheck
65 else k.lower()
66 ): k
67 for k in self._data
68 }
69
70 def copy(self) -> "CaseInsensitiveDict":
71 """Copy a CaseInsensitiveDict.
72
73 Returns a copy of CaseInsensitiveDict.
74 """
75 # pylint: disable=protected-access
76 _copy = CaseInsensitiveDict.__new__(CaseInsensitiveDict)
77 _copy._data = self._data.copy()
78 _copy._case_map = self._case_map.copy()
79 return _copy
80
81 def combine(self, other: "CaseInsensitiveDict") -> "CaseInsensitiveDict":
82 """Combine a CaseInsensitiveDict with another CaseInsensitiveDict.
83
84 Returns a brand new CaseInsensitiveDict that is the combination
85 of the two CaseInsensitiveDicts.
86 """
87 # pylint: disable=protected-access
88 _combined = CaseInsensitiveDict.__new__(CaseInsensitiveDict)
89 _combined._data = {**self._data, **other._data}
90 _combined._case_map = {**self._case_map, **other._case_map}
91 return _combined
92
93 def combine_lower_dict(self, lower_dict: dict[lowerstr, Any]) -> "CaseInsensitiveDict":
94 """Combine a CaseInsensitiveDict with a dict where all the keys are lowerstr.
95
96 Returns a brand new CaseInsensitiveDict that is the combination
97 of the CaseInsensitiveDict and dict where all the keys are lowerstr.
98 """
99 # pylint: disable=protected-access
100 _combined = CaseInsensitiveDict.__new__(CaseInsensitiveDict)
101 _combined._data = {**self._data, **lower_dict}
102 _combined._case_map = {**self._case_map, **{k: k for k in lower_dict}}
103 return _combined
104
105 def case_map(self) -> dict[str, str]:
106 """Get the case map."""
107 return self._case_map
108
109 def as_dict(self) -> dict[str, Any]:
110 """Return the underlying dict without iterating."""
111 return self._data
112
113 def as_lower_dict(self) -> dict[str, Any]:
114 """Return the underlying dict in lowercase."""
115 return {k.lower(): v for k, v in self._data.items()}
116
117 def get_lower(self, lower_key: str, default: Any = None) -> Any:
118 """Get a lower case key."""
119 return self._data.get(self._case_map.get(lower_key), default)
120
121 def lower_values_true(self, lower_keys: tuple[str, ...]) -> bool:
122 """Check if all lower case keys are present and true values."""
123 for lower_key in lower_keys:
124 if not self._data.get(self._case_map.get(lower_key)):
125 return False
126 return True
127
128 def replace(self, new_data: abcMapping) -> None:
129 """Replace the underlying dict without making a copy if possible."""
130 if isinstance(new_data, CaseInsensitiveDict):
131 self._data = new_data.as_dict()
132 self._case_map = new_data.case_map()
133 else:
134 self._data = {**new_data}
135 self._case_map = {
136 (
137 k
138 if type(k) is lowerstr # pylint: disable=unidiomatic-typecheck
139 else k.lower()
140 ): k
141 for k in self._data
142 }
143
144 def del_lower(self, lower_key: str) -> None:
145 """Delete a lower case key."""
146 del self._data[self._case_map[lower_key]]
147 del self._case_map[lower_key]
148
149 def __setitem__(self, key: str, value: Any) -> None:
150 """Set item."""
151 lower_key = key.lower()
152 if self._case_map.get(lower_key, key) != key:
153 # Case changed
154 del self._data[self._case_map[lower_key]]
155 self._data[key] = value
156 self._case_map[lower_key] = key
157
158 def __getitem__(self, key: str) -> Any:
159 """Get item."""
160 return self._data[self._case_map[key.lower()]]
161
162 def __delitem__(self, key: str) -> None:
163 """Del item."""
164 lower_key = key.lower()
165 del self._data[self._case_map[lower_key]]
166 del self._case_map[lower_key]
167
168 def __len__(self) -> int:
169 """Get length."""
170 return len(self._data)
171
172 def __iter__(self) -> Generator[str, None, None]:
173 """Get iterator."""
174 return (key for key in self._data.keys())
175
176 def __repr__(self) -> str:
177 """Repr."""
178 return repr(self._data)
179
180 def __str__(self) -> str:
181 """Str."""
182 return str(self._data)
183
184 def __eq__(self, other: Any) -> bool:
185 """Compare for equality."""
186 if isinstance(other, CaseInsensitiveDict):
187 return self.as_lower_dict() == other.as_lower_dict()
188
189 if isinstance(other, abcMapping):
190 return self.as_lower_dict() == {key.lower(): value for key, value in other.items()}
191
192 return NotImplemented
193
194 def __hash__(self) -> int:
195 """Get hash."""
196 return hash(tuple(sorted(self._data.items())))
197
198
199 def time_to_str(time: timedelta) -> str:
200 """Convert timedelta to str/units."""
201 total_seconds = abs(time.total_seconds())
202 target = {
203 "sign": "-" if time.total_seconds() < 0 else "",
204 "hours": int(total_seconds // 3600),
205 "minutes": int(total_seconds % 3600 // 60),
206 "seconds": int(total_seconds % 60),
207 }
208 return "{sign}{hours}:{minutes}:{seconds}".format(**target)
209
210
211 def str_to_time(string: str) -> timedelta | None:
212 """Convert a string to timedelta."""
213 match = TIME_RE.match(string)
214 if not match:
215 return None
216
217 sign = -1 if match.group("sign") == "-" else 1
218 hours = int(match.group("h"))
219 minutes = int(match.group("m"))
220 seconds = int(match.group("s"))
221 if match.group("ms"):
222 msec = int(match.group("ms"))
223 else:
224 msec = 0
225 return sign * timedelta(hours=hours, minutes=minutes, seconds=seconds, milliseconds=msec)
226
227
228 def absolute_url(device_url: str, url: str) -> str:
229 """
230 Convert a relative URL to an absolute URL pointing at device.
231
232 If url is already an absolute url (i.e., starts with http:/https:),
233 then the url itself is returned.
234 """
235 if url.startswith("http:") or url.startswith("https:"):
236 return url
237
238 return urljoin(device_url, url)
239
240
241 def require_tzinfo(value: Any) -> Any:
242 """Require tzinfo."""
243 if value.tzinfo is None:
244 raise Invalid("Requires tzinfo")
245 return value
246
247
248 def parse_date_time(value: str) -> Any:
249 """Parse a date/time/date_time value."""
250 # fix up timezone part
251 if value[-6] in ["+", "-"] and value[-3] == ":":
252 value = value[:-3] + value[-2:]
253 for pattern, parser in COMPILED_MATCHERS.items():
254 if pattern.match(value):
255 return parser(value)
256 raise ValueError("Unknown date/time: " + value)
257
258
259 def _target_url_to_addr(target_url: str | None) -> tuple[str, int]:
260 """Resolve target_url into an address usable for get_local_ip."""
261 if target_url:
262 if "//" not in target_url:
263 # Make sure urllib can work with target_url to get the host
264 target_url = "//" + target_url
265 target_url_split = urlsplit(target_url)
266 target_host = target_url_split.hostname or EXTERNAL_IP
267 target_port = target_url_split.port or EXTERNAL_PORT
268 else:
269 target_host = EXTERNAL_IP
270 target_port = EXTERNAL_PORT
271
272 return target_host, target_port
273
274
275 def get_local_ip(target_url: str | None = None) -> str:
276 """Try to get the local IP of this machine, used to talk to target_url.
277
278 Only IPv4 addresses are supported.
279 """
280 target_addr = _target_url_to_addr(target_url)
281
282 try:
283 temp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
284 temp_sock.connect(target_addr)
285 local_ip: str = temp_sock.getsockname()[0]
286 return local_ip
287 finally:
288 temp_sock.close()
289
290
291 async def async_get_local_ip(
292 target_url: str | None = None, loop: asyncio.AbstractEventLoop | None = None
293 ) -> tuple[AddressFamily, str]:
294 """Try to get the local IP of this machine, used to talk to target_url.
295
296 IPv4 and IPv6 are supported. For IPv6 link-local addresses the local IP may
297 include the scope ID (zone index).
298 """
299 target_addr = _target_url_to_addr(target_url)
300 loop = loop or asyncio.get_event_loop()
301
302 # Create a UDP connection to the target. This won't cause any network
303 # traffic but will assign a local IP to the socket.
304 transport, _ = await loop.create_datagram_endpoint(asyncio.protocols.DatagramProtocol, remote_addr=target_addr)
305
306 try:
307 sock = transport.get_extra_info("socket")
308 sockname = sock.getsockname()
309 host, _ = socket.getnameinfo(sockname, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV)
310 return sock.family, host
311 finally:
312 transport.close()
313
314
315 # Adapted from http://stackoverflow.com/a/10077069
316 # to follow the XML to JSON spec
317 # https://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html
318 def etree_to_dict(tree: DET) -> dict[str, dict[str, Any] | None]:
319 """Convert an ETree object to a dict."""
320 # strip namespace
321 tag_name = tree.tag[tree.tag.find("}") + 1 :]
322
323 tree_dict: dict[str, dict[str, Any] | None] = {tag_name: {} if tree.attrib else None}
324 children = list(tree)
325 if children:
326 child_dict: dict[str, list] = defaultdict(list)
327 for child in map(etree_to_dict, children):
328 for k, val in child.items():
329 child_dict[k].append(val)
330 tree_dict = {tag_name: {k: v[0] if len(v) == 1 else v for k, v in child_dict.items()}}
331 dict_meta = tree_dict[tag_name]
332 if tree.attrib:
333 assert dict_meta is not None
334 dict_meta.update(("@" + k, v) for k, v in tree.attrib.items())
335 if tree.text:
336 text = tree.text.strip()
337 if children or tree.attrib:
338 if text:
339 assert dict_meta is not None
340 dict_meta["#text"] = text
341 else:
342 tree_dict[tag_name] = text
343 return tree_dict