35bfebd3e3
- 9b0d0c133035: wechat_account.list_order 进迁移链(此前仅模型声明, 干净库 /api/accounts 即 500);sa.inspect 幂等守卫兼容已手动加列的 smoke.db - fe63c6789e94(验证中发现的预存缺口,超出原清单): Task 14 的 5 列模型 类型修正(4×URL String(1024)→Text, db_size Integer→BigInteger)从未落 链——纯 alembic 新库会复活 >1KB 链接截断;对齐后干净库 alembic check 全绿。SQLite message 表 batch 重建会掉 FTS 触发器+rowid 脱节(docstring 记明 ensure_fts+rebuild_fts 修复,smoke.db 已修复验证) - scrape_via_page: _iter_moments_pages 每页一行进度日志(镜像 _fetch_pages) - messages: MsgTypeParam=Literal[tuple(_MSG_TYPE_FILTER)] 派生,杜绝 双处罗列漂移(openapi enum 验证一致,492 绿含 422 行为) - 文档: ChatGroup 复合PK docstring/groups room_id 多行表述/测试名去 单行假设;Dockerfile 补 alembic.ini+migrations;DEPLOY 增「数据库 迁移」节(新库/旧库stamp路径/回填脚本显式DB_URL)+运维表升级行 Co-Authored-By: Claude <noreply@anthropic.com>
114 lines
4.3 KiB
Python
114 lines
4.3 KiB
Python
"""GET /api/messages — chat timeline list (WeChat + WhatsApp).
|
|
|
|
Read-only query over the mirrored ``message`` table. Filters:
|
|
|
|
* ``channel`` — ``wechat`` / ``whatsapp``.
|
|
* ``owner_account_id`` — owning staff account (wxId / uid).
|
|
* ``talker_id`` (1:1) OR ``room_id`` (group) — the conversation anchor. Both
|
|
may be supplied (AND), but typically the frontend sends exactly one.
|
|
* ``start`` / ``end`` — ms-epoch window compared against ``timestamp``
|
|
(inclusive on both ends).
|
|
* ``msg_type`` — normalized type label (``text`` / ``image`` / ...,
|
|
see ``_MSG_TYPE_FILTER``). Unknown values are rejected with 422.
|
|
* ``q`` — substring match on ``text`` (``%``/``_`` escaped
|
|
as literals).
|
|
|
|
Ordered by ``timestamp asc`` so the timeline renders oldest-first. The index
|
|
``ix_message_channel_owner_talker_time`` covers the hot path
|
|
``(channel, owner_account_id, talker_id, timestamp)``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Annotated, Literal
|
|
|
|
import sqlalchemy as sa
|
|
from fastapi import APIRouter, Depends, Query
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.api.deps import get_session
|
|
from app.api.schemas import MessageOut, Page
|
|
from app.db.models import Message
|
|
|
|
router = APIRouter(prefix="/api", tags=["messages"])
|
|
|
|
SessionDep = Annotated[AsyncSession, Depends(get_session)]
|
|
PageParam = Annotated[int, Query(ge=1)]
|
|
PageSizeParam = Annotated[int, Query(ge=1, le=100)]
|
|
|
|
# msg_type 参数值 → 覆盖的 Message.type 标签集合(对齐云客 10 类下拉;
|
|
# mini_program 暂无样本行也保留, 查空是数据现实)
|
|
_MSG_TYPE_FILTER: dict[str, tuple[str, ...]] = {
|
|
"text": ("text",),
|
|
"image": ("image", "image_legacy"),
|
|
"voice": ("voice",),
|
|
"video": ("video",),
|
|
"link": ("link",),
|
|
"file": ("file",),
|
|
"red_packet": ("red_packet",),
|
|
"transfer": ("transfer",),
|
|
"voice_call": ("voice_call",),
|
|
"video_call": ("video_call",),
|
|
"mini_program": ("mini_program",),
|
|
}
|
|
|
|
# 派生而非重复罗列:加一类只改上面的 dict,Literal 与 422 校验自动跟上
|
|
# (两处手写曾会漂移——漏一边即 500/422 不一致)
|
|
MsgTypeParam = Literal[tuple(_MSG_TYPE_FILTER)]
|
|
|
|
|
|
@router.get("/messages")
|
|
async def list_messages(
|
|
session: SessionDep,
|
|
page: PageParam = 1,
|
|
page_size: PageSizeParam = 50,
|
|
channel: Annotated[str | None, Query()] = None,
|
|
owner_account_id: Annotated[str | None, Query()] = None,
|
|
talker_id: Annotated[str | None, Query()] = None,
|
|
room_id: Annotated[str | None, Query()] = None,
|
|
start: Annotated[int | None, Query(ge=0)] = None,
|
|
end: Annotated[int | None, Query(ge=0)] = None,
|
|
msg_type: Annotated[MsgTypeParam | None, Query()] = None,
|
|
q: Annotated[str | None, Query()] = None,
|
|
) -> Page[MessageOut]:
|
|
"""List messages for a timeline (ordered by ``timestamp asc``)."""
|
|
conditions = []
|
|
if channel is not None:
|
|
conditions.append(Message.channel == channel)
|
|
if owner_account_id is not None:
|
|
conditions.append(Message.owner_account_id == owner_account_id)
|
|
if talker_id is not None:
|
|
conditions.append(Message.talker_id == talker_id)
|
|
if room_id is not None:
|
|
conditions.append(Message.room_id == room_id)
|
|
if start is not None:
|
|
conditions.append(Message.timestamp >= start)
|
|
if end is not None:
|
|
conditions.append(Message.timestamp <= end)
|
|
if msg_type is not None:
|
|
conditions.append(Message.type.in_(_MSG_TYPE_FILTER[msg_type]))
|
|
if q:
|
|
# LIKE 通配符转义: %/_ 按字面匹配
|
|
escaped = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
|
conditions.append(Message.text.like(f"%{escaped}%", escape="\\"))
|
|
|
|
total_stmt = sa.select(sa.func.count()).select_from(Message)
|
|
if conditions:
|
|
total_stmt = total_stmt.where(*conditions)
|
|
total = (await session.execute(total_stmt)).scalar_one()
|
|
|
|
list_stmt = sa.select(Message)
|
|
if conditions:
|
|
list_stmt = list_stmt.where(*conditions)
|
|
list_stmt = (
|
|
list_stmt.order_by(
|
|
sa.nullslast(Message.timestamp.asc()),
|
|
Message.msg_id.asc(),
|
|
)
|
|
.limit(page_size)
|
|
.offset((page - 1) * page_size)
|
|
)
|
|
rows = (await session.execute(list_stmt)).scalars().all()
|
|
items = [MessageOut.model_validate(row) for row in rows]
|
|
return Page(items=items, total=total, page=page, page_size=page_size)
|