Home Assistant Unofficial Reference 2024.12.1
view.py
Go to the documentation of this file.
1 """Implement a view to provide proxied Plex thumbnails to the media browser."""
2 
3 from __future__ import annotations
4 
5 from http import HTTPStatus
6 import logging
7 
8 from aiohttp import web
9 from aiohttp.hdrs import CACHE_CONTROL
10 from aiohttp.typedefs import LooseHeaders
11 
12 from homeassistant.components.http import KEY_AUTHENTICATED, KEY_HASS, HomeAssistantView
13 from homeassistant.components.media_player import async_fetch_image
14 
15 from .const import SERVERS
16 from .helpers import get_plex_data
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 
21 class PlexImageView(HomeAssistantView):
22  """Media player view to serve a Plex image."""
23 
24  name = "api:plex:image"
25  url = "/api/plex_image_proxy/{server_id}/{media_content_id}"
26 
27  async def get(
28  self,
29  request: web.Request,
30  server_id: str,
31  media_content_id: str,
32  ) -> web.Response:
33  """Start a get request."""
34  if not request[KEY_AUTHENTICATED]:
35  return web.Response(status=HTTPStatus.UNAUTHORIZED)
36 
37  hass = request.app[KEY_HASS]
38  if (server := get_plex_data(hass)[SERVERS].get(server_id)) is None:
39  return web.Response(status=HTTPStatus.NOT_FOUND)
40 
41  if (image_url := server.thumbnail_cache.get(media_content_id)) is None:
42  return web.Response(status=HTTPStatus.NOT_FOUND)
43 
44  data, content_type = await async_fetch_image(_LOGGER, hass, image_url)
45 
46  if data is None:
47  return web.Response(status=HTTPStatus.SERVICE_UNAVAILABLE)
48 
49  headers: LooseHeaders = {CACHE_CONTROL: "max-age=3600"}
50  return web.Response(body=data, content_type=content_type, headers=headers)
web.Response get(self, web.Request request, str server_id, str media_content_id)
Definition: view.py:32
tuple[bytes|None, str|None] async_fetch_image(logging.Logger logger, HomeAssistant hass, str url)
Definition: __init__.py:1353
PlexData get_plex_data(HomeAssistant hass)
Definition: helpers.py:29