session_images.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """Staging-only image uploads on the authenticated session authority."""
  2. import asyncio
  3. from pathlib import Path
  4. from hermes_state_runtime import RuntimeStoreError
  5. async def attach_bytes(connection, ref, params):
  6. if (not isinstance(ref.session_id, str) or not ref.session_id
  7. or set(params) - {'session_id', 'profile', 'content_base64', 'data', 'filename', 'ext'}
  8. or any(not isinstance(value, str) for value in params.values())):
  9. raise RuntimeStoreError('invalid_params')
  10. if ref.session_id not in connection.subscriptions:
  11. raise RuntimeStoreError('permission_denied')
  12. # The declared ``profile`` selector names this owner's own home or is refused (dokterdok N73).
  13. from gateway.session_busy_controls import authorize
  14. authorize(connection, ref, params, 'session:submit')
  15. # The owner, never the caller or ambient process profile, selects staging.
  16. directory = Path(connection.authority.profile_id) / 'cache' / 'images'
  17. return await asyncio.to_thread(_stage, directory, params)
  18. def _stage(directory, params):
  19. from tui_gateway.prompt_attachments import (
  20. _ATTACH_BYTES_MAX_BYTES, _decode_attach_base64, _sniff_image_ext, stage_image_bytes,
  21. )
  22. try:
  23. data = _decode_attach_base64(params.get('content_base64') or params.get('data') or '',
  24. mime_prefix='image/', max_bytes=_ATTACH_BYTES_MAX_BYTES)
  25. except OverflowError as exc:
  26. raise RuntimeStoreError('invalid_params') from exc
  27. if not data:
  28. raise RuntimeStoreError('invalid_params')
  29. hint = params.get('ext', '').strip().lower().lstrip('.')
  30. ext = _sniff_image_ext(data, params.get('filename') or (f'x.{hint}' if hint else ''))
  31. mime = {'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
  32. '.gif': 'image/gif', '.webp': 'image/webp'}.get(ext)
  33. if mime is None:
  34. raise RuntimeStoreError('invalid_params')
  35. try:
  36. path = stage_image_bytes(directory, data, ext, prefix='upload')
  37. except OSError as exc:
  38. raise RuntimeStoreError('storage_unavailable') from exc
  39. return {'attached': True, 'path': str(path), 'mime': mime, 'name': path.name,
  40. 'count': 1, 'remainder': '', 'text': f'[User attached image: {path.name}]', 'bytes': len(data)}