2016-11-25 21:04:06 +00:00
|
|
|
"""Static file handling for HTTP component."""
|
|
|
|
import asyncio
|
|
|
|
import re
|
|
|
|
|
|
|
|
from aiohttp import hdrs
|
2017-03-30 07:50:53 +00:00
|
|
|
from aiohttp.web import FileResponse
|
|
|
|
from aiohttp.web_exceptions import HTTPNotFound
|
2016-11-25 21:04:06 +00:00
|
|
|
from aiohttp.web_urldispatcher import StaticResource
|
2017-03-30 07:50:53 +00:00
|
|
|
from yarl import unquote
|
|
|
|
|
2016-11-25 21:04:06 +00:00
|
|
|
from .const import KEY_DEVELOPMENT
|
|
|
|
|
|
|
|
_FINGERPRINT = re.compile(r'^(.+)-[a-z0-9]{32}\.(\w+)$', re.IGNORECASE)
|
|
|
|
|
|
|
|
|
2017-03-30 07:50:53 +00:00
|
|
|
class CachingStaticResource(StaticResource):
|
|
|
|
"""Static Resource handler that will add cache headers."""
|
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def _handle(self, request):
|
|
|
|
filename = unquote(request.match_info['filename'])
|
|
|
|
try:
|
|
|
|
# PyLint is wrong about resolve not being a member.
|
|
|
|
# pylint: disable=no-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():
|
|
|
|
return (yield from super()._handle(request))
|
|
|
|
elif filepath.is_file():
|
|
|
|
return CachingFileResponse(filepath, chunk_size=self._chunk_size)
|
|
|
|
else:
|
|
|
|
raise HTTPNotFound
|
|
|
|
|
|
|
|
|
|
|
|
class CachingFileResponse(FileResponse):
|
2017-01-11 20:25:02 +00:00
|
|
|
"""FileSender class that caches output if not in dev mode."""
|
2016-11-25 21:04:06 +00:00
|
|
|
|
2017-01-11 20:25:02 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
"""Initialize the hass file sender."""
|
|
|
|
super().__init__(*args, **kwargs)
|
2016-11-25 21:04:06 +00:00
|
|
|
|
2017-01-11 20:25:02 +00:00
|
|
|
orig_sendfile = self._sendfile
|
2016-11-25 21:04:06 +00:00
|
|
|
|
2017-01-11 20:25:02 +00:00
|
|
|
@asyncio.coroutine
|
2017-03-30 07:50:53 +00:00
|
|
|
def sendfile(request, fobj, count):
|
2017-01-11 20:25:02 +00:00
|
|
|
"""Sendfile that includes a cache header."""
|
|
|
|
if not request.app[KEY_DEVELOPMENT]:
|
|
|
|
cache_time = 31 * 86400 # = 1 month
|
2017-03-30 07:50:53 +00:00
|
|
|
self.headers[hdrs.CACHE_CONTROL] = "public, max-age={}".format(
|
2017-01-11 20:25:02 +00:00
|
|
|
cache_time)
|
|
|
|
|
2017-03-30 07:50:53 +00:00
|
|
|
yield from orig_sendfile(request, fobj, count)
|
2017-01-11 20:25:02 +00:00
|
|
|
|
|
|
|
# Overwriting like this because __init__ can change implementation.
|
|
|
|
self._sendfile = sendfile
|
2016-11-25 21:04:06 +00:00
|
|
|
|
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def staticresource_middleware(app, handler):
|
2017-03-30 07:50:53 +00:00
|
|
|
"""Middleware to strip out fingerprint from fingerprinted assets."""
|
2016-11-25 21:04:06 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def static_middleware_handler(request):
|
|
|
|
"""Strip out fingerprints from resource names."""
|
2017-03-30 07:50:53 +00:00
|
|
|
if not request.path.startswith('/static/'):
|
|
|
|
return handler(request)
|
|
|
|
|
2016-11-25 21:04:06 +00:00
|
|
|
fingerprinted = _FINGERPRINT.match(request.match_info['filename'])
|
|
|
|
|
|
|
|
if fingerprinted:
|
|
|
|
request.match_info['filename'] = \
|
|
|
|
'{}.{}'.format(*fingerprinted.groups())
|
|
|
|
|
2017-03-30 07:50:53 +00:00
|
|
|
return handler(request)
|
2016-11-25 21:04:06 +00:00
|
|
|
|
|
|
|
return static_middleware_handler
|