Debian Codegraph @

src/arcam/fmj/utils.py

raw
1 import asyncio
2 import aiohttp
3 import functools
4 import logging
5 import re
6 from datetime import datetime, timedelta
7 from defusedxml import ElementTree
8 from typing import Optional, Any
9
10 _LOGGER = logging.getLogger(__name__)
11
12
13 def async_retry(attempts=2, allowed_exceptions=()):
14 def decorator(f):
15 @functools.wraps(f)
16 async def wrapper(*args, **kwargs):
17 attempt = attempts
18 while True:
19 attempt -= 1
20
21 try:
22 return await f(*args, **kwargs)
23 except allowed_exceptions:
24 if attempt == 0:
25 raise
26 _LOGGER.warning("Retrying: %s %s", f, args)
27
28 return wrapper
29
30 return decorator
31
32
33 class Throttle:
34 def __init__(self, delay: float) -> None:
35 self._timestamp = datetime.now()
36 self._lock = asyncio.Lock()
37 self._delay = timedelta(seconds=delay)
38
39 async def get(self) -> None:
40 async with self._lock:
41 timestamp = datetime.now()
42 delay = (self._timestamp - timestamp).total_seconds()
43 if delay > 0:
44 await asyncio.sleep(delay)
45 self._timestamp = datetime.now() + self._delay
46
47
48 def _log_exception(msg, *args):
49 """Log an error and turn on traceback if debug is on."""
50 _LOGGER.error(msg, *args, exc_info=_LOGGER.getEffectiveLevel() == logging.DEBUG)
51
52
53 def get_uniqueid_from_udn(data) -> str | None:
54 """Extract a unique id from udn."""
55 try:
56 return data[5:].split("-")[4]
57 except IndexError:
58 _log_exception("Unable to get unique id from %s", data)
59 return None
60
61
62 def get_possibly_invalid_xml(data) -> Any:
63 try:
64 return ElementTree.fromstring(data)
65 except ElementTree.ParseError:
66 _LOGGER.info("Device provide corrupt xml, trying with ampersand replacement")
67 data = re.sub(r"&(?![A-Za-z]+[0-9]*;|#[0-9]+;|#x[0-9a-fA-F]+;)", r"&", data)
68 return ElementTree.fromstring(data)
69
70
71 def get_udn_from_xml(xml: Any) -> str | None:
72 return xml.findtext(
73 "d:device/d:UDN", None, {"d": "urn:schemas-upnp-org:device-1-0"}
74 )
75
76
77 async def get_uniqueid_from_device_description(
78 session: aiohttp.ClientSession, url: str
79 ):
80 """Retrieve and extract unique id from url."""
81 try:
82 async with session.get(url) as req:
83 req.raise_for_status()
84 data = await req.text()
85 xml = get_possibly_invalid_xml(data)
86 udn = get_udn_from_xml(xml)
87 return get_uniqueid_from_udn(udn)
88 except (aiohttp.ClientError, TimeoutError, ElementTree.ParseError):
89 _log_exception("Unable to get device description from %s", url)
90 return None
91
92
93 async def get_uniqueid_from_host(session: aiohttp.ClientSession, host: str):
94 """Try to deduce a unique id from a host based on ssdp/upnp."""
95 return await get_uniqueid_from_device_description(
96 session, f"http://{host}:8080/dd.xml"
97 )