Skip to content

Commit

Permalink
Use built-in aiohttp timeout instead of asyncio.timeout in media_play…
Browse files Browse the repository at this point in the history
…er (home-assistant#116364)

* Use built-in aiohttp timeout instead of asyncio.timeout in media_player

Avoids having two timeouts running to fetch images

* fix mock
  • Loading branch information
bdraco authored Apr 29, 2024
1 parent 8c73c1e commit 381ffe6
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
15 changes: 9 additions & 6 deletions homeassistant/components/media_player/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from typing import Any, Final, Required, TypedDict, final
from urllib.parse import quote, urlparse

import aiohttp
from aiohttp import web
from aiohttp.hdrs import CACHE_CONTROL, CONTENT_TYPE
from aiohttp.typedefs import LooseHeaders
Expand Down Expand Up @@ -1336,19 +1337,21 @@ async def websocket_browse_media(
connection.send_result(msg["id"], result)


_FETCH_TIMEOUT = aiohttp.ClientTimeout(total=10)


async def async_fetch_image(
logger: logging.Logger, hass: HomeAssistant, url: str
) -> tuple[bytes | None, str | None]:
"""Retrieve an image."""
content, content_type = (None, None)
websession = async_get_clientsession(hass)
with suppress(TimeoutError):
async with asyncio.timeout(10):
response = await websession.get(url)
if response.status == HTTPStatus.OK:
content = await response.read()
if content_type := response.headers.get(CONTENT_TYPE):
content_type = content_type.split(";")[0]
response = await websession.get(url, timeout=_FETCH_TIMEOUT)
if response.status == HTTPStatus.OK:
content = await response.read()
if content_type := response.headers.get(CONTENT_TYPE):
content_type = content_type.split(";")[0]

if content is None:
url_parts = URL(url)
Expand Down
2 changes: 1 addition & 1 deletion tests/components/demo/test_media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ async def release(self):
class MockWebsession:
"""Test websession."""

async def get(self, url):
async def get(self, url, **kwargs):
"""Test websession get."""
return MockResponse()

Expand Down

0 comments on commit 381ffe6

Please sign in to comment.