"""Read-only Feishu history sync with date-bounded pagination and private counters.""" from __future__ import annotations from datetime import date, datetime, time, timedelta from typing import Any from zoneinfo import ZoneInfo from .proto import decoders class HistoryError(RuntimeError): """History synchronization failed without exposing message content.""" def _feed_chats(client: Any, page_size: int = 50, max_pages: int = 100): cursor = None seen: set[str] = set() for _ in range(max_pages): request = { "type": "INBOX", "count": page_size, "pullType": "REFRESH" if cursor is None else "LOAD_MORE", "pullFeedType": "ALL", "businessType": "LARK", "withMessageEntity": True, "useMsCursor": True, } if cursor is not None: request["cursor"] = cursor response = client.api("feed.PullFeedCardsRequest", request) or {} response_chats = response.get("chats") or {} for card in response.get("cards", []): if card.get("type") not in (1, "CHAT", 7, "TOPIC"): continue if card.get("status") in (3, "DELETED") or card.get("isHide"): continue chat_id = str(card.get("id") or "") if chat_id and chat_id in response_chats and chat_id not in seen: seen.add(chat_id) yield response_chats[chat_id] next_cursor = response.get("nextCursor") if not next_cursor: return if cursor is not None and int(next_cursor) == int(cursor): raise HistoryError("会话分页游标没有前进。") cursor = int(next_cursor) raise HistoryError("会话分页超过安全页数上限。") def sync_all_chats_for_day( client: Any, storage: Any, target_day: date, tz: ZoneInfo, batch_size: int = 50, start_ts: int | None = None, end_ts: int | None = None, ) -> dict[str, int]: """Save one natural day from every visible INBOX chat; never print content.""" if not 1 <= batch_size <= 200: raise HistoryError("历史消息批次大小必须在 1 到 200 之间。") if start_ts is None: start = datetime.combine(target_day, time.min, tzinfo=tz) start_ts = int(start.timestamp()) if end_ts is None: end = datetime.combine(target_day + timedelta(days=1), time.min, tzinfo=tz) end_ts = int(end.timestamp()) own_id = str(getattr(client.auth, "user_id", "") or "") chats = list(_feed_chats(client, page_size=50)) stats = { "chats": len(chats), "scanned": 0, "empty": 0, "matched": 0, "saved": 0, "failed": 0, "requests": 0, } for chat in chats: chat_id = str(chat.get("id") or "") upper = int(chat.get("lastMessagePosition") or 0) floor = max(1, int(chat.get("firstChatMessagePosition") or 1)) if not chat_id or upper < floor: stats["empty"] += 1 continue stats["scanned"] += 1 try: batches = 0 while upper >= floor: if batches >= 100: raise HistoryError("单会话历史分页超过安全批次上限。") lower = max(floor, upper - batch_size + 1) messages = client.pull_history( chat_id, list(range(lower, upper + 1)), visible_only=True, thread_chat=decoders.is_thread_chat(chat), ) stats["requests"] += 1 batches += 1 timestamps = [] for message in messages: timestamp = int(message.get("create_time") or 0) if timestamp: timestamps.append(timestamp) if start_ts <= timestamp < end_ts: stats["matched"] += 1 direction = ( "out" if own_id and str(message.get("from_id") or "") == own_id else "in" ) saved = storage.save_message( message, chat_name=chat.get("name") or "", direction=direction, ) stats["saved"] += int(bool(saved)) if timestamps and min(timestamps) < start_ts: break upper = lower - 1 except Exception: # noqa: BLE001 - isolate chat failures without exposing upstream data stats["failed"] += 1 return stats