|
1 | 1 | from homeassistant.components.http import HomeAssistantView |
2 | 2 | from homeassistant.config_entries import ConfigEntry |
3 | | -from aiohttp import web |
| 3 | +from aiohttp import web, ClientError |
4 | 4 | from homeassistant.helpers.aiohttp_client import async_get_clientsession |
5 | 5 | import requests |
6 | 6 | import os |
| 7 | +import logging |
| 8 | + |
| 9 | +_LOGGER = logging.getLogger(__name__) |
7 | 10 |
|
8 | 11 | from homeassistant.const import ( |
9 | 12 | CONF_API_KEY, |
@@ -44,25 +47,30 @@ async def get(self, request): |
44 | 47 | if if_none: |
45 | 48 | fwd_headers["If-None-Match"] = if_none |
46 | 49 |
|
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 | + try: |
| 51 | + async with self._session.get(url, headers=fwd_headers, timeout=10) as res: |
| 52 | + if res.status == 304: |
| 53 | + return web.Response(status=304) |
50 | 54 |
|
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) |
| 55 | + ctype = res.headers.get("Content-Type", "") |
| 56 | + if res.status == 200 and ctype.startswith("image/"): |
| 57 | + body = await res.read() |
| 58 | + headers = { |
| 59 | + "Content-Type": ctype or "image/jpeg", |
| 60 | + "Cache-Control": "public, max-age=31536000, immutable", |
| 61 | + } |
| 62 | + etag = res.headers.get("ETag") |
| 63 | + last_mod = res.headers.get("Last-Modified") |
| 64 | + if etag: |
| 65 | + headers["ETag"] = etag |
| 66 | + if last_mod: |
| 67 | + headers["Last-Modified"] = last_mod |
| 68 | + return web.Response(body=body, headers=headers) |
65 | 69 |
|
66 | | - return web.HTTPNotFound() |
| 70 | + _LOGGER.debug("Missing artwork (status=%s, ctype=%s) url=%s", res.status, ctype, url) |
| 71 | + return web.HTTPNotFound() |
| 72 | + except ClientError: |
| 73 | + _LOGGER.debug("Upstream image fetch failed url=%s", url) |
| 74 | + return web.HTTPBadGateway() |
67 | 75 |
|
68 | 76 |
|
0 commit comments