"""Fail-closed filtering of group messages sent before the current user joined.""" from __future__ import annotations import json import os from pathlib import Path from typing import Any DEFAULT_JOIN_TIME_CACHE = Path("~/.larkx/chat-join-times.json") GROUP_TYPES = {2, 3, "2", "3", "GROUP", "TOPIC_GROUP"} class MembershipError(RuntimeError): """Membership metadata could not be verified safely.""" def is_group_row(row: Any) -> bool: return getattr(row, "chat_type", None) in GROUP_TYPES def _read_cache(path: Path) -> dict[str, int]: try: data = json.loads(path.read_text(encoding="utf-8")) except FileNotFoundError: return {} except (OSError, ValueError) as exc: raise MembershipError("无法读取入群时间缓存。") from exc if not isinstance(data, dict): raise MembershipError("入群时间缓存格式不正确。") result = {} for chat_id, timestamp in data.items(): try: value = int(timestamp) except (TypeError, ValueError): continue if value > 0: result[str(chat_id)] = value return result def _write_cache(path: Path, values: dict[str, int]) -> None: path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text( json.dumps(values, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8", ) temporary.chmod(0o600) os.replace(temporary, path) def _fetch_self_join_time(client: Any, chat_id: str, own_id: str) -> int: """Scan all member pages; zero means the successful response had no self record.""" cursor = None for _ in range(100): request = {"chatId": str(chat_id), "needChatters": True, "limit": 100} if cursor is not None: request["cursor"] = cursor try: response = client.api("chats.PullChatChattersRequest", request) or {} except Exception as exc: raise MembershipError(f"获取群聊入群时间失败: {chat_id}") from exc join_times = response.get("joinTimesSec") or {} if isinstance(join_times, dict): for member_id, timestamp in join_times.items(): if str(member_id) != own_id: continue try: value = int(timestamp) except (TypeError, ValueError) as exc: raise MembershipError(f"入群时间格式不正确: {chat_id}") from exc if value > 0: return value next_cursor = response.get("nextCursor") if not next_cursor: return 0 if cursor is not None and str(next_cursor) == str(cursor): raise MembershipError(f"入群时间分页游标没有前进: {chat_id}") cursor = next_cursor raise MembershipError(f"入群时间分页超过安全页数上限: {chat_id}") def fetch_self_join_times( client: Any, chat_ids: set[str] | list[str], cache_path: Path | str = DEFAULT_JOIN_TIME_CACHE, strict: bool = True, ) -> dict[str, int]: """Return positive join times, or zero for groups without verifiable membership.""" path = Path(cache_path).expanduser() result = _read_cache(path) own_id = str(getattr(client.auth, "user_id", "") or "") if not own_id: raise MembershipError("当前用户 ID 为空,无法校验入群时间。") pending = sorted({str(chat_id) for chat_id in chat_ids} - result.keys()) for index, chat_id in enumerate(pending, 1): try: value = _fetch_self_join_time(client, chat_id, own_id) except MembershipError: if strict: raise # Historical groups may be deleted or inaccessible; exclude them safely. value = 0 result[chat_id] = value if value > 0: # Cache only positive evidence; unknown groups are retried next time. _write_cache(path, {key: item for key, item in result.items() if item > 0}) if index % 50 == 0 or index == len(pending): print(f"入群时间检查: {index}/{len(pending)} 个群聊", flush=True) return result def filter_rows_by_membership( rows: list[Any], join_times: dict[str, int] ) -> tuple[list[Any], dict[str, int]]: """Private chats pass through; unknown group membership is excluded fail-closed.""" filtered = [] stats = { "included": 0, "excluded_before_join": 0, "excluded_unknown": 0, "excluded_chats": set(), } for row in rows: if not is_group_row(row): filtered.append(row) stats["included"] += 1 continue chat_id = str(row.chat_id) join_time = int(join_times.get(chat_id) or 0) if join_time <= 0: stats["excluded_unknown"] += 1 stats["excluded_chats"].add(chat_id) continue if int(row.create_time or 0) < join_time: stats["excluded_before_join"] += 1 stats["excluded_chats"].add(chat_id) continue filtered.append(row) stats["included"] += 1 stats["excluded_chats"] = len(stats["excluded_chats"]) return filtered, stats def filter_rows_with_membership( client: Any, rows: list[Any], cache_path: Path | str = DEFAULT_JOIN_TIME_CACHE, ) -> tuple[list[Any], dict[str, int]]: chat_ids = {str(row.chat_id) for row in rows if is_group_row(row)} join_times = fetch_self_join_times(client, chat_ids, cache_path) if chat_ids else {} return filter_rows_by_membership(rows, join_times)