2016-11-25 13:04:06 -08:00
|
|
|
"""Static file handling for HTTP component."""
|
|
|
|
from aiohttp import hdrs
|
2019-02-02 02:52:34 -08:00
|
|
|
from aiohttp.web import FileResponse
|
2017-03-30 00:50:53 -07:00
|
|
|
from aiohttp.web_exceptions import HTTPNotFound
|
2016-11-25 13:04:06 -08:00
|
|
|
from aiohttp.web_urldispatcher import StaticResource
|
2018-02-09 05:57:05 +01:00
|
|
|
from yarl import URL
|
2017-03-30 00:50:53 -07:00
|
|
|
|
2016-11-25 13:04:06 -08:00
|
|
|
|
2017-03-30 00:50:53 -07:00
|
|
|
class CachingStaticResource(StaticResource):
|
|
|
|
"""Static Resource handler that will add cache headers."""
|
|
|
|
|
2018-03-09 09:51:49 +08:00
|
|
|
async def _handle(self, request):
|
2018-02-09 05:57:05 +01:00
|
|
|
filename = URL(request.match_info['filename']).path
|
2017-03-30 00:50:53 -07:00
|
|
|
try:
|
|
|
|
# PyLint is wrong about resolve not being a member.
|
|
|
|
filepath = self._directory.joinpath(filename).resolve()
|
|
|
|
if not self._follow_symlinks:
|
|
|
|
filepath.relative_to(self._directory)
|
|
|
|
except (ValueError, FileNotFoundError) as error:
|
|
|
|
# relatively safe
|
|
|
|
raise HTTPNotFound() from error
|
|
|
|
except Exception as error:
|
|
|
|
# perm error or other kind!
|
|
|
|
request.app.logger.exception(error)
|
|
|
|
raise HTTPNotFound() from error
|
|
|
|
|
|
|
|
if filepath.is_dir():
|
2018-03-09 09:51:49 +08:00
|
|
|
return await super()._handle(request)
|
2018-07-23 11:16:05 +03:00
|
|
|
if filepath.is_file():
|
2017-03-30 00:50:53 -07:00
|
|
|
return CachingFileResponse(filepath, chunk_size=self._chunk_size)
|
2018-07-23 11:16:05 +03:00
|
|
|
raise HTTPNotFound
|
2017-03-30 00:50:53 -07:00
|
|
|
|
|
|
|
|
2018-03-05 13:28:41 -08:00
|
|
|
# pylint: disable=too-many-ancestors
|
2017-03-30 00:50:53 -07:00
|
|
|
class CachingFileResponse(FileResponse):
|
2017-01-11 21:25:02 +01:00
|
|
|
"""FileSender class that caches output if not in dev mode."""
|
2016-11-25 13:04:06 -08:00
|
|
|
|
2017-01-11 21:25:02 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
"""Initialize the hass file sender."""
|
|
|
|
super().__init__(*args, **kwargs)
|
2016-11-25 13:04:06 -08:00
|
|
|
|
2017-01-11 21:25:02 +01:00
|
|
|
orig_sendfile = self._sendfile
|
2016-11-25 13:04:06 -08:00
|
|
|
|
2018-03-09 09:51:49 +08:00
|
|
|
async def sendfile(request, fobj, count):
|
2017-01-11 21:25:02 +01:00
|
|
|
"""Sendfile that includes a cache header."""
|
2017-11-01 05:07:16 -07:00
|
|
|
cache_time = 31 * 86400 # = 1 month
|
|
|
|
self.headers[hdrs.CACHE_CONTROL] = "public, max-age={}".format(
|
|
|
|
cache_time)
|
2017-01-11 21:25:02 +01:00
|
|
|
|
2018-03-09 09:51:49 +08:00
|
|
|
await orig_sendfile(request, fobj, count)
|
2017-01-11 21:25:02 +01:00
|
|
|
|
|
|
|
# Overwriting like this because __init__ can change implementation.
|
|
|
|
self._sendfile = sendfile
|