Debian Codegraph @

async_upnp_client/description_cache.py

raw
1 """async_upnp_client.description_cache module."""
2
3 import asyncio
4 import logging
5 from typing import Any, Mapping, cast
6
7 import aiohttp
8 import defusedxml.ElementTree as DET
9
10 from async_upnp_client.client import UpnpRequester
11 from async_upnp_client.const import HttpRequest
12 from async_upnp_client.exceptions import UpnpResponseError
13 from async_upnp_client.utils import etree_to_dict
14
15 _LOGGER = logging.getLogger(__name__)
16
17
18 _UNDEF = object()
19
20
21 DescriptionType = Mapping[str, Any] | None
22
23
24 def _description_xml_to_dict(description_xml: str) -> Mapping[str, str] | None:
25 """Convert description (XML) to dict."""
26 try:
27 tree = DET.fromstring(description_xml)
28 except DET.ParseError as err:
29 _LOGGER.debug("Error parsing %s: %s", description_xml, err)
30 return None
31
32 root = etree_to_dict(tree).get("root")
33 if root is None:
34 return None
35
36 return root.get("device")
37
38
39 class DescriptionCache:
40 """Cache for descriptions (xml)."""
41
42 def __init__(self, requester: UpnpRequester):
43 """Initialize."""
44 self._requester = requester
45 self._cache_dict: dict[str, asyncio.Event | DescriptionType] = {}
46
47 async def async_get_description_xml(self, location: str) -> str | None:
48 """Get a description as XML, either from cache or download it."""
49 try:
50 return await self._async_fetch_description(location)
51 except Exception: # pylint: disable=broad-except
52 # If it fails, cache the failure so we do not keep trying over and over
53 _LOGGER.exception("Failed to fetch description from: %s", location)
54
55 return None
56
57 def peek_description_dict(self, location: str | None) -> tuple[bool, DescriptionType]:
58 """Peek a description as dict, only try the cache."""
59 if location is None:
60 return True, None
61
62 description = self._cache_dict.get(location, _UNDEF)
63 if description is _UNDEF:
64 return False, None
65
66 if isinstance(description, asyncio.Event):
67 return False, None
68
69 return True, cast(DescriptionType, description)
70
71 async def async_get_description_dict(self, location: str | None) -> DescriptionType:
72 """Get a description as dict, either from cache or download it."""
73 if location is None:
74 return None
75
76 cache_dict_or_evt = self._cache_dict.get(location, _UNDEF)
77 if isinstance(cache_dict_or_evt, asyncio.Event):
78 await cache_dict_or_evt.wait()
79 elif cache_dict_or_evt is _UNDEF:
80 evt = self._cache_dict[location] = asyncio.Event()
81 try:
82 description_xml = await self.async_get_description_xml(location)
83 except UpnpResponseError:
84 self._cache_dict[location] = None
85 else:
86 if description_xml:
87 self._cache_dict[location] = _description_xml_to_dict(description_xml)
88 else:
89 self._cache_dict[location] = None
90 evt.set()
91
92 return cast(DescriptionType, self._cache_dict[location])
93
94 def uncache_description(self, location: str) -> None:
95 """Uncache a description."""
96 if location in self._cache_dict:
97 del self._cache_dict[location]
98
99 async def _async_fetch_description(self, location: str) -> str | None:
100 """Download a description from location."""
101 try:
102 for _ in range(2):
103 request = HttpRequest("GET", location, {}, None)
104 response = await self._requester.async_http_request(request)
105 if response.status_code != 200:
106 raise UpnpResponseError(status=response.status_code, headers=response.headers)
107
108 return response.body
109 # Samsung Smart TV sometimes returns an empty document the
110 # first time. Retry once.
111 except (aiohttp.ClientError, asyncio.TimeoutError) as err:
112 _LOGGER.debug("Error fetching %s: %s", location, err)
113
114 return None