adapter_crypto.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """Matrix E2EE crypto state-store shim handed to mautrix's OlmMachine."""
  2. from __future__ import annotations
  3. import logging
  4. from contextlib import suppress
  5. from typing import Any
  6. logger = logging.getLogger(__name__)
  7. class _CryptoStateStore:
  8. """StateStore shim for OlmMachine (MemoryStateStore lacks is_encrypted/get_encryption_info/
  9. find_shared_rooms); falls back to a homeserver state query when the store has no info."""
  10. def __init__(self, client_state_store: Any, joined_rooms: set, client=None):
  11. self._ss = client_state_store
  12. self._joined_rooms = joined_rooms
  13. self._client = client
  14. # MemoryStateStore has no set_encryption_info, so cache homeserver answers here.
  15. self._enc_info_cache: dict = {}
  16. async def is_encrypted(self, room_id: str) -> bool:
  17. return (await self.get_encryption_info(room_id)) is not None
  18. async def get_encryption_info(self, room_id: str):
  19. info = await self._ss.get_encryption_info(room_id) if hasattr(self._ss, "get_encryption_info") else None
  20. if info is not None:
  21. return info
  22. if room_id in self._enc_info_cache:
  23. return self._enc_info_cache[room_id]
  24. if self._client is None:
  25. return None
  26. try:
  27. from mautrix.types import EventType as _ET, RoomEncryptionStateEventContent as _Enc, RoomID as _RID
  28. raw = await self._client.get_state_event(_RID(room_id), _ET.ROOM_ENCRYPTION)
  29. except Exception as exc:
  30. logger.debug("Matrix: homeserver encryption-info query failed for %s: %s", room_id, exc)
  31. return None
  32. if not raw:
  33. return None
  34. content = raw if isinstance(raw, _Enc) else _Enc.deserialize(
  35. raw.serialize() if hasattr(raw, "serialize") else raw)
  36. if hasattr(self._ss, "set_encryption_info"):
  37. with suppress(Exception):
  38. await self._ss.set_encryption_info(_RID(room_id), content)
  39. self._enc_info_cache[room_id] = content
  40. return content
  41. async def find_shared_rooms(self, user_id: str) -> list:
  42. return list(self._joined_rooms) # all joined rooms: correct for a single-user bot