48 lines
1.5 KiB
Python
48 lines
1.5 KiB
Python
"""Conversation id helpers for Douyin IM."""
|
|
|
|
|
|
def parse_conversation_parts(conversation_id: str) -> tuple[int, int] | None:
|
|
parts = (conversation_id or "").split(":")
|
|
if len(parts) >= 4 and parts[0] == "0" and parts[1] == "1":
|
|
try:
|
|
return int(parts[2]), int(parts[3])
|
|
except (TypeError, ValueError):
|
|
return None
|
|
return None
|
|
|
|
|
|
def resolve_peer_uid(conversation_id: str, my_uid: int) -> int | None:
|
|
"""Resolve peer user id from conversation id or bare numeric id."""
|
|
raw = (conversation_id or "").strip()
|
|
if not raw:
|
|
return None
|
|
|
|
parts = parse_conversation_parts(raw)
|
|
if parts:
|
|
uid1, uid2 = parts
|
|
if my_uid and uid1 == my_uid:
|
|
return uid2
|
|
if my_uid and uid2 == my_uid:
|
|
return uid1
|
|
# 0:1:{my}:{peer} — 若 my_uid 与首段不一致,仍取末段为对方
|
|
return uid2
|
|
|
|
if raw.isdigit():
|
|
peer = int(raw)
|
|
if my_uid and peer == my_uid:
|
|
return None
|
|
return peer
|
|
return None
|
|
|
|
|
|
def build_conversation_id(my_uid: int, peer_uid: int) -> str:
|
|
return f"0:1:{int(my_uid)}:{int(peer_uid)}"
|
|
|
|
|
|
def normalize_conversation_id(conversation_id: str, my_uid: int) -> str:
|
|
"""Ensure conversation id uses current account uid as first participant."""
|
|
peer_uid = resolve_peer_uid(conversation_id, my_uid)
|
|
if peer_uid and my_uid:
|
|
return build_conversation_id(my_uid, peer_uid)
|
|
return (conversation_id or "").strip()
|