From d14f517db21105d265611df6c63c65be046cd4b1 Mon Sep 17 00:00:00 2001 From: Benature Date: Sat, 28 Nov 2026 18:02:01 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8C=BA=E5=88=86=E6=9C=AA=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E4=B8=8E=E6=97=A0=E6=95=B0=E6=8D=AE=E6=97=A5=E6=9C=9F?= =?UTF-8?q?=EF=BC=8C=E5=9B=9E=E8=A1=A5=E5=8F=AF=E8=87=AA=E5=8A=A8=E8=81=94?= =?UTF-8?q?=E7=BD=91=E8=A1=A5=E6=8B=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- VERSION | 2 +- backfill_summaries.py | 37 +++++++++++++++++++++++++++++++ snooper_history.py | 2 ++ snooper_storage.py | 41 ++++++++++++++++++++++++++++++++++ tests/test_history.py | 51 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 132 insertions(+), 1 deletion(-) diff --git a/VERSION b/VERSION index a45be46..1866a36 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.2.8 +0.2.9 diff --git a/backfill_summaries.py b/backfill_summaries.py index c54ac67..153057b 100755 --- a/backfill_summaries.py +++ b/backfill_summaries.py @@ -17,6 +17,7 @@ from larkx.storage.models import Message from sqlalchemy import func from snooper_client import SnifferLarkClient as LarkClient +from snooper_history import HistoryError, sync_all_chats_for_day from snooper_membership import ( MembershipError, fetch_self_join_times, @@ -111,6 +112,7 @@ def main(): parser.add_argument("--weekly-through", help="先仅补齐此日期前已结束周的周记") parser.add_argument("--refresh-tagged-from", help="重新生成此日期起带缺周报/月报标签的日报") parser.add_argument("--daily-overwrite-from", help="覆盖此日期起的全部已有日报") + parser.add_argument("--fetch-missing", action="store_true", help="对本地无消息且从未同步的日期先联网拉取,再判断是否生成") parser.add_argument("--state", default=str(DEFAULT_STATE_PATH)) args = parser.parse_args() @@ -185,6 +187,38 @@ def main(): filtered, _ = filter_rows_by_membership(rows, join_times) return bool(filtered) + def ensure_day_synced(day: date) -> None: + """Fetch a day's messages only when it has neither local data nor a sync mark.""" + if storage.is_day_synced(day.isoformat()): + return + _, day_start, day_end, tz = resolve_day(day.isoformat(), args.timezone) + rows = storage.get_received_messages( + int(day_start.timestamp()), + int(day_end.timestamp()), + exclude_chat_ids=exclude_chat_ids, + include_outgoing=True, + ) + if rows: + return + print(f"===== 联网拉取 {day} =====", flush=True) + try: + stats = sync_all_chats_for_day( + LarkClient(LarkAuth()), + storage, + day, + tz, + batch_size=50, + exclude_chat_ids=exclude_chat_ids, + ) + except HistoryError as error: + print(f"===== 联网拉取 {day} 失败: {error} =====", flush=True) + return + print( + f"===== 联网拉取 {day} 完成:消息 {stats['matched']} 条," + f"失败会话 {stats['failed']} 个 =====", + flush=True, + ) + state = { "model": args.model, "start_date": start.isoformat(), @@ -268,6 +302,9 @@ def main(): _, natural_week_end = week_bounds(current_week) day_start = max(daily_start, month_start, current_week) day_end = min(month_end, natural_week_end) + if args.fetch_missing: + for offset in range((day_end - day_start).days + 1): + ensure_day_synced(day_start + timedelta(days=offset)) for day in missing_message_dates( day_start, day_end, diff --git a/snooper_history.py b/snooper_history.py index 39b12f5..d1e1858 100644 --- a/snooper_history.py +++ b/snooper_history.py @@ -214,4 +214,6 @@ def sync_all_chats_for_day( "error_type": type(error).__name__, } ) + if not stats["failed"] and hasattr(storage, "mark_day_synced"): + storage.mark_day_synced(target_day.isoformat(), stats["matched"]) return stats diff --git a/snooper_storage.py b/snooper_storage.py index 4fe2bd0..d9377f3 100644 --- a/snooper_storage.py +++ b/snooper_storage.py @@ -26,6 +26,17 @@ class SyncProgress(Base): updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now) +class DaySyncState(Base): + """Whether a calendar day has been fully synced, regardless of message count.""" + + __tablename__ = "day_sync_state" + + sync_date = Column(String(10), primary_key=True) + completed = Column(Integer, default=0) + message_count = Column(Integer, default=0) + updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now) + + class SnifferStorage(Storage): def __init__(self, url: str | None = None): if url is None and not os.environ.get("LARKX_STORAGE_URL"): @@ -247,3 +258,33 @@ class SnifferStorage(Storage): session.commit() finally: session.close() + + def mark_day_synced(self, sync_date: str, message_count: int) -> None: + """Record that a calendar day has been fully synced (even with 0 messages).""" + session = self.Session() + try: + row = ( + session.query(DaySyncState) + .filter_by(sync_date=sync_date) + .first() + ) + if not row: + row = DaySyncState(sync_date=sync_date) + session.add(row) + row.completed = 1 + row.message_count = int(message_count) + session.commit() + finally: + session.close() + + def is_day_synced(self, sync_date: str) -> bool: + session = self.Session() + try: + row = ( + session.query(DaySyncState) + .filter_by(sync_date=sync_date) + .first() + ) + return bool(row and row.completed) + finally: + session.close() diff --git a/tests/test_history.py b/tests/test_history.py index db11212..bef2e2d 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -138,6 +138,57 @@ def test_sync_all_chats_for_day_excludes_configured_chat_before_history_pull(): assert storage.get_messages("private-b") == [] +def test_sync_marks_day_synced_when_no_failures(): + from snooper_history import sync_all_chats_for_day + + tz = ZoneInfo("Asia/Shanghai") + start_ts = 1_792_000_000 + client = FakeClient(start_ts) + client.auth = type("Auth", (), {"user_id": "self"})() + storage = Storage(url="sqlite:///:memory:") + + stats = sync_all_chats_for_day( + client, + storage, + date(2026, 11, 3), + tz, + batch_size=2, + start_ts=start_ts, + end_ts=start_ts + 86_400, + ) + + assert stats["failed"] == 0 + assert storage.is_day_synced("2026-11-03") is True + assert storage.is_day_synced("2026-11-04") is False + + +def test_sync_does_not_mark_day_synced_when_failures(): + from snooper_history import sync_all_chats_for_day + + class FailingClient(FakeClient): + def pull_history(self, chat_id, positions, **kwargs): + raise RuntimeError("合成失败") + + tz = ZoneInfo("Asia/Shanghai") + start_ts = 1_792_000_000 + client = FailingClient(start_ts) + client.auth = type("Auth", (), {"user_id": "self"})() + storage = Storage(url="sqlite:///:memory:") + + stats = sync_all_chats_for_day( + client, + storage, + date(2026, 11, 3), + tz, + batch_size=2, + start_ts=start_ts, + end_ts=start_ts + 86_400, + ) + + assert stats["failed"] >= 1 + assert storage.is_day_synced("2026-11-03") is False + + def test_history_failure_log_identifies_chat_without_sensitive_error_body(tmp_path): from snooper_history import ( format_history_failures,