ForcePilot/backend/package/yuxi/channels/adapters/matrix/crypto.py
Kris 2063145ce1 feat(matrix): 新增完整的Matrix适配器工具集
新增了20+个Matrix相关工具模块,包含线程处理、自动加入、消息去重、配置管理、安全策略、媒体处理、命令解析等功能,完善Matrix适配器基础能力
2026-05-12 00:45:54 +08:00

45 lines
1.5 KiB
Python

from __future__ import annotations
import json
import os
from typing import TYPE_CHECKING
from yuxi.utils.logging_config import logger
if TYPE_CHECKING:
from nio import AsyncClient
async def import_room_keys(client: AsyncClient, store_path: str) -> None:
keys_file = os.path.join(store_path, "room_keys.json")
if not os.path.exists(keys_file):
return
try:
with open(keys_file, encoding="utf-8") as f:
keys_data = json.load(f)
if isinstance(keys_data, dict) and "rooms" in keys_data:
await client.import_room_keys(keys_file)
logger.info("Matrix room keys imported successfully")
else:
logger.warning("Matrix room keys file exists but has unexpected format")
except json.JSONDecodeError as e:
logger.error(f"Matrix room keys file is corrupted: {e}")
except OSError as e:
logger.error(f"Matrix room keys file read error: {e}")
except Exception as e:
logger.error(f"Matrix room keys import failed: {e}")
async def export_room_keys(client: AsyncClient, store_path: str) -> bool:
dest_file = os.path.join(store_path, "room_keys.json")
try:
os.makedirs(store_path, exist_ok=True)
resp = await client.export_room_keys(dest_file)
logger.info(f"Matrix room keys exported to {dest_file}, count: {getattr(resp, 'count', 'unknown')}")
return True
except Exception as e:
logger.error(f"Matrix room keys export failed: {e}")
return False