ForcePilot/backend/package/yuxi/channel/extensions/line/session.py

45 lines
1.4 KiB
Python
Raw Normal View History

from __future__ import annotations
import re
from yuxi.channel.extensions.line.types import LineChatType
LINE_ID_PATTERN = re.compile(r"^[UCR][a-f0-9]{32}$", re.IGNORECASE)
LINE_PREFIX_PATTERN = re.compile(r"^line:", re.IGNORECASE)
class LineSessionAdapter:
def build_dm_session_key(self, agent_id: str, account_id: str, sender_id: str) -> str:
return f"agent:{agent_id}:line:direct:{sender_id}"
def build_group_session_key(self, agent_id: str, account_id: str, group_id: str) -> str:
return f"agent:{agent_id}:line:group:{group_id}"
def build_session_key(
self,
agent_id: str,
account_id: str,
chat_type: LineChatType | str,
target_id: str,
) -> str:
chat = "direct" if chat_type in (LineChatType.DIRECT, "direct") else "group"
return f"agent:{agent_id}:line:{chat}:{target_id}"
@staticmethod
def is_valid_line_id(target_id: str) -> bool:
stripped = target_id.strip()
if LINE_PREFIX_PATTERN.match(stripped):
return True
return bool(LINE_ID_PATTERN.match(stripped))
@staticmethod
def normalize_target_id(target_id: str) -> str:
stripped = target_id.strip()
if stripped.startswith("line:"):
return stripped[5:]
if stripped.startswith("group:"):
return stripped[6:]
if stripped.startswith("room:"):
return stripped[5:]
return stripped