ForcePilot/backend/package/yuxi/channels/adapters/matrix/crypto.py

45 lines
1.5 KiB
Python
Raw Normal View History

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