mirror of
https://github.com/home-assistant/core
synced 2024-09-12 15:16:21 +02:00
ImageEntity split load_image_from_url (#96146)
* Initial commit * fix async_load_image_from_url
This commit is contained in:
parent
b8bc958070
commit
c54ceb2da2
@ -167,18 +167,14 @@ class ImageEntity(Entity):
|
||||
"""Return bytes of image."""
|
||||
raise NotImplementedError()
|
||||
|
||||
async def _async_load_image_from_url(self, url: str) -> Image | None:
|
||||
"""Load an image by url."""
|
||||
async def _fetch_url(self, url: str) -> httpx.Response | None:
|
||||
"""Fetch a URL."""
|
||||
try:
|
||||
response = await self._client.get(
|
||||
url, timeout=GET_IMAGE_TIMEOUT, follow_redirects=True
|
||||
)
|
||||
response.raise_for_status()
|
||||
content_type = response.headers.get("content-type")
|
||||
return Image(
|
||||
content=response.content,
|
||||
content_type=valid_image_content_type(content_type),
|
||||
)
|
||||
return response
|
||||
except httpx.TimeoutException:
|
||||
_LOGGER.error("%s: Timeout getting image from %s", self.entity_id, url)
|
||||
return None
|
||||
@ -190,14 +186,25 @@ class ImageEntity(Entity):
|
||||
err,
|
||||
)
|
||||
return None
|
||||
except ImageContentTypeError:
|
||||
_LOGGER.error(
|
||||
"%s: Image from %s has invalid content type: %s",
|
||||
self.entity_id,
|
||||
url,
|
||||
content_type,
|
||||
)
|
||||
return None
|
||||
|
||||
async def _async_load_image_from_url(self, url: str) -> Image | None:
|
||||
"""Load an image by url."""
|
||||
if response := await self._fetch_url(url):
|
||||
content_type = response.headers.get("content-type")
|
||||
try:
|
||||
return Image(
|
||||
content=response.content,
|
||||
content_type=valid_image_content_type(content_type),
|
||||
)
|
||||
except ImageContentTypeError:
|
||||
_LOGGER.error(
|
||||
"%s: Image from %s has invalid content type: %s",
|
||||
self.entity_id,
|
||||
url,
|
||||
content_type,
|
||||
)
|
||||
return None
|
||||
return None
|
||||
|
||||
async def async_image(self) -> bytes | None:
|
||||
"""Return bytes of image."""
|
||||
|
Loading…
Reference in New Issue
Block a user