refactor(webui): move media replay helpers out of websocket channel
This commit is contained in:
1 parent
7aa5e620be
commit
f382133bb4
5 files changed
+155
-125
No files matched your search
@@ -24,6 +24,8 @@ from nanobot.config.paths import get_media_dir
|
||||
from nanobot.utils.helpers import safe_filename
|
||||
|
||||
MediaDirProvider = Callable[[str | None], Path]
|
||||
SignedMediaPath = Callable[[Path], dict[str, str] | None]
|
||||
SignedMediaUrl = Callable[[Path], str | None]
|
||||
|
||||
|
||||
def b64url_encode(data: bytes) -> str:
|
||||
@@ -172,6 +174,64 @@ def sign_or_stage_media_path(
|
||||
return {"url": signed, "name": path.name}
|
||||
|
||||
|
||||
def media_attachment_kind(name: str) -> str:
|
||||
"""Infer the WebUI media attachment kind from a filename."""
|
||||
mime, _ = mimetypes.guess_type(name)
|
||||
if mime and mime.startswith("video/"):
|
||||
return "video"
|
||||
if mime and mime.startswith("image/"):
|
||||
return "image"
|
||||
return "file"
|
||||
|
||||
|
||||
def signed_media_attachments(
|
||||
paths: list[str],
|
||||
*,
|
||||
sign_path: SignedMediaPath,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Map persisted media paths to WebUI attachment dicts with fresh signed URLs."""
|
||||
out: list[dict[str, Any]] = []
|
||||
for pstr in paths:
|
||||
path = Path(pstr)
|
||||
att = sign_path(path)
|
||||
if att is None:
|
||||
continue
|
||||
url = att.get("url")
|
||||
if not url:
|
||||
continue
|
||||
name = att.get("name") or path.name
|
||||
out.append({"kind": media_attachment_kind(name), "url": url, "name": name})
|
||||
return out
|
||||
|
||||
|
||||
def attach_signed_media_urls(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
sign_path: SignedMediaUrl,
|
||||
) -> None:
|
||||
"""Replace raw media path lists in a WebUI session payload with signed URLs."""
|
||||
messages = payload.get("messages")
|
||||
if not isinstance(messages, list):
|
||||
return
|
||||
for msg in messages:
|
||||
if not isinstance(msg, dict):
|
||||
continue
|
||||
media = msg.get("media")
|
||||
if not isinstance(media, list) or not media:
|
||||
continue
|
||||
urls: list[dict[str, str]] = []
|
||||
for entry in media:
|
||||
if not isinstance(entry, str) or not entry:
|
||||
continue
|
||||
signed = sign_path(Path(entry))
|
||||
if signed is None:
|
||||
continue
|
||||
urls.append({"url": signed, "name": Path(entry).name})
|
||||
if urls:
|
||||
msg["media_urls"] = urls
|
||||
msg.pop("media", None)
|
||||
|
||||
|
||||
def serve_signed_media(
|
||||
sig: str,
|
||||
payload: str,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Logging helpers for the WebUI WebSocket server surface."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from websockets.exceptions import ConnectionClosed
|
||||
|
||||
OPENING_HANDSHAKE_FAILED_MESSAGE = "opening handshake failed"
|
||||
|
||||
|
||||
def _exception_chain_has_disconnect(exc: BaseException | None) -> bool:
|
||||
seen: set[int] = set()
|
||||
while exc is not None:
|
||||
ident = id(exc)
|
||||
if ident in seen:
|
||||
return False
|
||||
seen.add(ident)
|
||||
if isinstance(exc, (
|
||||
BrokenPipeError,
|
||||
ConnectionAbortedError,
|
||||
ConnectionResetError,
|
||||
ConnectionClosed,
|
||||
)):
|
||||
return True
|
||||
exc = exc.__cause__ or exc.__context__
|
||||
return False
|
||||
|
||||
|
||||
class WebSocketHandshakeNoiseFilter(logging.Filter):
|
||||
"""Suppress restart-time handshakes where the browser already disconnected."""
|
||||
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
if record.getMessage() != OPENING_HANDSHAKE_FAILED_MESSAGE:
|
||||
return True
|
||||
exc_info = record.exc_info
|
||||
exc = exc_info[1] if isinstance(exc_info, tuple) and len(exc_info) >= 2 else None
|
||||
return not _exception_chain_has_disconnect(exc)
|
||||
|
||||
|
||||
def websockets_server_logger() -> logging.Logger:
|
||||
ws_logger = logging.getLogger("websockets.server")
|
||||
if not any(isinstance(f, WebSocketHandshakeNoiseFilter) for f in ws_logger.filters):
|
||||
ws_logger.addFilter(WebSocketHandshakeNoiseFilter())
|
||||
return ws_logger
|
||||
Reference in new issue
Block a user