修复聊天状态并完善风控浏览器诊断
修复内容: - 持久化聊天消息已读状态与未读边界,过滤系统通知红点,修正实时消息 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
@@ -83,6 +83,19 @@ type Handler interface {
|
||||
OnAccountAlert(ctx context.Context, cookieID, level, title, body string)
|
||||
}
|
||||
|
||||
// MessageReadHandler receives platform read receipts. It is optional so older
|
||||
// integrations and tests remain valid.
|
||||
type MessageReadHandler interface {
|
||||
HandleMessageRead(context.Context, MessageReadEvent) error
|
||||
}
|
||||
|
||||
type MessageReadEvent struct {
|
||||
AccountID string
|
||||
ChatID string
|
||||
MessageID string
|
||||
ReadAt int64
|
||||
}
|
||||
|
||||
type accountEventHandler interface {
|
||||
OnAccountEvent(ctx context.Context, cookieID, eventType, level, title, body string)
|
||||
}
|
||||
@@ -121,6 +134,7 @@ type ChatMessage struct {
|
||||
SenderUserID string
|
||||
SenderName string
|
||||
Text string
|
||||
MessageID string
|
||||
ItemID string
|
||||
Raw map[string]any // 解密后的完整消息
|
||||
}
|
||||
@@ -1799,6 +1813,22 @@ func (a *Account) SendText(ctx context.Context, chatID, toUserID, text string) e
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Account) MarkChatRead(ctx context.Context, chatID string, messageIDs []map[string]any) error {
|
||||
conn, _, err := a.currentSenderState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
readCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
reader, ok := conn.(interface {
|
||||
MarkChatRead(context.Context, string, []map[string]any) error
|
||||
})
|
||||
if !ok {
|
||||
return fmt.Errorf("当前 WebSocket 不支持已读上报")
|
||||
}
|
||||
return reader.MarkChatRead(readCtx, chatID, messageIDs)
|
||||
}
|
||||
|
||||
// SendImage 通过当前 WebSocket 给买家发送图片消息。当前仅支持可直接访问的 CDN/公网 URL。
|
||||
func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64) error {
|
||||
imageURL = strings.TrimSpace(imageURL)
|
||||
|
||||
+191
-3
@@ -3,11 +3,14 @@ package engine
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
// dispatch 是 ws.ReceiveLoop 的回调,对每条解密后的消息做:
|
||||
@@ -59,6 +62,17 @@ func (a *Account) handleMessage(decrypted map[string]any) {
|
||||
}
|
||||
|
||||
func (a *Account) handleMessageContext(ctx context.Context, decrypted map[string]any) {
|
||||
if receipt, ok := extractMessageReadEvent(decrypted); ok {
|
||||
receipt.AccountID = a.CookieID
|
||||
if h, ok := a.handler.(MessageReadHandler); ok {
|
||||
if err := h.HandleMessageRead(ctx, receipt); err != nil {
|
||||
a.logger.Warn("处理聊天已读回执失败", "err", err, "message_id", receipt.MessageID)
|
||||
}
|
||||
} else {
|
||||
a.logger.Debug("收到聊天已读回执,但未接入处理器", "message_id", receipt.MessageID)
|
||||
}
|
||||
return
|
||||
}
|
||||
// 第一优先级:系统卡片和平台通知进入自动化中心。
|
||||
// 这里不判断具体业务,只做“平台事件”事实解析;系统消息永远不进入 AI 回复范围。
|
||||
if task := automation.ExtractTaskFromWS(a.CookieID, a.currentCookieStr(), decrypted); task != nil {
|
||||
@@ -69,6 +83,10 @@ func (a *Account) handleMessageContext(ctx context.Context, decrypted map[string
|
||||
}
|
||||
return
|
||||
}
|
||||
if senderUserID := extractChatSenderUserID(decrypted); isSelfUserID(senderUserID, protocol.TransCookies(a.currentCookieStr())["unb"]) {
|
||||
a.logger.Info("忽略账号自身发送的 WebSocket 聊天回显", "chat_id", extractChatID(decrypted), "sender_id", senderUserID)
|
||||
return
|
||||
}
|
||||
|
||||
chat := extractChatMessage(decrypted, a.CookieID, a.currentCookieStr())
|
||||
if chat != nil && chat.Text != "" {
|
||||
@@ -82,6 +100,89 @@ func (a *Account) handleMessageContext(ctx context.Context, decrypted map[string
|
||||
}
|
||||
}
|
||||
|
||||
func extractMessageReadEvent(v map[string]any) (MessageReadEvent, bool) {
|
||||
// 40103 解密后不会保留外层 objectType,只剩下固定的紧凑字段:
|
||||
// 1=PNM 消息 ID、2=状态(2=已读)、4=会话 ID、6=事件时间。
|
||||
// 不能只在解密后的 map 里继续寻找 "bizType":40103,否则真实回执
|
||||
// 会被当成普通消息静默丢弃。
|
||||
messageID := strings.TrimSpace(toString(v["1"]))
|
||||
if ids, ok := v["1"].([]any); ok && len(ids) > 0 {
|
||||
messageID = strings.TrimSpace(toString(ids[0]))
|
||||
}
|
||||
if strings.HasSuffix(messageID, ".PNM") && toString(v["2"]) == "2" {
|
||||
chatID := strings.TrimSpace(toString(v["4"]))
|
||||
if !strings.Contains(chatID, "@goofish") {
|
||||
chatID = strings.TrimSpace(toString(v["3"]))
|
||||
}
|
||||
chatID = strings.TrimSuffix(chatID, "@goofish")
|
||||
return MessageReadEvent{ChatID: chatID, MessageID: messageID, ReadAt: time.Now().UTC().UnixMilli()}, true
|
||||
}
|
||||
var found bool
|
||||
var ev MessageReadEvent
|
||||
var walk func(any)
|
||||
walk = func(x any) {
|
||||
if found {
|
||||
return
|
||||
}
|
||||
switch m := x.(type) {
|
||||
case map[string]any:
|
||||
for k, val := range m {
|
||||
lk := strings.ToLower(k)
|
||||
if lk == "biztype" || lk == "biz_type" || lk == "type" {
|
||||
if toString(val) == "40103" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if found {
|
||||
ev.MessageID = extractNestedString(m, "messageid", "message_id")
|
||||
ev.ChatID = extractNestedString(m, "cid", "chatid", "chat_id")
|
||||
if ev.MessageID == "" {
|
||||
ev.MessageID = extractNestedString(m, "id")
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, child := range m {
|
||||
walk(child)
|
||||
}
|
||||
case []any:
|
||||
for _, child := range m {
|
||||
walk(child)
|
||||
}
|
||||
case string:
|
||||
// Some sync envelopes carry the event body as an escaped JSON
|
||||
// string instead of an already-decoded object.
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(m), &decoded) == nil {
|
||||
walk(decoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(v)
|
||||
if !found || ev.MessageID == "" {
|
||||
return MessageReadEvent{}, false
|
||||
}
|
||||
return ev, true
|
||||
}
|
||||
|
||||
func extractNestedString(m map[string]any, keys ...string) string {
|
||||
for k, v := range m {
|
||||
for _, want := range keys {
|
||||
if strings.EqualFold(k, want) && strings.TrimSpace(toString(v)) != "" {
|
||||
return strings.TrimSpace(toString(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, v := range m {
|
||||
if child, ok := v.(map[string]any); ok {
|
||||
if s := extractNestedString(child, keys...); s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// markAndCheckDedup 提取消息 ID,检查 1 小时内是否已处理;未处理则标记。
|
||||
// 返回 true 表示应继续处理。移植自 _schedule_debounced_reply 的去重段。
|
||||
func (a *Account) markAndCheckDedup(decrypted map[string]any, chat *ChatMessage) bool {
|
||||
@@ -183,13 +284,21 @@ func (a *Account) scheduleDebouncedReply(chat ChatMessage) {
|
||||
})
|
||||
}
|
||||
|
||||
// extractMessageID 从 message["1"]["10"]["bizTag"] 或 extJson 中提取 messageId。
|
||||
// 移植自 _extract_message_id。
|
||||
// extractMessageID 提取闲鱼消息状态接口使用的消息 ID。
|
||||
//
|
||||
// 实时 WS 聊天消息同时包含两种 ID:message["1"]["3"] 是消息在 IM
|
||||
// 服务中的 PNM ID,/r/MessageStatus/read 使用的正是这个 ID;10.bizTag、
|
||||
// extJson 和 reminderUrl 里的 messageId 是通知/推送侧的关联 ID,不能用来
|
||||
// 上报会话已读。历史消息接口也返回 PNM ID,因此优先使用字段 3,其他
|
||||
// 字段只作为兼容旧消息或缺失字段 3 的兜底。
|
||||
func extractMessageID(decrypted map[string]any) string {
|
||||
m1, ok := decrypted["1"].(map[string]any)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
if id := strings.TrimSpace(toString(m1["3"])); id != "" && id != "<nil>" {
|
||||
return id
|
||||
}
|
||||
m10, ok := m1["10"].(map[string]any)
|
||||
if !ok {
|
||||
return ""
|
||||
@@ -205,6 +314,43 @@ func extractMessageID(decrypted map[string]any) string {
|
||||
return id
|
||||
}
|
||||
}
|
||||
if reminderURL, _ := m10["reminderUrl"].(string); reminderURL != "" {
|
||||
if parsed, err := url.Parse(reminderURL); err == nil {
|
||||
if id := strings.TrimSpace(parsed.Query().Get("messageId")); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
return findMessageID(decrypted)
|
||||
}
|
||||
|
||||
func findMessageID(value any) string {
|
||||
switch x := value.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range x {
|
||||
if strings.EqualFold(key, "messageId") || strings.EqualFold(key, "message_id") {
|
||||
if id := strings.TrimSpace(fmt.Sprint(child)); id != "" && id != "<nil>" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, child := range x {
|
||||
if id := findMessageID(child); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, child := range x {
|
||||
if id := findMessageID(child); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
case string:
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(x), &decoded) == nil {
|
||||
return findMessageID(decoded)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -241,7 +387,13 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
|
||||
if i := strings.Index(chatID, "@"); i >= 0 {
|
||||
chatID = chatID[:i]
|
||||
}
|
||||
senderUserID, _ := m10["senderUserId"].(string)
|
||||
senderUserID := extractChatSenderUserIDFromMaps(m1, m10)
|
||||
if isSelfUserID(senderUserID, protocol.TransCookies(cookieStr)["unb"]) {
|
||||
// The official client echoes messages sent by this account over the
|
||||
// same WebSocket. They are delivery observations, not new buyer input,
|
||||
// and must never enter the automatic-reply pipeline.
|
||||
return nil
|
||||
}
|
||||
senderName, _ := m10["senderNick"].(string)
|
||||
if strings.TrimSpace(senderName) == "" {
|
||||
senderName, _ = m10["reminderTitle"].(string)
|
||||
@@ -255,11 +407,47 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
|
||||
SenderUserID: senderUserID,
|
||||
SenderName: senderName,
|
||||
Text: reminder,
|
||||
MessageID: extractMessageID(decrypted),
|
||||
ItemID: itemID,
|
||||
Raw: decrypted,
|
||||
}
|
||||
}
|
||||
|
||||
func extractChatSenderUserID(decrypted map[string]any) string {
|
||||
m1, _ := decrypted["1"].(map[string]any)
|
||||
if m1 == nil {
|
||||
return ""
|
||||
}
|
||||
m10, _ := m1["10"].(map[string]any)
|
||||
return extractChatSenderUserIDFromMaps(m1, m10)
|
||||
}
|
||||
|
||||
func extractChatSenderUserIDFromMaps(m1, m10 map[string]any) string {
|
||||
if m10 != nil {
|
||||
if sender := strings.TrimSpace(toString(m10["senderUserId"])); sender != "" {
|
||||
return sender
|
||||
}
|
||||
}
|
||||
// Some echoed messages omit 10.senderUserId but retain the sender in the
|
||||
// compact 1.1 envelope.
|
||||
if sender, ok := m1["1"].(map[string]any); ok {
|
||||
return strings.TrimSpace(toString(sender["1"]))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractChatID(decrypted map[string]any) string {
|
||||
m1, _ := decrypted["1"].(map[string]any)
|
||||
chatID := strings.TrimSpace(toString(m1["2"]))
|
||||
return strings.TrimSuffix(chatID, "@goofish")
|
||||
}
|
||||
|
||||
func isSelfUserID(senderUserID, selfUserID string) bool {
|
||||
sender := strings.TrimSuffix(strings.TrimSpace(senderUserID), "@goofish")
|
||||
self := strings.TrimSuffix(strings.TrimSpace(selfUserID), "@goofish")
|
||||
return sender != "" && self != "" && sender == self
|
||||
}
|
||||
|
||||
// isNonUserChatNotice 判断闲鱼 IM 中不应进入自动回复的系统提示或交易卡片。
|
||||
// 典型样本:
|
||||
// - contentType=14:“有蚂蚁森林能量可领”“不想宝贝被砍价?设置不砍价回复”“退款成功”
|
||||
|
||||
@@ -135,6 +135,22 @@ func TestHandleMessage_DedupSkipsRepeat(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMessage_IgnoresOwnWebSocketEcho(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
// newAccountForTest 使用 unb=123;模拟同一账号在闲鱼官方客户端发出的
|
||||
// 消息回显,不能进入自动回复或业务消息处理链。
|
||||
acc.handleMessage(plainChatMessage(t, "官方客户端发送", "123", "chat-own"))
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 0 {
|
||||
t.Fatalf("账号自身消息回显不应触发自动回复,got %d", len(h.chats))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMessage_NoReminderNoOp 无 reminderContent 的消息不进入回复链也不报错。
|
||||
func TestHandleMessage_NoReminderNoOp(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
@@ -522,3 +538,19 @@ func plainChatMessage(t *testing.T, text, senderUserID, chatID string) map[strin
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestExtractMessageReadEvent40103(t *testing.T) {
|
||||
event, ok := extractMessageReadEvent(map[string]any{
|
||||
"1": "4263141580162.PNM", "2": 2, "3": 0,
|
||||
"4": "64725235816@goofish", "5": 1, "6": 1786945729928,
|
||||
})
|
||||
if !ok || event.MessageID != "4263141580162.PNM" || event.ChatID != "64725235816" || event.ReadAt <= 0 {
|
||||
t.Fatalf("40103 event=%+v ok=%v", event, ok)
|
||||
}
|
||||
batch, ok := extractMessageReadEvent(map[string]any{
|
||||
"1": []any{"4263107993838.PNM"}, "2": 2, "3": "64725235816@goofish", "4": 1,
|
||||
})
|
||||
if !ok || batch.MessageID != "4263107993838.PNM" || batch.ChatID != "64725235816" {
|
||||
t.Fatalf("40103 batch event=%+v ok=%v", batch, ok)
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,16 @@ func TestExtractChatMessageUsesReminderTitleAsNickname(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractChatMessageIgnoresOwnWebSocketEcho(t *testing.T) {
|
||||
decrypted := map[string]any{"1": map[string]any{
|
||||
"2": "chat-1@goofish",
|
||||
"10": map[string]any{"reminderContent": "我在官方客户端发送的消息", "senderUserId": "self-1", "senderNick": "我"},
|
||||
}}
|
||||
if chat := extractChatMessage(decrypted, "account-1", "unb=self-1;"); chat != nil {
|
||||
t.Fatalf("账号自身发送的 WS 回显不应进入自动回复链: %+v", chat)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractChatMessage_FiltersRefundTradeCard(t *testing.T) {
|
||||
decrypted := mustRefundTradeCard(t)
|
||||
if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
|
||||
|
||||
@@ -216,17 +216,18 @@ func TestParseMessageIDFromJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractMessageID 优先 bizTag,其次 extJson,无则空。
|
||||
// TestExtractMessageID 优先实时消息的 PNM ID,其次兼容 bizTag/extJson,无则空。
|
||||
func TestExtractMessageID(t *testing.T) {
|
||||
if got := extractMessageID(map[string]any{
|
||||
"1": map[string]any{
|
||||
"3": "4263141580162.PNM",
|
||||
"10": map[string]any{
|
||||
"bizTag": `{"messageId":"biz-id"}`,
|
||||
"extJson": `{"messageId":"ext-id"}`,
|
||||
},
|
||||
},
|
||||
}); got != "biz-id" {
|
||||
t.Errorf("bizTag 优先: got %q", got)
|
||||
}); got != "4263141580162.PNM" {
|
||||
t.Errorf("PNM 优先: got %q", got)
|
||||
}
|
||||
if got := extractMessageID(map[string]any{
|
||||
"1": map[string]any{
|
||||
|
||||
Reference in new issue
Block a user