2026-11-07 11:23:50 +08:00
|
|
|
|
"""Lark Snooper queries built on the upstream LarkAgentX storage."""
|
2026-11-06 15:43:15 +08:00
|
|
|
|
|
2026-11-15 20:07:24 +08:00
|
|
|
|
import json
|
|
|
|
|
|
import os
|
2026-11-21 20:29:55 +08:00
|
|
|
|
import re
|
2026-11-07 18:46:23 +08:00
|
|
|
|
from datetime import datetime
|
2026-11-15 20:07:24 +08:00
|
|
|
|
from pathlib import Path
|
2026-11-07 18:46:23 +08:00
|
|
|
|
|
2026-11-07 11:23:50 +08:00
|
|
|
|
from larkx.storage import Storage
|
2026-11-07 18:46:23 +08:00
|
|
|
|
from larkx.storage.models import Base, Message
|
|
|
|
|
|
from sqlalchemy import BigInteger, Column, DateTime, Integer, String, asc
|
|
|
|
|
|
|
2026-11-15 20:07:24 +08:00
|
|
|
|
from snooper_client import extract_card_text
|
|
|
|
|
|
|
2026-11-07 18:46:23 +08:00
|
|
|
|
|
2026-11-21 20:29:55 +08:00
|
|
|
|
_URL_RE = re.compile(r"https?://[A-Za-z0-9./_?=&%#:-]+")
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-07 18:46:23 +08:00
|
|
|
|
class SyncProgress(Base):
|
|
|
|
|
|
__tablename__ = "sync_progress"
|
|
|
|
|
|
|
|
|
|
|
|
chat_id = Column(String(32), primary_key=True)
|
|
|
|
|
|
last_synced_date = Column(String(10), default="")
|
|
|
|
|
|
min_scanned_position = Column(Integer, default=0)
|
|
|
|
|
|
min_scanned_time = Column(BigInteger, default=0)
|
|
|
|
|
|
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
|
2026-11-06 15:43:15 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-11-28 18:02:01 +08:00
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-06 15:43:15 +08:00
|
|
|
|
class SnifferStorage(Storage):
|
2026-11-15 20:07:24 +08:00
|
|
|
|
def __init__(self, url: str | None = None):
|
|
|
|
|
|
if url is None and not os.environ.get("LARKX_STORAGE_URL"):
|
|
|
|
|
|
db_path = Path("downloads/messages.db").resolve()
|
|
|
|
|
|
url = f"sqlite:///{db_path}"
|
|
|
|
|
|
super().__init__(url)
|
|
|
|
|
|
|
2026-11-21 20:29:55 +08:00
|
|
|
|
def save_message(self, msg: dict, sender_name='', chat_name='', direction='in') -> bool:
|
|
|
|
|
|
"""Save message, preserving URLs from card content_data in plain content."""
|
|
|
|
|
|
content_data = msg.get('content_data')
|
|
|
|
|
|
if content_data and (not msg.get('content') or msg.get('content') == '[卡片]'):
|
|
|
|
|
|
urls = self._extract_urls_from_content_data(content_data)
|
|
|
|
|
|
if urls:
|
|
|
|
|
|
msg = dict(msg)
|
|
|
|
|
|
msg['content'] = '\n'.join(urls)
|
|
|
|
|
|
return super().save_message(msg, sender_name=sender_name, chat_name=chat_name, direction=direction)
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _extract_urls_from_content_data(data, urls=None):
|
|
|
|
|
|
"""Recursively extract URLs from bytes in content_data."""
|
|
|
|
|
|
if urls is None:
|
|
|
|
|
|
urls = []
|
|
|
|
|
|
if isinstance(data, bytes):
|
|
|
|
|
|
try:
|
|
|
|
|
|
text = data.decode('utf-8', errors='ignore')
|
|
|
|
|
|
urls.extend(_URL_RE.findall(text))
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
pass
|
|
|
|
|
|
elif isinstance(data, dict):
|
|
|
|
|
|
for value in data.values():
|
|
|
|
|
|
SnifferStorage._extract_urls_from_content_data(value, urls)
|
|
|
|
|
|
elif isinstance(data, (list, tuple)):
|
|
|
|
|
|
for item in data:
|
|
|
|
|
|
SnifferStorage._extract_urls_from_content_data(item, urls)
|
|
|
|
|
|
return urls
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _extract_links_with_topics(data, links=None):
|
|
|
|
|
|
"""Recursively extract URLs with their following topic text from bytes."""
|
|
|
|
|
|
if links is None:
|
|
|
|
|
|
links = []
|
|
|
|
|
|
if isinstance(data, bytes):
|
|
|
|
|
|
try:
|
|
|
|
|
|
text = data.decode('utf-8', errors='ignore')
|
|
|
|
|
|
# Match URL followed by optional protobuf field marker and topic text
|
|
|
|
|
|
pattern = re.compile(
|
|
|
|
|
|
r"(https?://[A-Za-z0-9./_?=&%#:-]+)(?:\x12\x18([\u4e00-\u9fffA-Za-z0-9_\s\-()()]+))?"
|
|
|
|
|
|
)
|
|
|
|
|
|
for match in pattern.finditer(text):
|
|
|
|
|
|
url = match.group(1)
|
|
|
|
|
|
topic = match.group(2).strip() if match.group(2) else ""
|
|
|
|
|
|
links.append({"url": url, "topic": topic})
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
pass
|
|
|
|
|
|
elif isinstance(data, dict):
|
|
|
|
|
|
for value in data.values():
|
|
|
|
|
|
SnifferStorage._extract_links_with_topics(value, links)
|
|
|
|
|
|
elif isinstance(data, (list, tuple)):
|
|
|
|
|
|
for item in data:
|
|
|
|
|
|
SnifferStorage._extract_links_with_topics(item, links)
|
|
|
|
|
|
return links
|
|
|
|
|
|
|
2026-11-07 18:46:23 +08:00
|
|
|
|
def get_received_messages(
|
2026-11-08 23:45:44 +08:00
|
|
|
|
self,
|
|
|
|
|
|
start_ts: int,
|
|
|
|
|
|
end_ts: int,
|
|
|
|
|
|
chat_ids=None,
|
|
|
|
|
|
exclude_chat_ids=None,
|
|
|
|
|
|
include_outgoing: bool = False,
|
2026-11-07 18:46:23 +08:00
|
|
|
|
):
|
2026-11-08 23:45:44 +08:00
|
|
|
|
"""Return dated messages, optionally including current-user replies."""
|
2026-11-06 15:43:15 +08:00
|
|
|
|
session = self.Session()
|
|
|
|
|
|
try:
|
|
|
|
|
|
query = session.query(Message).filter(
|
|
|
|
|
|
Message.create_time >= int(start_ts),
|
|
|
|
|
|
Message.create_time < int(end_ts),
|
|
|
|
|
|
)
|
2026-11-08 23:45:44 +08:00
|
|
|
|
if not include_outgoing:
|
|
|
|
|
|
query = query.filter(Message.direction == "in")
|
2026-11-06 15:43:15 +08:00
|
|
|
|
if chat_ids:
|
|
|
|
|
|
query = query.filter(
|
|
|
|
|
|
Message.chat_id.in_([str(chat_id) for chat_id in chat_ids])
|
|
|
|
|
|
)
|
2026-11-07 18:46:23 +08:00
|
|
|
|
if exclude_chat_ids:
|
|
|
|
|
|
query = query.filter(
|
|
|
|
|
|
~Message.chat_id.in_(
|
|
|
|
|
|
[str(chat_id) for chat_id in exclude_chat_ids]
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
2026-11-06 15:43:15 +08:00
|
|
|
|
return query.order_by(asc(Message.create_time), asc(Message.id)).all()
|
|
|
|
|
|
finally:
|
|
|
|
|
|
session.close()
|
2026-11-07 18:46:23 +08:00
|
|
|
|
|
2026-11-15 20:07:24 +08:00
|
|
|
|
def backfill_card_text(self) -> int:
|
|
|
|
|
|
"""Populate readable text for card rows saved by the old decoder once."""
|
|
|
|
|
|
session = self.Session()
|
|
|
|
|
|
updated = 0
|
|
|
|
|
|
try:
|
|
|
|
|
|
rows = session.query(Message).filter(Message.msg_type == 14).all()
|
|
|
|
|
|
for row in rows:
|
|
|
|
|
|
if not row.content_data:
|
|
|
|
|
|
continue
|
|
|
|
|
|
try:
|
|
|
|
|
|
data = json.loads(row.content_data)
|
|
|
|
|
|
text = extract_card_text(data)
|
|
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
|
|
continue
|
|
|
|
|
|
if text and text not in (row.content or ""):
|
|
|
|
|
|
row.content = f"{row.content or '[卡片]'}\n{text}"
|
|
|
|
|
|
updated += 1
|
|
|
|
|
|
if updated:
|
|
|
|
|
|
session.commit()
|
|
|
|
|
|
return updated
|
|
|
|
|
|
finally:
|
|
|
|
|
|
session.close()
|
|
|
|
|
|
|
2026-11-07 18:46:23 +08:00
|
|
|
|
def has_messages_for_day(
|
|
|
|
|
|
self, start_ts: int, end_ts: int, chat_ids=None, exclude_chat_ids=None
|
|
|
|
|
|
) -> bool:
|
|
|
|
|
|
"""Check whether any messages already exist for the target day."""
|
|
|
|
|
|
session = self.Session()
|
|
|
|
|
|
try:
|
|
|
|
|
|
query = session.query(Message.id).filter(
|
|
|
|
|
|
Message.create_time >= int(start_ts),
|
|
|
|
|
|
Message.create_time < int(end_ts),
|
|
|
|
|
|
)
|
|
|
|
|
|
if chat_ids:
|
|
|
|
|
|
query = query.filter(
|
|
|
|
|
|
Message.chat_id.in_([str(chat_id) for chat_id in chat_ids])
|
|
|
|
|
|
)
|
|
|
|
|
|
if exclude_chat_ids:
|
|
|
|
|
|
query = query.filter(
|
|
|
|
|
|
~Message.chat_id.in_(
|
|
|
|
|
|
[str(chat_id) for chat_id in exclude_chat_ids]
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
|
|
|
|
|
return query.first() is not None
|
|
|
|
|
|
finally:
|
|
|
|
|
|
session.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-08 11:31:18 +08:00
|
|
|
|
def mark_messages_read(self, message_ids: list[int], read: bool = True) -> int:
|
|
|
|
|
|
"""按自增 id 批量标记已读/未读,返回更新条数。"""
|
|
|
|
|
|
if not message_ids:
|
|
|
|
|
|
return 0
|
|
|
|
|
|
session = self.Session()
|
|
|
|
|
|
try:
|
|
|
|
|
|
count = (
|
|
|
|
|
|
session.query(Message)
|
|
|
|
|
|
.filter(Message.id.in_([int(mid) for mid in message_ids]))
|
|
|
|
|
|
.update({Message.is_read: read}, synchronize_session=False)
|
|
|
|
|
|
)
|
|
|
|
|
|
session.commit()
|
|
|
|
|
|
return count
|
|
|
|
|
|
finally:
|
|
|
|
|
|
session.close()
|
|
|
|
|
|
|
|
|
|
|
|
def get_unread_messages(
|
|
|
|
|
|
self, start_ts: int, end_ts: int, chat_ids=None, exclude_chat_ids=None
|
|
|
|
|
|
):
|
|
|
|
|
|
"""Return unread incoming messages in [start_ts, end_ts)."""
|
|
|
|
|
|
session = self.Session()
|
|
|
|
|
|
try:
|
|
|
|
|
|
query = session.query(Message).filter(
|
|
|
|
|
|
Message.direction == "in",
|
|
|
|
|
|
Message.is_read == False,
|
|
|
|
|
|
Message.create_time >= int(start_ts),
|
|
|
|
|
|
Message.create_time < int(end_ts),
|
|
|
|
|
|
)
|
|
|
|
|
|
if chat_ids:
|
|
|
|
|
|
query = query.filter(
|
|
|
|
|
|
Message.chat_id.in_([str(chat_id) for chat_id in chat_ids])
|
|
|
|
|
|
)
|
|
|
|
|
|
if exclude_chat_ids:
|
|
|
|
|
|
query = query.filter(
|
|
|
|
|
|
~Message.chat_id.in_(
|
|
|
|
|
|
[str(chat_id) for chat_id in exclude_chat_ids]
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
|
|
|
|
|
return query.order_by(asc(Message.create_time), asc(Message.id)).all()
|
|
|
|
|
|
finally:
|
|
|
|
|
|
session.close()
|
|
|
|
|
|
|
2026-11-07 18:46:23 +08:00
|
|
|
|
def get_sync_progress(self, chat_id: str) -> SyncProgress | None:
|
|
|
|
|
|
session = self.Session()
|
|
|
|
|
|
try:
|
|
|
|
|
|
return (
|
|
|
|
|
|
session.query(SyncProgress)
|
|
|
|
|
|
.filter_by(chat_id=str(chat_id))
|
|
|
|
|
|
.first()
|
|
|
|
|
|
)
|
|
|
|
|
|
finally:
|
|
|
|
|
|
session.close()
|
|
|
|
|
|
|
|
|
|
|
|
def update_sync_progress(
|
|
|
|
|
|
self,
|
|
|
|
|
|
chat_id: str,
|
|
|
|
|
|
synced_date: str,
|
|
|
|
|
|
min_position: int,
|
|
|
|
|
|
min_time: int,
|
|
|
|
|
|
) -> None:
|
|
|
|
|
|
session = self.Session()
|
|
|
|
|
|
try:
|
|
|
|
|
|
row = (
|
|
|
|
|
|
session.query(SyncProgress)
|
|
|
|
|
|
.filter_by(chat_id=str(chat_id))
|
|
|
|
|
|
.first()
|
|
|
|
|
|
)
|
|
|
|
|
|
if not row:
|
|
|
|
|
|
row = SyncProgress(chat_id=str(chat_id))
|
|
|
|
|
|
session.add(row)
|
|
|
|
|
|
row.last_synced_date = synced_date
|
|
|
|
|
|
if min_position and (
|
|
|
|
|
|
not row.min_scanned_position
|
|
|
|
|
|
or min_position < row.min_scanned_position
|
|
|
|
|
|
):
|
|
|
|
|
|
row.min_scanned_position = min_position
|
|
|
|
|
|
row.min_scanned_time = min_time
|
|
|
|
|
|
session.commit()
|
|
|
|
|
|
finally:
|
|
|
|
|
|
session.close()
|
2026-11-28 18:02:01 +08:00
|
|
|
|
|
|
|
|
|
|
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()
|