"""A file handler for audios."""
from __future__ import annotations
from os.path import splitext
from pyramid.config import Configurator
from pyramid.request import Request
from chrysalio.helpers.literal import Literal
from ..lib.ciotype import CioType
from ..lib.ciopath import CioPath
from ..lib.handler import LAYOUT_VIEW_PT, Handler
from ..lib.warehouse import Warehouse
from ..lib.i18n import _
EXTENSIONS_WEB = ('.ogg', '.mp3', '.wav', '.webm', '.aac')
# =============================================================================
[docs]
def includeme(configurator: Configurator):
"""Function to include an audio handler.
:type configurator: pyramid.config.Configurator
:param configurator:
Object used to do configuration declaration within the application.
"""
Handler.register(configurator, HandlerAudio)
# =============================================================================
[docs]
class HandlerAudio(Handler):
"""Class to manage an audio."""
ciotype = CioType('audio')
label = _('Generic audio file handling')
viewings = ( # yapf: disable
{'name': 'default',
'label': _('Default'),
'template': LAYOUT_VIEW_PT,
'css': ('/ciowarehouse2/css/handler_audio.css',)},)
# -------------------------------------------------------------------------
[docs]
def match(self, ciotype: CioType) -> bool:
"""Check whether this file handler matches with the CioType.
See: :meth:`.lib.handler.Handler.match`
"""
return ciotype.type_ == 'audio' \
and f'.{ciotype.subtype}' in EXTENSIONS_WEB
# -------------------------------------------------------------------------
[docs]
def view(
self,
request: Request,
warehouse: Warehouse,
ciopath: CioPath,
ts_factory=None) -> str | None:
"""Return a string containing HTML to display the file.
See: :meth:`.lib.handler.Handler.view`
"""
if not ciopath or \
splitext(ciopath.path)[1].lower() not in EXTENSIONS_WEB:
return None
url = request.route_path('file_download', ciopath=ciopath.route())
message = request.localizer.translate(
_('Your browser does not support HTML5 audio.'))
content = '<div class="cioAudio"><audio controls="">'\
f'<source src="{url}"/><span>{message}</span></audio></div>'
return self._chameleon_render(
request, warehouse, ciopath, self.viewings[0], ts_factory or _,
{'content': Literal(content)})