11from homeassistant .components .http import HomeAssistantView
22from homeassistant .config_entries import ConfigEntry
3- from aiohttp import web , ClientSession
3+ from aiohttp import web
4+ from homeassistant .helpers .aiohttp_client import async_get_clientsession
45import requests
56import os
67
1516from .const import DOMAIN
1617
1718class ImagesRedirect (HomeAssistantView ):
18- def __init__ (self , config_entry : ConfigEntry ):
19+ def __init__ (self , hass , config_entry : ConfigEntry ):
1920 super ().__init__ ()
2021 self ._token = config_entry .data [CONF_API_KEY ]
2122 self ._base_url = f'http{ 's' if config_entry .data [CONF_SSL ] else '' } ://{ config_entry .data [CONF_HOST ]} :{ config_entry .data [CONF_PORT ]} '
2223 self .name = f'{ self ._token } _Plex_Recently_Added'
2324 self .url = f'/{ config_entry .data [CONF_NAME ].lower () + "_" if len (config_entry .data [CONF_NAME ]) > 0 else "" } plex_recently_added'
25+ self ._session = async_get_clientsession (hass )
2426
2527 async def get (self , request ):
2628 metadataId = int (request .query .get ("metadata" , 0 ))
@@ -34,12 +36,33 @@ async def get(self, request):
3436
3537 url = f'{ self ._base_url } /library/metadata/{ metadataId } /{ image_type } /{ image_id } ?X-Plex-Token={ self ._token } '
3638
37- async with ClientSession () as session :
38- async with session .get (url ) as res :
39- if res .ok :
40- content = await res .read ()
41- return web .Response (body = content , content_type = res .content_type )
39+ fwd_headers = {}
40+ if_modified = request .headers .get ("If-Modified-Since" )
41+ if_none = request .headers .get ("If-None-Match" )
42+ if if_modified :
43+ fwd_headers ["If-Modified-Since" ] = if_modified
44+ if if_none :
45+ fwd_headers ["If-None-Match" ] = if_none
4246
43- return web .HTTPNotFound ()
47+ async with self ._session .get (url , headers = fwd_headers , timeout = 10 ) as res :
48+ if res .status == 304 :
49+ return web .Response (status = 304 )
50+
51+ if res .status == 200 :
52+ body = await res .read ()
53+ headers = {
54+ "Content-Type" : res .headers .get ("Content-Type" , "image/jpeg" ),
55+ # Strong client caching: immutable for a year cuts repeat requests
56+ "Cache-Control" : "public, max-age=31536000, immutable" ,
57+ }
58+ etag = res .headers .get ("ETag" )
59+ last_mod = res .headers .get ("Last-Modified" )
60+ if etag :
61+ headers ["ETag" ] = etag
62+ if last_mod :
63+ headers ["Last-Modified" ] = last_mod
64+ return web .Response (body = body , headers = headers )
65+
66+ return web .HTTPNotFound ()
4467
4568
0 commit comments