修复聊天状态并完善风控浏览器诊断
修复内容: - 持久化聊天消息已读状态与未读边界,过滤系统通知红点,修正实时消息 ID、已读回执和前端徽标显示 - 完善账号级任务、商品接口和消息调度联动,补充相关服务端与引擎测试 - 新增 token 风控诊断包,保存页面、截图、Frame、选择器、网络事件和完整指纹信息 - 规范化无头 Chromium 的 User-Agent 与 Client Hints,覆盖 Playwright 主引擎和直接 CDP 备用引擎 - 增加可选证书错误兼容开关、真实 Chromium 指纹集成测试,并同步冻结规范 - 新增 SQLite、MySQL、Postgres 聊天状态迁移并重新构建嵌入式前端
This commit is contained in:
1 parent
1185551018
commit
ecfe43b5a4
43 files changed
+2244
-113
No files matched your search
+101
-3
@@ -113,9 +113,10 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
||||
if lastMessageAt <= 0 {
|
||||
lastMessageAt = modifyTime
|
||||
}
|
||||
unreadCount := s.conversationUnreadCount(ctx, accountID, cid, peerID, conv, last, summary)
|
||||
session := db.ChatSession{CookieID: accountID, ChatID: cid, BuyerID: peerID, BuyerName: peerName, BuyerAvatar: avatar,
|
||||
ItemID: cleanNilString(ext["itemId"]), ItemTitle: cleanNilString(ext["itemTitle"]), LastMessage: summary,
|
||||
LastMessageAt: lastMessageAt, UnreadCount: int(int64Value(conv["redPoint"]))}
|
||||
LastMessageAt: lastMessageAt, UnreadCount: unreadCount}
|
||||
if err := s.store.Chats.UpsertSession(ctx, session); err != nil {
|
||||
return page, err
|
||||
}
|
||||
@@ -126,6 +127,69 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// conversationUnreadCount keeps redPoint as the platform's authoritative
|
||||
// signal, while using our message-level state for the number shown in the UI.
|
||||
// redPoint counts every unread item in a conversation, including trade cards
|
||||
// and official notices; only incoming non-system messages are user unread.
|
||||
func (s *Service) conversationUnreadCount(ctx context.Context, accountID, chatID, peerID string, conv, last map[string]any, summary string) int {
|
||||
official := int(int64Value(conv["redPoint"]))
|
||||
if official < 0 {
|
||||
official = 0
|
||||
}
|
||||
if official == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
if local, err := s.store.Chats.CountUnreadUserMessages(ctx, accountID, chatID); err == nil && local > 0 {
|
||||
// A stale local event must not make the badge exceed the official
|
||||
// conversation signal. In normal operation these values are equal.
|
||||
if local > official {
|
||||
return official
|
||||
}
|
||||
return local
|
||||
}
|
||||
|
||||
if !historyMessageIsSystem(last, summary) {
|
||||
// No message-level row exists yet (for example immediately after a
|
||||
// fresh login), so retain the official count as a safe fallback.
|
||||
return official
|
||||
}
|
||||
|
||||
// 闲小蜜会话只包含平台消息,永远不能制造用户红点。
|
||||
if strings.TrimSuffix(strings.TrimSpace(peerID), "@goofish") == "1400" {
|
||||
return 0
|
||||
}
|
||||
|
||||
// The official last-message envelope exposes unreadCount/readStatus for
|
||||
// that item. Subtract that system portion from redPoint; when older server
|
||||
// responses omit the fields, conservatively remove one system item.
|
||||
systemUnread := int(int64Value(last["unreadCount"]))
|
||||
readStatus := int64Value(last["readStatus"])
|
||||
if systemUnread <= 0 && readStatus != 2 {
|
||||
systemUnread = 1
|
||||
}
|
||||
if systemUnread > official {
|
||||
systemUnread = official
|
||||
}
|
||||
return official - systemUnread
|
||||
}
|
||||
|
||||
func historyMessageIsSystem(last map[string]any, summary string) bool {
|
||||
extension := mapValue(last["extension"])
|
||||
senderID := cleanNilString(extension["senderUserId"])
|
||||
content := map[string]any{}
|
||||
if contentMap, ok := last["content"].(map[string]any); ok {
|
||||
if custom, ok := contentMap["custom"].(map[string]any); ok {
|
||||
if encoded := cleanNilString(custom["data"]); encoded != "" {
|
||||
if raw, err := base64.StdEncoding.DecodeString(encoded); err == nil {
|
||||
_ = json.Unmarshal(raw, &content)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return isOfficialSystemMessage(content, senderID, summary)
|
||||
}
|
||||
|
||||
var invalidNicknames = map[string]struct{}{
|
||||
"交易消息": {}, "系统消息": {}, "卡片消息": {}, "我完成了评价": {}, "对方完成了评价": {},
|
||||
"快给ta一个评价吧~": {}, "卖家已发货": {}, "买家已付款": {}, "买家已确认收货": {},
|
||||
@@ -164,6 +228,7 @@ type Incoming struct {
|
||||
BuyerID string
|
||||
BuyerName string
|
||||
Text string
|
||||
MessageID string
|
||||
ItemID string
|
||||
Raw map[string]any
|
||||
}
|
||||
@@ -243,7 +308,10 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess
|
||||
if sentAt == 0 {
|
||||
sentAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
key := extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid")
|
||||
key := strings.TrimSpace(in.MessageID)
|
||||
if key == "" {
|
||||
key = extractString(in.Raw, "messageId", "message_id", "msgId", "uuid")
|
||||
}
|
||||
if key == "" {
|
||||
raw, _ := json.Marshal(in.Raw)
|
||||
digest := sha256.Sum256([]byte(in.AccountID + "\x00" + in.ChatID + "\x00" + in.BuyerID + "\x00" + in.Text + "\x00" + string(raw)))
|
||||
@@ -263,7 +331,10 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess
|
||||
}
|
||||
message := db.ChatMessage{MessageKey: key, Direction: "incoming", SenderID: in.BuyerID,
|
||||
SenderName: in.BuyerName, MessageType: messageType, Content: content, Status: "received", SentAt: sentAt}
|
||||
stored, inserted, err := s.store.Chats.SaveMessage(ctx, session, message, true)
|
||||
// Official notices may still reach this side channel when protocol fields
|
||||
// vary. They are rendered as system messages and must never create a user
|
||||
// unread badge.
|
||||
stored, inserted, err := s.store.Chats.SaveMessage(ctx, session, message, messageType != "system")
|
||||
if err == nil && inserted {
|
||||
s.Publish(in.AccountID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||
}
|
||||
@@ -527,6 +598,23 @@ func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status
|
||||
return message, err
|
||||
}
|
||||
|
||||
// MarkOutgoingRead records the platform's read receipt for an outgoing message.
|
||||
func (s *Service) MarkOutgoingRead(ctx context.Context, accountID, key string, readAt int64) (*db.ChatMessage, error) {
|
||||
message, err := s.store.Chats.MarkMessageRead(ctx, accountID, key, readAt)
|
||||
if err == nil {
|
||||
s.Publish(accountID, Event{Type: "message.updated", Message: message})
|
||||
}
|
||||
return message, err
|
||||
}
|
||||
|
||||
func (s *Service) MarkLatestOutgoingRead(ctx context.Context, accountID, chatID string, readAt int64) (*db.ChatMessage, error) {
|
||||
message, err := s.store.Chats.MarkLatestOutgoingRead(ctx, accountID, chatID, readAt)
|
||||
if err == nil {
|
||||
s.Publish(accountID, Event{Type: "message.updated", Message: message})
|
||||
}
|
||||
return message, err
|
||||
}
|
||||
|
||||
func randomID() string {
|
||||
var value [16]byte
|
||||
if _, err := rand.Read(value[:]); err == nil {
|
||||
@@ -562,6 +650,16 @@ func extractString(value any, keys ...string) string {
|
||||
return text
|
||||
}
|
||||
}
|
||||
case string:
|
||||
// Live WS envelopes often keep extJson/bizTag as an encoded JSON
|
||||
// string. Decode it so messageId is preserved instead of falling
|
||||
// back to a local in-* key.
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(x), &decoded) == nil {
|
||||
if text := walk(decoded); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -106,6 +106,24 @@ func TestRecordIncomingClassifiesXianxiaomiAndPlaceholder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordIncomingExtractsMessageIDFromEncodedExtension(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
service := New(store)
|
||||
message, _, err := service.RecordIncoming(context.Background(), Incoming{
|
||||
AccountID: "account-1", ChatID: "live", BuyerID: "peer", BuyerName: "对方", Text: "实时消息",
|
||||
Raw: map[string]any{"1": map[string]any{"10": map[string]any{
|
||||
"extJson": `{"messageId":"live-123"}`,
|
||||
}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if message.MessageKey != "live-123" {
|
||||
t.Fatalf("实时消息未提取平台 messageId: %+v", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
@@ -157,6 +175,7 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t
|
||||
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "singleChatConversation": map[string]any{"cid": "platform@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "900"}}}},
|
||||
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "modifyTime": float64(123),
|
||||
"singleChatConversation": map[string]any{"cid": "xiaomi@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "1400"}},
|
||||
"redPoint": float64(3),
|
||||
"lastMessage": map[string]any{"message": map[string]any{"extension": map[string]any{"senderUserId": "1400@goofish", "reminderTitle": "闲小蜜发来一条新消息"}, "content": map[string]any{"custom": map[string]any{"summary": "邀您填写售后问卷"}}}}}},
|
||||
}}
|
||||
if _, err := service.RecordConversationPage(ctx, "account-1", "self", body); err != nil {
|
||||
@@ -167,11 +186,61 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar {
|
||||
if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar || rows[0].UnreadCount != 0 {
|
||||
t.Fatalf("unexpected sessions: %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConversationUnreadCountUsesRedPointButFiltersSystemMessages(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
service := New(store)
|
||||
|
||||
systemCard := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26}`))
|
||||
systemLast := map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"summary": "[交易通知]", "data": systemCard}},
|
||||
"unreadCount": float64(1), "readStatus": float64(1),
|
||||
}
|
||||
if got := service.conversationUnreadCount(context.Background(), "account-1", "system-last", "peer", map[string]any{"redPoint": float64(3)}, systemLast, "[交易通知]"); got != 2 {
|
||||
t.Fatalf("系统未读未从 redPoint 扣除: got=%d", got)
|
||||
}
|
||||
if got := service.conversationUnreadCount(context.Background(), "account-1", "xiaomi", "1400", map[string]any{"redPoint": float64(3)}, systemLast, "[交易通知]"); got != 0 {
|
||||
t.Fatalf("闲小蜜全是系统消息时仍显示红点: got=%d", got)
|
||||
}
|
||||
|
||||
if _, _, err := service.RecordIncoming(context.Background(), Incoming{
|
||||
AccountID: "account-1", ChatID: "real", BuyerID: "peer", BuyerName: "真实用户", Text: "未读消息",
|
||||
MessageID: "real-unread", Raw: map[string]any{"messageId": "real-unread"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
userLast := map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"summary": "未读消息"}},
|
||||
}
|
||||
if got := service.conversationUnreadCount(context.Background(), "account-1", "real", "peer", map[string]any{"redPoint": float64(3)}, userLast, "未读消息"); got != 1 {
|
||||
t.Fatalf("未使用消息级真实未读数: got=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryMessageIsSystem(t *testing.T) {
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26,"dxCard":{}}`))
|
||||
last := map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"data": encoded}},
|
||||
}
|
||||
if !historyMessageIsSystem(last, "[我已拍下,待付款]") {
|
||||
t.Fatal("交易卡片应被识别为系统消息")
|
||||
}
|
||||
if historyMessageIsSystem(map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"summary": "你好"}},
|
||||
}, "你好") {
|
||||
t.Fatal("真实用户文本不应被识别为系统消息")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
|
||||
Reference in new issue
Block a user