新增 Matrix 渠道扩展,支持在 Yuxi 平台中集成 Matrix 去中心化通讯协议。 包含以下功能模块: - config: 渠道配置管理 - gateway: SSE/WebSocket 网关接入 - outbound: 外发消息管理 - streaming: 流式消息处理 - pairing: 用户配对与绑定 - security: 安全校验 - crypto: 端到端加密 - dedupe: 消息去重 - monitor: 渠道状态监控 - status: 会话状态管理 - session: 会话管理 - room_resolver: 房间解析 - dm_tracker: 私聊追踪 - rate_limiter: 速率限制 - actions: 动作处理 - constants: 常量定义 - utils: 工具函数 - types: 类型定义
81 lines
2.7 KiB
Python
81 lines
2.7 KiB
Python
from __future__ import annotations
|
|
|
|
import logging
|
|
|
|
from .utils import is_room_alias, is_room_id
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class RoomResolver:
|
|
def __init__(self):
|
|
self._room_cache: dict[str, dict] = {}
|
|
|
|
async def resolve_room_id(self, identifier: str, client=None) -> str | None:
|
|
if is_room_id(identifier):
|
|
return identifier
|
|
if is_room_alias(identifier):
|
|
return await self._resolve_alias(identifier, client)
|
|
return None
|
|
|
|
async def resolve_room_name(self, room_id: str, client=None) -> str:
|
|
cached = self._room_cache.get(room_id, {})
|
|
name = cached.get("name", "")
|
|
if name:
|
|
return name
|
|
|
|
if client is not None:
|
|
try:
|
|
resp = await client.room_get_state_event(room_id, "m.room.name")
|
|
name = resp.content.get("name", "")
|
|
if name:
|
|
self._update_cache(room_id, name=name)
|
|
except Exception:
|
|
logger.debug("Failed to resolve room name for %s", room_id)
|
|
return name or room_id
|
|
|
|
async def resolve_room_topic(self, room_id: str, client=None) -> str:
|
|
cached = self._room_cache.get(room_id, {})
|
|
topic = cached.get("topic", "")
|
|
if topic:
|
|
return topic
|
|
|
|
if client is not None:
|
|
try:
|
|
resp = await client.room_get_state_event(room_id, "m.room.topic")
|
|
topic = resp.content.get("topic", "")
|
|
if topic:
|
|
self._update_cache(room_id, topic=topic)
|
|
except Exception:
|
|
logger.debug("Failed to resolve room topic for %s", room_id)
|
|
return topic
|
|
|
|
async def search_user_directory(self, search_term: str, client=None) -> list[dict]:
|
|
if client is None:
|
|
return []
|
|
try:
|
|
resp = await client.search_user_directory(search_term)
|
|
return resp.results
|
|
except Exception:
|
|
logger.debug("Failed to search user directory for '%s'", search_term)
|
|
return []
|
|
|
|
async def _resolve_alias(self, alias: str, client) -> str | None:
|
|
if client is None:
|
|
return None
|
|
try:
|
|
resp = await client.room_resolve_alias(alias)
|
|
room_id = resp.room_id
|
|
self._update_cache(room_id, alias=alias)
|
|
return room_id
|
|
except Exception:
|
|
logger.debug("Failed to resolve alias %s", alias)
|
|
return None
|
|
|
|
def _update_cache(self, room_id: str, **kwargs) -> None:
|
|
entry = self._room_cache.setdefault(room_id, {})
|
|
entry.update(kwargs)
|
|
|
|
def clear(self) -> None:
|
|
self._room_cache.clear()
|