72 lines
2.3 KiB
Python
72 lines
2.3 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
from yuxi.utils.logging_config import logger
|
||
|
|
|
||
|
|
|
||
|
|
class WeChatConversationBindingAdapter:
|
||
|
|
def __init__(self):
|
||
|
|
self._parent_map: dict[str, str] = {}
|
||
|
|
self._child_map: dict[str, list[str]] = {}
|
||
|
|
|
||
|
|
def bind_conversation(
|
||
|
|
self,
|
||
|
|
child_id: str,
|
||
|
|
parent_id: str,
|
||
|
|
) -> None:
|
||
|
|
self._parent_map[child_id] = parent_id
|
||
|
|
self._child_map.setdefault(parent_id, []).append(child_id)
|
||
|
|
logger.debug(f"[WeChat/ConvBind] Bound conversation: {child_id} → {parent_id}")
|
||
|
|
|
||
|
|
def unbind_conversation(self, child_id: str) -> bool:
|
||
|
|
parent = self._parent_map.pop(child_id, None)
|
||
|
|
if parent and parent in self._child_map:
|
||
|
|
children = self._child_map[parent]
|
||
|
|
if child_id in children:
|
||
|
|
children.remove(child_id)
|
||
|
|
if not children:
|
||
|
|
self._child_map.pop(parent, None)
|
||
|
|
return parent is not None
|
||
|
|
|
||
|
|
def get_parent(self, conversation_id: str) -> str | None:
|
||
|
|
return self._parent_map.get(conversation_id)
|
||
|
|
|
||
|
|
def get_children(self, parent_id: str) -> list[str]:
|
||
|
|
return list(self._child_map.get(parent_id, []))
|
||
|
|
|
||
|
|
def resolve_parent_conversation_candidates(
|
||
|
|
self,
|
||
|
|
chat_id: str,
|
||
|
|
sender_id: str,
|
||
|
|
) -> list[str]:
|
||
|
|
candidates = [f"chat:{chat_id}", f"direct:{sender_id}"]
|
||
|
|
parent_from_chat = self._parent_map.get(chat_id)
|
||
|
|
if parent_from_chat:
|
||
|
|
candidates.insert(0, parent_from_chat)
|
||
|
|
parent_from_sender = self._parent_map.get(sender_id)
|
||
|
|
if parent_from_sender and parent_from_sender not in candidates:
|
||
|
|
candidates.insert(0, parent_from_sender)
|
||
|
|
return candidates
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def resolve_inbound_conversation(
|
||
|
|
chat_id: str,
|
||
|
|
chat_type: str = "direct",
|
||
|
|
) -> str:
|
||
|
|
return f"{chat_type}:{chat_id}"
|
||
|
|
|
||
|
|
def list_bindings(self) -> list[dict[str, Any]]:
|
||
|
|
return [
|
||
|
|
{
|
||
|
|
"child_id": child,
|
||
|
|
"parent_id": parent,
|
||
|
|
"sibling_count": len(self._child_map.get(parent, [])) - 1,
|
||
|
|
}
|
||
|
|
for child, parent in self._parent_map.items()
|
||
|
|
]
|
||
|
|
|
||
|
|
def clear(self) -> None:
|
||
|
|
self._parent_map.clear()
|
||
|
|
self._child_map.clear()
|