2026-11-05 22:18:12 +08:00
|
|
|
|
"""Read-only Feishu history sync with date-bounded pagination and private counters."""
|
|
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
2026-11-08 11:31:18 +08:00
|
|
|
|
import json
|
|
|
|
|
|
import os
|
|
|
|
|
|
from datetime import date, datetime, time, timedelta, timezone
|
|
|
|
|
|
from pathlib import Path
|
2026-11-05 22:18:12 +08:00
|
|
|
|
from typing import Any
|
|
|
|
|
|
from zoneinfo import ZoneInfo
|
|
|
|
|
|
|
2026-11-08 11:31:18 +08:00
|
|
|
|
from larkx.config import DATA_DIR
|
2026-11-06 15:43:15 +08:00
|
|
|
|
from larkx.proto import decoders
|
2026-11-05 22:18:12 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class HistoryError(RuntimeError):
|
|
|
|
|
|
"""History synchronization failed without exposing message content."""
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-08 11:31:18 +08:00
|
|
|
|
def format_history_failures(failures: list[dict[str, str]]) -> str:
|
|
|
|
|
|
"""Format useful failure metadata without upstream response bodies."""
|
|
|
|
|
|
return ";".join(
|
|
|
|
|
|
f"{failure['chat_name'] or '<未命名会话>'} "
|
|
|
|
|
|
f"({failure['chat_id']}): {failure['error_type']}"
|
|
|
|
|
|
for failure in failures
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def write_history_failures(
|
|
|
|
|
|
target_day: date, failures: list[dict[str, str]], path: Path | str | None = None
|
|
|
|
|
|
) -> Path:
|
|
|
|
|
|
"""Append private JSONL failure metadata for later diagnosis."""
|
|
|
|
|
|
destination = (
|
|
|
|
|
|
Path(path).expanduser()
|
|
|
|
|
|
if path is not None
|
|
|
|
|
|
else DATA_DIR / "logs" / "history-failures.jsonl"
|
|
|
|
|
|
)
|
|
|
|
|
|
if not failures:
|
|
|
|
|
|
return destination
|
|
|
|
|
|
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
|
|
|
|
fd = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
|
|
|
|
with os.fdopen(fd, "a", encoding="utf-8") as handle:
|
|
|
|
|
|
for failure in failures:
|
|
|
|
|
|
record = {
|
|
|
|
|
|
"logged_at": datetime.now(timezone.utc).isoformat(),
|
|
|
|
|
|
"date": target_day.isoformat(),
|
|
|
|
|
|
**failure,
|
|
|
|
|
|
}
|
|
|
|
|
|
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
|
|
|
|
|
|
destination.chmod(0o600)
|
|
|
|
|
|
return destination
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-05 22:18:12 +08:00
|
|
|
|
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,
|
2026-11-06 00:04:11 +08:00
|
|
|
|
chat_ids: list[str] | None = None,
|
2026-11-07 18:46:23 +08:00
|
|
|
|
exclude_chat_ids: list[str] | None = None,
|
|
|
|
|
|
force: bool = False,
|
2026-11-08 11:31:18 +08:00
|
|
|
|
chats: list[dict] | None = None,
|
|
|
|
|
|
) -> dict[str, Any]:
|
|
|
|
|
|
"""Save one natural day and retain safe failure metadata, never content."""
|
2026-11-05 22:18:12 +08:00
|
|
|
|
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 "")
|
2026-11-08 11:31:18 +08:00
|
|
|
|
if chats is None:
|
|
|
|
|
|
chats = list(_feed_chats(client, page_size=50))
|
2026-11-06 00:04:11 +08:00
|
|
|
|
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]
|
2026-11-07 18:46:23 +08:00
|
|
|
|
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]
|
2026-11-05 22:18:12 +08:00
|
|
|
|
stats = {
|
|
|
|
|
|
"chats": len(chats),
|
|
|
|
|
|
"scanned": 0,
|
|
|
|
|
|
"empty": 0,
|
|
|
|
|
|
"matched": 0,
|
|
|
|
|
|
"saved": 0,
|
|
|
|
|
|
"failed": 0,
|
|
|
|
|
|
"requests": 0,
|
2026-11-07 18:46:23 +08:00
|
|
|
|
"skipped": 0,
|
2026-11-08 11:31:18 +08:00
|
|
|
|
"failures": [],
|
2026-11-05 22:18:12 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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
|
2026-11-07 18:46:23 +08:00
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
2026-11-05 22:18:12 +08:00
|
|
|
|
stats["scanned"] += 1
|
|
|
|
|
|
try:
|
|
|
|
|
|
batches = 0
|
2026-11-07 18:46:23 +08:00
|
|
|
|
min_position_scanned = upper
|
|
|
|
|
|
min_time_scanned = 0
|
2026-11-05 22:18:12 +08:00
|
|
|
|
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
|
2026-11-07 18:46:23 +08:00
|
|
|
|
min_position_scanned = min(min_position_scanned, lower)
|
2026-11-05 22:18:12 +08:00
|
|
|
|
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))
|
2026-11-07 18:46:23 +08:00
|
|
|
|
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
|
2026-11-05 22:18:12 +08:00
|
|
|
|
upper = lower - 1
|
2026-11-07 18:46:23 +08:00
|
|
|
|
storage.update_sync_progress(
|
|
|
|
|
|
chat_id,
|
|
|
|
|
|
target_day.isoformat(),
|
|
|
|
|
|
min_position_scanned,
|
|
|
|
|
|
min_time_scanned,
|
|
|
|
|
|
)
|
2026-11-08 11:31:18 +08:00
|
|
|
|
except Exception as error: # noqa: BLE001 - isolate chats without exposing content
|
2026-11-05 22:18:12 +08:00
|
|
|
|
stats["failed"] += 1
|
2026-11-08 11:31:18 +08:00
|
|
|
|
stats["failures"].append(
|
|
|
|
|
|
{
|
|
|
|
|
|
"chat_id": chat_id,
|
|
|
|
|
|
"chat_name": str(chat.get("name") or ""),
|
|
|
|
|
|
"error_type": type(error).__name__,
|
|
|
|
|
|
}
|
|
|
|
|
|
)
|
2026-11-05 22:18:12 +08:00
|
|
|
|
return stats
|