170 lines
6.4 KiB
Python
170 lines
6.4 KiB
Python
"""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 larkx.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,
|
||
chat_ids: list[str] | None = None,
|
||
exclude_chat_ids: list[str] | None = None,
|
||
force: bool = False,
|
||
) -> 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))
|
||
if chat_ids:
|
||
requested = {str(chat_id) for chat_id in chat_ids}
|
||
chats = [chat for chat in chats if str(chat.get("id") or "") in requested]
|
||
if exclude_chat_ids:
|
||
excluded = {str(chat_id) for chat_id in exclude_chat_ids}
|
||
chats = [chat for chat in chats if str(chat.get("id") or "") not in excluded]
|
||
stats = {
|
||
"chats": len(chats),
|
||
"scanned": 0,
|
||
"empty": 0,
|
||
"matched": 0,
|
||
"saved": 0,
|
||
"failed": 0,
|
||
"requests": 0,
|
||
"skipped": 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
|
||
|
||
progress = None
|
||
if not force:
|
||
progress = storage.get_sync_progress(chat_id)
|
||
if progress and progress.last_synced_date == target_day.isoformat():
|
||
stats["skipped"] += 1
|
||
continue
|
||
|
||
# 如果目标日期完全早于已扫描范围,从断点继续往前拉,避免从最新position重扫
|
||
if (
|
||
progress
|
||
and progress.min_scanned_time
|
||
and end_ts <= progress.min_scanned_time
|
||
and progress.min_scanned_position > floor
|
||
):
|
||
upper = min(upper, progress.min_scanned_position - 1)
|
||
if upper < floor:
|
||
stats["skipped"] += 1
|
||
continue
|
||
|
||
stats["scanned"] += 1
|
||
try:
|
||
batches = 0
|
||
min_position_scanned = upper
|
||
min_time_scanned = 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
|
||
min_position_scanned = min(min_position_scanned, lower)
|
||
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:
|
||
batch_min_time = min(timestamps)
|
||
if not min_time_scanned or batch_min_time < min_time_scanned:
|
||
min_time_scanned = batch_min_time
|
||
if batch_min_time < start_ts:
|
||
break
|
||
upper = lower - 1
|
||
storage.update_sync_progress(
|
||
chat_id,
|
||
target_day.isoformat(),
|
||
min_position_scanned,
|
||
min_time_scanned,
|
||
)
|
||
except Exception: # noqa: BLE001 - isolate chat failures without exposing upstream data
|
||
stats["failed"] += 1
|
||
return stats
|