Initial xianyu-go repository

This commit is contained in:
Christ committed 2026-06-28 11:54:39 +08:00
commit 074554a6de
100 files changed
+20612

No files matched your search

+641
View File
@@ -0,0 +1,641 @@
// Package engine 实现单账号运行时:WebSocket 连接生命周期、token 刷新、
// 消息分发主循环(信号量限并发 + 防抖 + 去重)、重连策略。
//
// 移植自 Python XianyuAutoAsync.py 的 main() / handle_message /
// _handle_message_with_semaphore / _schedule_debounced_reply / token_refresh_loop。
//
// 业务逻辑(自动发货、回复)在 Phase 3 通过 Handler 接口注入,
// Phase 2 先搭好骨架并跑通"收消息→解密→去重→防抖→回调"。
package engine
import (
"context"
"fmt"
"log/slog"
"strings"
"sync"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
"xianyu-go/internal/xianyu/protocol"
"xianyu-go/internal/xianyu/ws"
)
// 常量,与 Python 端一致。
const (
MaxConnectionFailures = 5 // 连续失败上限,触发密码登录刷新
MessageSemaphoreSize = 100 // 并发消息处理上限
MessageDebounceDelay = 1 * time.Second // 防抖延迟:用户停止发送 1s 后回复
MessageExpireTime = time.Hour // 去重有效期
ProcessedIDsMaxSize = 10000 // 去重表上限,超限清理
HeartbeatInterval = 15 * time.Second
TokenRefreshInterval = 1 * time.Hour
TokenRefreshMinGap = time.Minute
MessageCooldown = 5 * time.Minute // 收到消息后 5 分钟内不刷 cookie
PasswordLoginMinGap = 30 * time.Minute
)
// Handler 是业务逻辑注入点(Phase 3 实现)。
// 收到一条防抖后的聊天消息时回调;返回错误仅记录日志、不影响主循环。
type Handler interface {
HandleChatMessage(ctx context.Context, m ChatMessage) error
// HandleSystemMessage 处理订单状态等非聊天消息(如 redReminder)。
HandleSystemMessage(ctx context.Context, m SystemMessage) error
// OnPasswordLoginRefresh 连续失败触发密码登录刷新(Phase 5 sidecar);返回是否成功。
OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool
}
// ChatMessage 防抖后投递给业务层的一条聊天消息。
type ChatMessage struct {
AccountID string // cookie_id
CookieStr string
ChatID string
SenderUserID string
SenderName string
Text string
ItemID string
Raw map[string]any // 解密后的完整消息
}
// SystemMessage 订单状态等系统消息。
type SystemMessage struct {
AccountID string
CookieStr string
RedReminder string // message["3"]["redReminder"],订单状态文本
UserID string
Raw map[string]any
}
// RuntimeStatus 是账号引擎的实时连接状态,不写入数据库。
type RuntimeStatus struct {
State string `json:"state"`
Message string `json:"message,omitempty"`
Connected bool `json:"connected"`
Failures int `json:"failures"`
UpdatedAt time.Time `json:"updated_at"`
}
const (
RuntimeStarting = "starting"
RuntimeConnecting = "connecting"
RuntimeOnline = "online"
RuntimeReconnecting = "reconnecting"
RuntimeAuthExpired = "auth_expired"
RuntimeVerificationRequired = "verification_required"
RuntimeError = "error"
RuntimeStopped = "stopped"
)
// Account 单账号运行时。
type Account struct {
CookieID string
CookieStr string
UserID string // unb(myid)
store *db.Store
mtop *mtop.Client
wsDialer wsDialer
handler Handler
logger *slog.Logger
// 运行时状态(受 mu 保护)
mu sync.Mutex
currentToken string
deviceID string
connFailures int
lastMsgReceived time.Time
lastTokenRefresh time.Time
lastPasswordLogin time.Time
runtimeState string
runtimeMessage string
runtimeUpdatedAt time.Time
stopFn context.CancelFunc
stopped bool
conn *ws.Conn
// 去重
dedupMu sync.Mutex
processed map[string]time.Time
// 防抖:chat_id → 防抖句柄
debounceMu sync.Mutex
debounceTimers map[string]*debounceEntry
// 消息处理信号量
sem chan struct{}
delivery *DeliveryService
reply *ReplyService
}
type debounceEntry struct {
timer *time.Timer
lastMsg ChatMessage
deadline time.Time
}
// wsDialer 抽象 ws.Dial,便于测试替身。
type wsDialer interface {
Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (*ws.Conn, error)
}
type defaultDialer struct{}
func (defaultDialer) Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (*ws.Conn, error) {
return ws.Dial(ctx, cfg, logger)
}
// Config 构造 Account 所需依赖。
type Config struct {
CookieID string
CookieStr string
Store *db.Store
Handler Handler
Logger *slog.Logger
}
// New 构造单账号运行时(未启动)。
func New(cfg Config) *Account {
logger := cfg.Logger
if logger == nil {
logger = slog.Default()
}
cookies := protocol.TransCookies(cfg.CookieStr)
myid := cookies["unb"]
a := &Account{
CookieID: cfg.CookieID,
CookieStr: cfg.CookieStr,
UserID: myid,
store: cfg.Store,
mtop: &mtop.Client{},
wsDialer: defaultDialer{},
handler: cfg.Handler,
logger: logger.With("account", cfg.CookieID),
deviceID: protocol.GenerateDeviceID(myid),
processed: make(map[string]time.Time),
debounceTimers: make(map[string]*debounceEntry),
sem: make(chan struct{}, MessageSemaphoreSize),
runtimeState: RuntimeStarting,
runtimeMessage: "正在启动账号服务",
runtimeUpdatedAt: time.Now(),
}
if cfg.Store != nil {
var orderFetcher OrderDetailFetcher
if fetcher, ok := cfg.Handler.(OrderDetailFetcher); ok {
orderFetcher = fetcher
}
a.delivery = NewDeliveryService(cfg.CookieID, cfg.Store, a, orderFetcher, nil, logger)
a.delivery.SetCookieSource(a.currentCookieStr, a.replaceCookieStr)
a.reply = NewReplyService(cfg.CookieID, cfg.Store, a, nil, NewAIReplier(cfg.CookieID, cfg.Store, logger), logger)
}
return a
}
// Run 阻塞运行账号主循环,直到 ctx 取消或不可恢复错误。
// 调用方应在独立 goroutine 中运行;Stop 可优雅停止。
func (a *Account) Run(parent context.Context) error {
ctx, cancel := context.WithCancel(parent)
a.mu.Lock()
a.stopFn = cancel
a.mu.Unlock()
for {
if ctx.Err() != nil {
return ctx.Err()
}
// 账号是否被禁用。
if !a.store.Cookies.GetStatus(ctx, a.CookieID) {
a.logger.Info("账号已禁用,停止主循环")
return nil
}
// 1) 刷新 token。
token, cookieStr, err := a.refreshToken(ctx)
if err != nil {
a.logger.Error("刷新 token 失败", "err", err)
a.mu.Lock()
a.connFailures++
failures := a.connFailures
a.mu.Unlock()
a.setRuntimeError(err)
if failures >= MaxConnectionFailures {
if err := a.handleMaxFailures(ctx); err != nil {
return err
}
continue
}
if sleepCtx(ctx, a.retryDelay("token_refresh")) != nil {
return ctx.Err()
}
continue
}
a.mu.Lock()
a.currentToken = token
a.CookieStr = cookieStr
a.connFailures = 0
a.mu.Unlock()
a.setRuntimeState(RuntimeConnecting, "登录凭证有效,正在连接消息服务")
// 2) 连接 WS + 注册。
var recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string)
if a.store != nil && a.store.WSMessages != nil {
recorder = func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
_ = a.store.WSMessages.Add(context.Background(), db.WSMessage{
CookieID: a.CookieID,
Direction: direction,
RawText: rawText,
ParsedJSON: parsedJSON,
MessageKind: "",
ParseStatus: parseStatus,
Error: errMsg,
})
}
}
a.mu.Lock()
deviceID := a.deviceID
a.mu.Unlock()
conn, err := a.wsDialer.Dial(ctx, ws.Config{
CookieStr: cookieStr,
DeviceID: deviceID,
AccessToken: token,
Recorder: recorder,
}, a.logger)
if err != nil {
a.logger.Error("WS 连接失败", "err", err)
a.mu.Lock()
a.connFailures++
failures := a.connFailures
a.mu.Unlock()
a.setRuntimeState(RuntimeReconnecting, "消息服务连接失败,稍后自动重试")
if failures >= MaxConnectionFailures {
if err := a.handleMaxFailures(ctx); err != nil {
return err
}
continue
}
if sleepCtx(ctx, a.retryDelay("ws_dial")) != nil {
return ctx.Err()
}
continue
}
a.mu.Lock()
a.conn = conn
a.mu.Unlock()
a.setRuntimeState(RuntimeOnline, "消息服务连接正常")
// 3) 心跳 + 消息接收。
hbCtx, hbCancel := context.WithCancel(ctx)
var hbErr error
go func() {
hbErr = conn.HeartbeatLoop(hbCtx, HeartbeatInterval)
hbCancel()
}()
recvErr := conn.ReceiveLoop(ctx, a.dispatch)
hbCancel()
_ = conn.Close()
// 连接结束:清 token,统计失败,决定重连或密码刷新。
a.mu.Lock()
a.currentToken = ""
a.conn = nil
a.connFailures++
failures := a.connFailures
a.mu.Unlock()
a.setRuntimeState(RuntimeReconnecting, "消息连接已断开,稍后自动重连")
a.logger.Warn("WS 连接结束", "err", recvErr, "failures", failures, "heartbeat_err", hbErr)
if failures >= MaxConnectionFailures {
if err := a.handleMaxFailures(ctx); err != nil {
return err
}
continue
}
if sleepCtx(ctx, a.retryDelay(errString(recvErr))) != nil {
return ctx.Err()
}
}
}
// Stop 优雅停止。
func (a *Account) Stop() {
a.mu.Lock()
defer a.mu.Unlock()
if a.stopped {
return
}
a.stopped = true
a.runtimeState = RuntimeStopped
a.runtimeMessage = "账号服务已停止"
a.runtimeUpdatedAt = time.Now()
if a.stopFn != nil {
a.stopFn()
}
// 取消所有防抖定时器。
a.debounceMu.Lock()
for _, e := range a.debounceTimers {
if e.timer != nil {
e.timer.Stop()
}
}
a.debounceTimers = make(map[string]*debounceEntry)
a.debounceMu.Unlock()
}
// handleMaxFailures 连续失败达上限:尝试密码登录刷新;失败则返回 err 触发上层重启实例。
func (a *Account) handleMaxFailures(ctx context.Context) error {
a.logger.Warn("连续失败达上限,触发密码登录刷新", "failures", MaxConnectionFailures)
a.mu.Lock()
lastMsg := a.lastMsgReceived
lastLogin := a.lastPasswordLogin
a.mu.Unlock()
if !lastMsg.IsZero() && time.Since(lastMsg) < MessageCooldown {
a.logger.Warn("最近仍收到消息,跳过密码登录刷新", "cooldown", MessageCooldown)
a.resetFailures()
return sleepCtx(ctx, a.retryDelay("recent_message_skip_password_login"))
}
if !lastLogin.IsZero() && time.Since(lastLogin) < PasswordLoginMinGap {
remain := PasswordLoginMinGap - time.Since(lastLogin)
a.logger.Warn("密码登录刷新冷却中,跳过本次刷新", "remain", remain.Round(time.Second))
a.resetFailures()
return sleepCtx(ctx, minDuration(remain, time.Minute))
}
a.mu.Lock()
a.lastPasswordLogin = time.Now()
a.mu.Unlock()
if a.handler != nil && a.handler.OnPasswordLoginRefresh(ctx, a.CookieID) {
if d, err := a.store.Cookies.GetDetails(ctx, a.CookieID); err == nil && d != nil && d.Value != "" {
a.replaceCookieStr(d.Value)
}
a.logger.Info("密码登录刷新成功,重置失败计数")
a.setRuntimeState(RuntimeConnecting, "登录凭证已刷新,正在重新连接")
a.resetFailures()
return sleepCtx(ctx, 2*time.Second)
}
a.resetFailures()
a.setRuntimeState(RuntimeAuthExpired, "登录凭证已失效,请重新扫码登录")
return fmt.Errorf("账号 %s 连续失败 %d 次且密码登录刷新失败,需重启实例", a.CookieID, MaxConnectionFailures)
}
func (a *Account) resetFailures() {
a.mu.Lock()
defer a.mu.Unlock()
a.connFailures = 0
}
// retryDelay 移植自 _calculate_retry_delay。
func (a *Account) retryDelay(errMsg string) time.Duration {
a.mu.Lock()
f := a.connFailures
a.mu.Unlock()
if f < 1 {
f = 1
}
secs := 0
switch {
case contains(errMsg, "no close frame received or sent"):
secs = min(3*f, 15)
case contains(errMsg, "connection refused") || contains(errMsg, "timeout"):
secs = min(10*f, 60)
default:
secs = min(5*f, 30)
}
return time.Duration(secs) * time.Second
}
// refreshToken 调 mtop token API,返回 (accessToken, 更新后的 cookie)。
func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
a.mu.Lock()
cookieStr := a.CookieStr
last := a.lastTokenRefresh
if !last.IsZero() && time.Since(last) < TokenRefreshMinGap {
remain := TokenRefreshMinGap - time.Since(last)
a.mu.Unlock()
a.logger.Info("等待 token 刷新冷却", "remain", remain.Round(time.Second))
if err := sleepCtx(ctx, remain); err != nil {
return "", "", err
}
a.mu.Lock()
cookieStr = a.CookieStr
}
a.lastTokenRefresh = time.Now()
a.mu.Unlock()
deviceID := strings.TrimSpace(a.deviceID)
if deviceID == "" {
if unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" {
deviceID = protocol.GenerateDeviceID(unb)
a.mu.Lock()
a.deviceID = deviceID
a.mu.Unlock()
}
}
res, err := a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID)
if res != nil && res.UpdatedCookies != "" && res.UpdatedCookies != cookieStr {
a.replaceCookieStr(res.UpdatedCookies)
cookieStr = res.UpdatedCookies
if a.store != nil {
if d, e := a.store.Cookies.GetDetails(ctx, a.CookieID); e == nil {
_ = a.store.Cookies.Save(ctx, a.CookieID, res.UpdatedCookies, d.UserID)
}
}
}
if err != nil {
return "", "", err
}
if res == nil {
return "", "", fmt.Errorf("token API 未返回结果")
}
// 若 cookie 被刷新,持久化回 DB(与 Python update_config_cookies 一致)。
if res.UpdatedCookies != cookieStr {
a.mu.Lock()
a.CookieStr = res.UpdatedCookies
cookieStr = res.UpdatedCookies
a.mu.Unlock()
if a.store != nil {
// 保留原 user_id:用 GetDetails 取后回写。
if d, e := a.store.Cookies.GetDetails(ctx, a.CookieID); e == nil {
_ = a.store.Cookies.Save(ctx, a.CookieID, res.UpdatedCookies, d.UserID)
}
}
}
return res.AccessToken, cookieStr, nil
}
// RuntimeStatus 返回账号当前连接状态的线程安全快照。
func (a *Account) RuntimeStatus() RuntimeStatus {
a.mu.Lock()
defer a.mu.Unlock()
return RuntimeStatus{
State: a.runtimeState,
Message: a.runtimeMessage,
Connected: a.conn != nil && a.runtimeState == RuntimeOnline,
Failures: a.connFailures,
UpdatedAt: a.runtimeUpdatedAt,
}
}
func (a *Account) setRuntimeState(state, message string) {
a.mu.Lock()
defer a.mu.Unlock()
a.runtimeState = state
a.runtimeMessage = message
a.runtimeUpdatedAt = time.Now()
}
func (a *Account) setRuntimeError(err error) {
msg := strings.ToLower(errString(err))
switch {
case strings.Contains(msg, "验证"), strings.Contains(msg, "captcha"), strings.Contains(msg, "risk"), strings.Contains(msg, "rgv587"), strings.Contains(msg, "fail_sys_user_validate"):
a.setRuntimeState(RuntimeVerificationRequired, "闲鱼要求安全验证,请重新扫码并完成验证")
case strings.Contains(msg, "登录凭证已失效"), strings.Contains(msg, "fail_sys_token_exoired"), strings.Contains(msg, "fail_sys_token_expired"), strings.Contains(msg, "cookie 缺少 unb"):
a.setRuntimeState(RuntimeAuthExpired, "登录凭证已失效,请重新扫码登录")
default:
a.setRuntimeState(RuntimeReconnecting, "连接异常,系统将在限速后自动重试")
}
}
// SendText 通过当前 WebSocket 给买家发送文本消息。
func (a *Account) SendText(ctx context.Context, chatID, toUserID, text string) error {
text = strings.TrimSpace(text)
if text == "" {
return nil
}
conn, myID, err := a.currentSenderState()
if err != nil {
return err
}
sendCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
return conn.SendText(sendCtx, myID, chatID, toUserID, text)
}
// SendImage 通过当前 WebSocket 给买家发送图片消息。当前仅支持可直接访问的 CDN/公网 URL。
func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64) error {
imageURL = strings.TrimSpace(imageURL)
if imageURL == "" {
return nil
}
if strings.HasPrefix(imageURL, "/static/") || strings.HasPrefix(imageURL, "static/") {
return fmt.Errorf("Go 运行时暂不支持本地图片自动上传到闲鱼 CDN: %s", imageURL)
}
conn, myID, err := a.currentSenderState()
if err != nil {
return err
}
sendCtx, cancel := context.WithTimeout(ctx, 8*time.Second)
defer cancel()
return conn.SendImage(sendCtx, myID, chatID, toUserID, imageURL, 800, 600)
}
// ManualFullDelivery 对已存在订单执行完整手动发货:匹配卡券、确认发货、发送给买家并更新本地订单。
func (a *Account) ManualFullDelivery(ctx context.Context, order *db.Order) (int, error) {
if order == nil {
return 0, fmt.Errorf("订单不存在")
}
if a.delivery == nil {
return 0, fmt.Errorf("账号 %s 未初始化发货服务", a.CookieID)
}
if strings.TrimSpace(order.ItemID) == "" {
return 0, fmt.Errorf("订单缺少商品ID,无法匹配发货规则")
}
if strings.TrimSpace(order.BuyerID) == "" {
return 0, fmt.Errorf("订单缺少买家ID,无法发送卡券")
}
if strings.TrimSpace(order.ChatID) == "" {
return 0, fmt.Errorf("订单缺少 chat_id,无法发送卡券;请等待买家发消息后再试")
}
if _, _, err := a.currentSenderState(); err != nil {
return 0, err
}
quantity := 1
if a.store.Items.MultiQuantityDelivery(ctx, a.CookieID, order.ItemID) {
if q := parseIntSafe(order.Quantity); q > 1 {
quantity = q
}
}
contents, err := a.delivery.collectDeliveryContentsWithSpec(ctx, order.ItemID, order.OrderID, order.BuyerID, order.SpecName, order.SpecValue, quantity)
if err != nil {
return 0, err
}
if len(contents) == 0 {
return 0, fmt.Errorf("未匹配到发货规则或卡券获取失败")
}
for i, content := range contents {
if err := a.delivery.sendContent(ctx, content, order.ChatID, order.BuyerID); err != nil {
return i, err
}
if len(contents) > 1 && i < len(contents)-1 {
if err := sleepCtx(ctx, time.Second); err != nil {
return i + 1, err
}
}
}
a.delivery.markDeliverySent(order.OrderID)
sysShip := true
_ = a.store.Orders.Upsert(ctx, order.OrderID, db.OrderUpsertOpts{
CookieID: order.CookieID,
OrderStatus: "shipped",
SystemShipped: &sysShip,
ItemID: order.ItemID,
BuyerID: order.BuyerID,
ReceiverName: order.ReceiverName,
ReceiverPhone: order.ReceiverPhone,
ReceiverAddr: order.ReceiverAddr,
ReceiverCity: order.ReceiverCity,
ChatID: order.ChatID,
SpecName: order.SpecName,
SpecValue: order.SpecValue,
Quantity: order.Quantity,
Amount: order.Amount,
})
return len(contents), nil
}
func (a *Account) currentSenderState() (*ws.Conn, string, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.conn == nil {
return nil, "", fmt.Errorf("账号 %s 当前没有可用 WebSocket 连接", a.CookieID)
}
myID := strings.TrimSpace(a.UserID)
if myID == "" {
myID = protocol.TransCookies(a.CookieStr)["unb"]
}
if myID == "" {
return nil, "", fmt.Errorf("账号 %s 缺少 unb,无法发送消息", a.CookieID)
}
return a.conn, myID, nil
}
func (a *Account) replaceCookieStr(cookieStr string) {
a.mu.Lock()
defer a.mu.Unlock()
a.CookieStr = cookieStr
if unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" {
if a.UserID != "" && a.UserID != unb {
a.deviceID = protocol.GenerateDeviceID(unb)
}
a.UserID = unb
if a.deviceID == "" {
a.deviceID = protocol.GenerateDeviceID(unb)
}
}
}
// UpdateCookie 用外部刷新得到的新 cookie 更新运行时状态。
func (a *Account) UpdateCookie(cookieStr string) {
if strings.TrimSpace(cookieStr) == "" {
return
}
a.replaceCookieStr(cookieStr)
}
func minDuration(a, b time.Duration) time.Duration {
if a < b {
return a
}
return b
}
+186
View File
@@ -0,0 +1,186 @@
// ai.go AI 回复实现(优先级3)。调用 OpenAI 兼容 chat completions 接口。
// 移植自 Python ai_reply_engine.generate_reply 的核心:用商品信息 + 自定义 prompt 生成回复。
// 砍价/对话历史追踪(bargain_count、ai_conversations)留后续完善,本实现为单轮无状态回复。
package engine
import (
"context"
"fmt"
"log/slog"
"regexp"
"strings"
"github.com/sashabaranov/go-openai"
"xianyu-go/internal/db"
)
const (
defaultAIBaseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
defaultAIModel = "qwen-plus"
)
// AIReplierImpl AI 回复实现。
type AIReplierImpl struct {
cookieID string
store *db.Store
logger *slog.Logger
}
// NewAIReplier 构造。
func NewAIReplier(cookieID string, store *db.Store, logger *slog.Logger) *AIReplierImpl {
if logger == nil {
logger = slog.Default()
}
return &AIReplierImpl{
cookieID: cookieID,
store: store,
logger: logger.With("account", cookieID, "subsys", "ai"),
}
}
// Reply 实现 AIReplier 接口。
func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult, error) {
cfg, err := a.store.AIReply.Get(ctx, a.cookieID)
if err != nil || cfg == nil || !cfg.AIEnabled {
return nil, nil // 未启用 AI
}
aiCfg, err := a.globalAIConfig(ctx)
if err != nil {
return nil, fmt.Errorf("读取全局 AI 配置失败: %w", err)
}
if aiCfg.APIKey == "" {
a.logger.Warn("AI 已启用但未配置 APIKey")
return nil, nil
}
// 取商品信息构造 system prompt。
itemTitle, itemPrice, itemDesc := a.itemInfo(ctx, m.ItemID)
systemPrompt := buildSystemPrompt(cfg.CustomPrompts, itemTitle, itemPrice, itemDesc, cfg.MaxDiscountPercent, cfg.MaxDiscountAmount)
// 调 OpenAI 兼容接口。
clientCfg := openai.DefaultConfig(aiCfg.APIKey)
if aiCfg.BaseURL != "" {
clientCfg.BaseURL = aiCfg.BaseURL
}
client := openai.NewClientWithConfig(clientCfg)
resp, err := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
Model: aiCfg.Model,
Messages: []openai.ChatCompletionMessage{
{Role: openai.ChatMessageRoleSystem, Content: systemPrompt},
{Role: openai.ChatMessageRoleUser, Content: m.Text},
},
Temperature: 0.7,
})
if err != nil {
return nil, fmt.Errorf("AI 调用失败: %w", err)
}
if len(resp.Choices) == 0 {
return nil, nil
}
reply := strings.TrimSpace(resp.Choices[0].Message.Content)
if reply == "" {
return nil, nil
}
return &ReplyResult{Text: reply}, nil
}
type globalAIConfig struct {
APIKey string
BaseURL string
Model string
}
func (a *AIReplierImpl) globalAIConfig(ctx context.Context) (*globalAIConfig, error) {
apiKey, err := a.store.Settings.Get(ctx, "ai_api_key")
if err != nil {
return nil, err
}
baseURL, err := a.store.Settings.Get(ctx, "ai_api_url")
if err != nil {
return nil, err
}
if strings.TrimSpace(baseURL) == "" {
baseURL, err = a.store.Settings.Get(ctx, "ai_base_url")
if err != nil {
return nil, err
}
}
model, err := a.store.Settings.Get(ctx, "ai_model")
if err != nil {
return nil, err
}
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
if baseURL == "" {
baseURL = defaultAIBaseURL
}
model = strings.TrimSpace(model)
if model == "" {
model = defaultAIModel
}
return &globalAIConfig{
APIKey: strings.TrimSpace(apiKey),
BaseURL: baseURL,
Model: model,
}, nil
}
// itemInfo 取商品标题/价格/描述。
func (a *AIReplierImpl) itemInfo(ctx context.Context, itemID string) (title string, price float64, desc string) {
it, err := a.store.Items.Get(ctx, a.cookieID, itemID)
if err != nil || it == nil {
return "商品信息获取失败", 0, "暂无商品描述"
}
title = it.ItemTitle
if title == "" {
title = "未知商品"
}
price = parsePrice(it.ItemPrice)
desc = it.ItemDetail
if desc == "" {
desc = "暂无商品描述"
}
return
}
// buildSystemPrompt 构造 system 提示词。
// 优先用自定义 prompt,否则用默认模板(含商品信息)。
func buildSystemPrompt(customPrompts, itemTitle string, itemPrice float64, itemDesc string, maxDiscountPercent, maxDiscountAmount int) string {
if strings.TrimSpace(customPrompts) != "" {
return strings.ReplaceAll(customPrompts, "{item_title}", itemTitle)
}
if maxDiscountPercent <= 0 {
maxDiscountPercent = 10
}
if maxDiscountAmount <= 0 {
maxDiscountAmount = 100
}
return fmt.Sprintf(`你是闲鱼卖家的自动回复助手。请根据商品信息友好地回复买家。
商品信息:
- 标题:%s
- 价格:%.2f 元
- 描述:%s
要求:
1. 语气友好自然,像真人卖家
2. 回答简洁,不要过长
3. 涉及价格让步时,最多优惠 %.0f%% 或 %.0f 元
4. 不要编造商品没有的功能
5. 直接回复内容,不要加引号或解释`, itemTitle, itemPrice, itemDesc, float64(maxDiscountPercent), float64(maxDiscountAmount))
}
var priceRe = regexp.MustCompile(`[^\d.]`)
// parsePrice 复刻 Python _parse_price:移除非数字字符后转 float。
func parsePrice(s string) float64 {
cleaned := priceRe.ReplaceAllString(s, "")
if cleaned == "" {
return 0
}
var f float64
fmt.Sscanf(cleaned, "%f", &f)
return f
}
+882
View File
@@ -0,0 +1,882 @@
// delivery.go 实现卡密自动发货全流程。
// 移植自 Python _handle_auto_delivery + _auto_delivery:
//
// 商品归属校验 → 提取 order_id → 四重防重(延迟锁/冷却 + 加锁后复查)
// → 多规格/多数量检查 → 规则双向模糊匹配 → 延时 → 确认发货(mtop consign)
// → 入库 → 发消息 → 防重标记 → 通知
package engine
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
// 自动发货触发关键字(买家"我已付款"等系统消息)。
var autoDeliveryKeywords = []string{
"[我已付款,等待你发货]",
"[已付款,待发货]",
"我已付款,等待你发货",
"[记得及时发货]",
}
// IsAutoDeliveryTrigger 消息文本是否触发自动发货。
func IsAutoDeliveryTrigger(text string) bool {
for _, kw := range autoDeliveryKeywords {
if strings.Contains(text, kw) {
return true
}
}
return false
}
// 发货锁与冷却配置。
const (
DeliveryCooldown = 10 * time.Minute // 同一订单 10 分钟内不重复发货
DeliveryLockHold = 10 * time.Minute // 发货后持有延迟锁 10 分钟
ConfirmCooldown = 30 * time.Second // 同一订单确认发货冷却
)
// DeliverySender 抽象"发送消息给买家"的能力(由 Account 注入,复用其 WS 连接)。
type DeliverySender interface {
SendText(ctx context.Context, chatID, toUserID, text string) error
SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64) error
}
// OrderDetailFetcher 抽象"取订单详情"(多规格/多数量需要,Phase 5 由 sidecar 提供)。
type OrderDetailFetcher interface {
Fetch(ctx context.Context, cookieID, orderID, itemID, buyerID, cookieStr string) (*OrderDetail, error)
}
// OrderDetail 订单详情关键字段。
type OrderDetail struct {
Quantity string
SpecName string
SpecValue string
Amount string
OrderStatus string
}
// Notifier 发货通知(Phase 3 后段实现,先接口占位)。
type Notifier interface {
NotifyDelivery(accountID, buyerName, buyerID, itemID, message, chatID string)
}
// DeliveryService 单账号发货服务(每个 Account 持有一个)。
type DeliveryService struct {
cookieID string
store *db.Store
mtop *mtop.Client
sender DeliverySender
fetcher OrderDetailFetcher // 可为 nil(未配置多规格/多数量时不调用)
notifier Notifier // 可为 nil
logger *slog.Logger
// 防重状态
mu sync.Mutex
locks map[string]*deliveryLock // order_id → 延迟锁
lastDelivery map[string]time.Time // order_id → 上次发货时间(冷却)
confirmedOrder map[string]time.Time // order_id → 上次确认发货时间
// cookie 源/汇:与 Account 共享可变 cookie(发货/确认发货会刷新 cookie)
cookieSrc func() string
cookieSink func(string)
}
type deliveryLock struct {
locked bool
releasedAt time.Time
timer *time.Timer
mux sync.Mutex // per-order 串行锁
}
// NewDeliveryService 构造。
func NewDeliveryService(cookieID string, store *db.Store, sender DeliverySender,
fetcher OrderDetailFetcher, notifier Notifier, logger *slog.Logger) *DeliveryService {
if logger == nil {
logger = slog.Default()
}
return &DeliveryService{
cookieID: cookieID,
store: store,
mtop: &mtop.Client{},
sender: sender,
fetcher: fetcher,
notifier: notifier,
logger: logger.With("account", cookieID, "subsys", "delivery"),
locks: make(map[string]*deliveryLock),
lastDelivery: make(map[string]time.Time),
confirmedOrder: make(map[string]time.Time),
}
}
// Handle 收到一条聊天消息,若为自动发货触发关键字则执行发货流程。
// 由 Account 在防抖后调用(HandleChatMessage 适配)。
func (d *DeliveryService) Handle(ctx context.Context, m ChatMessage) error {
if !IsAutoDeliveryTrigger(m.Text) {
return nil
}
return d.handleAutoDelivery(ctx, m.Raw, m.ChatID, m.SenderUserID, m.SenderName, m.ItemID)
}
// handleAutoDelivery 发货主流程。
func (d *DeliveryService) handleAutoDelivery(ctx context.Context, raw map[string]any,
chatID, sendUserID, sendUserName, itemID string) error {
// 1. 商品归属校验。
if itemID != "" && itemID != "未知商品" {
if _, err := d.store.Items.Get(ctx, d.cookieID, itemID); err != nil {
d.logger.Warn("商品不属于当前账号或查询失败,跳过发货", "item_id", itemID, "err", err)
return nil
}
}
// 2. 提取 order_id。
orderID := extractOrderID(raw)
if orderID == "" {
d.logger.Warn("未能提取到订单ID,跳过自动发货")
return nil
}
// 3. 四重防重(延迟锁 + 冷却 + 加锁后复查)。
if d.isLockHeld(orderID) {
d.logger.Info("订单延迟锁持有中,跳过发货", "order_id", orderID)
return nil
}
if !d.canAutoDelivery(orderID) {
d.logger.Info("订单冷却期内,跳过发货", "order_id", orderID)
return nil
}
// 加订单级互斥锁(同一 order_id 串行处理)。
unlock := d.acquireOrderLock(orderID)
defer unlock()
if d.isLockHeld(orderID) {
d.logger.Info("获取锁后延迟锁仍持有,跳过", "order_id", orderID)
return nil
}
if !d.canAutoDelivery(orderID) {
d.logger.Info("获取锁后仍在冷却期,跳过", "order_id", orderID)
return nil
}
// 4. 订单详情只抓取一次:用于补全实付金额,并按需读取规格/购买数量。
quantity := 1
specName, specValue := "", ""
isMultiSpec := d.store.Items.IsMultiSpec(ctx, d.cookieID, itemID)
isMultiQuantity := d.store.Items.MultiQuantityDelivery(ctx, d.cookieID, itemID)
needDetail := isMultiSpec || isMultiQuantity
if existing, err := d.store.Orders.Get(ctx, orderID); err != nil || strings.TrimSpace(existing.Amount) == "" {
needDetail = true
}
if d.fetcher != nil && needDetail {
od, err := d.fetcher.Fetch(ctx, d.cookieID, orderID, itemID, sendUserID, d.cookieStr())
if err != nil {
d.logger.Warn("获取订单详情失败,继续尝试自动发货", "order_id", orderID, "err", err)
} else if od != nil {
specName, specValue = od.SpecName, od.SpecValue
_ = d.store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{
CookieID: d.cookieID, ItemID: itemID, BuyerID: sendUserID,
SpecName: od.SpecName, SpecValue: od.SpecValue, Quantity: od.Quantity,
Amount: od.Amount, OrderStatus: od.OrderStatus,
})
if isMultiQuantity {
if q := parseIntSafe(od.Quantity); q > 1 {
quantity = q
d.logger.Info("多数量发货", "quantity", quantity, "order_id", orderID)
}
}
}
}
// 5. 循环获取发货内容。
contents, err := d.collectDeliveryContentsWithSpec(ctx, itemID, orderID, sendUserID, specName, specValue, quantity)
if err != nil {
d.notify(sendUserName, sendUserID, itemID, "自动发货处理异常: "+err.Error(), chatID)
return err
}
if len(contents) == 0 {
d.logger.Warn("未找到匹配的发货规则或获取发货内容失败", "order_id", orderID)
d.notify(sendUserName, sendUserID, itemID, "未找到匹配的发货规则或获取发货内容失败", chatID)
return nil
}
// 6. 标记已发货 + 延迟锁 + 入库 system_shipped。
d.markDeliverySent(orderID)
sysShip := true
_ = d.store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{
SystemShipped: &sysShip,
ChatID: chatID,
ItemID: itemID,
BuyerID: sendUserID,
CookieID: d.cookieID,
})
// 7. 逐条发送,多数量间隔 1s。
for i, c := range contents {
if err := d.sendContent(ctx, c, chatID, sendUserID); err != nil {
d.logger.Error("发送发货内容失败", "index", i, "err", err)
}
if len(contents) > 1 && i < len(contents)-1 {
if sleepCtx(ctx, time.Second) != nil {
return ctx.Err()
}
}
}
// 8. 通知。
msg := "发货成功"
if len(contents) > 1 {
msg = fmt.Sprintf("多数量发货成功,共发送 %d 个卡券", len(contents))
}
d.notify(sendUserName, sendUserID, itemID, msg, chatID)
d.logger.Info("自动发货完成", "order_id", orderID, "count", len(contents))
return nil
}
// collectDeliveryContents 调用 quantity 次 _auto_delivery 等价逻辑,收集发货内容。
func (d *DeliveryService) collectDeliveryContents(ctx context.Context, itemID, orderID, sendUserID string, quantity int) ([]string, error) {
return d.collectDeliveryContentsWithSpec(ctx, itemID, orderID, sendUserID, "", "", quantity)
}
func (d *DeliveryService) collectDeliveryContentsWithSpec(ctx context.Context, itemID, orderID, sendUserID, specName, specValue string, quantity int) ([]string, error) {
contents := make([]string, 0, quantity)
for i := 0; i < quantity; i++ {
batch, err := d.autoDeliveryOnce(ctx, itemID, orderID, sendUserID, specName, specValue)
if err != nil {
d.logger.Error("获取发货内容异常", "index", i, "err", err)
continue
}
contents = append(contents, batch...)
}
return contents, nil
}
// autoDeliveryOnce 单次发货内容获取:匹配规则 → 延时 → 确认发货 → 卡券内容。
// 移植自 _auto_delivery。
func (d *DeliveryService) autoDeliveryOnce(ctx context.Context, itemID, orderID, sendUserID, knownSpecName, knownSpecValue string) ([]string, error) {
// 搜索文本 = 商品标题 + 详情。
searchText := d.buildSearchText(ctx, itemID)
// 多规格处理。
isMultiSpec := d.store.Items.IsMultiSpec(ctx, d.cookieID, itemID)
specName, specValue := strings.TrimSpace(knownSpecName), strings.TrimSpace(knownSpecValue)
if isMultiSpec && (specName == "" || specValue == "") && d.fetcher != nil {
od, err := d.fetcher.Fetch(ctx, d.cookieID, orderID, itemID, sendUserID, d.cookieStr())
if err != nil || od == nil || od.SpecName == "" || od.SpecValue == "" {
d.logger.Warn("多规格商品但无规格信息,跳过", "order_id", orderID, "err", err)
return nil, nil
}
specName, specValue = od.SpecName, od.SpecValue
}
if isMultiSpec && (specName == "" || specValue == "") {
d.logger.Warn("多规格商品缺少规格信息,跳过", "order_id", orderID)
return nil, nil
}
// 新规则按 item_id + 规格精确匹配;旧规则自动回退关键词。
if !isMultiSpec {
specName, specValue = "", ""
}
rules, err := d.store.DeliveryRules.MatchForOrder(ctx, d.cookieID, itemID, searchText, specName, specValue)
if err != nil {
return nil, fmt.Errorf("匹配发货规则失败: %w", err)
}
if len(rules) == 0 {
d.logger.Warn("未找到匹配的发货规则", "search_text", trunc(searchText, 50))
return nil, nil
}
if len(rules) > 1 {
d.logger.Warn("匹配到多个发货规则,无法确定,跳过", "count", len(rules))
return nil, nil
}
rule := rules[0]
// 延时。
if rule.CardDelaySeconds > 0 {
d.logger.Info("执行发货延时", "seconds", rule.CardDelaySeconds)
if sleepCtx(ctx, time.Duration(rule.CardDelaySeconds)*time.Second) != nil {
return nil, ctx.Err()
}
}
// 确认发货(mtop consign)。auto_confirm 仅控制平台订单状态,
// 不影响后续卡券内容发送。
if d.shouldAutoConfirm(ctx, orderID) {
d.logger.Info("确认发货", "order_id", orderID)
cookieStr := d.cookieStr()
ok, ret, updated, cerr := d.mtop.ConsignContext(ctx, cookieStr, orderID)
if cerr != nil {
d.logger.Warn("确认发货请求失败,继续发送内容", "err", cerr)
} else {
if updated != cookieStr && updated != "" {
d.setCookieStr(updated)
if err := d.store.Cookies.Save(ctx, d.cookieID, updated, 0); err != nil {
d.logger.Warn("保存确认发货更新后的 Cookie 失败", "err", err)
}
}
if ok {
d.recordConfirm(orderID)
} else {
d.logger.Warn("确认发货未成功,仍发送内容", "ret", ret)
}
}
}
// 卡券内容。
if orderID == "" {
d.logger.Info("无订单ID,跳过发货内容处理")
return nil, nil
}
deliveryCount := rule.DeliveryCount
if deliveryCount <= 0 {
deliveryCount = 1
}
contents := make([]string, 0, deliveryCount)
for i := 0; i < deliveryCount; i++ {
content := d.cardContent(ctx, rule, orderID, itemID, sendUserID, specName, specValue)
if content == "" {
break
}
contents = append(contents, processDeliveryContentWithDescription(content, rule.CardDescription))
_ = d.store.Cards.IncrementDeliveryTimes(ctx, rule.ID)
}
return contents, nil
}
// buildSearchText 商品标题 + 空格 + 详情。
func (d *DeliveryService) buildSearchText(ctx context.Context, itemID string) string {
it, err := d.store.Items.Get(ctx, d.cookieID, itemID)
if err != nil || it == nil {
return itemID
}
parts := []string{}
if strings.TrimSpace(it.ItemTitle) != "" {
parts = append(parts, strings.TrimSpace(it.ItemTitle))
}
if strings.TrimSpace(it.ItemDetail) != "" {
parts = append(parts, strings.TrimSpace(it.ItemDetail))
}
if len(parts) == 0 {
return itemID
}
return strings.Join(parts, " ")
}
// cardContent 按卡券类型取发货内容。
func (d *DeliveryService) cardContent(ctx context.Context, rule db.DeliveryRule, orderID, itemID, buyerID, specName, specValue string) string {
switch rule.CardType {
case "text":
return rule.TextContent
case "data":
c, err := d.store.Cards.ConsumeBatchData(ctx, rule.CardID)
if err != nil {
d.logger.Error("消费批量数据失败", "card_id", rule.CardID, "err", err)
return ""
}
return c
case "image":
if rule.ImageURL == "" {
d.logger.Error("图片卡券缺少 URL", "card_id", rule.CardID)
return ""
}
return fmt.Sprintf("__IMAGE_SEND__%d|%s", rule.CardID, rule.ImageURL)
case "api":
content, err := d.apiCardContent(ctx, rule, orderID, itemID, buyerID, specName, specValue)
if err != nil {
d.logger.Error("API 卡券调用失败", "card_id", rule.CardID, "err", err)
return ""
}
return content
}
return ""
}
func (d *DeliveryService) apiCardContent(ctx context.Context, rule db.DeliveryRule, orderID, itemID, buyerID, specName, specValue string) (string, error) {
cfg := rule.APIConfigMap()
if len(cfg) == 0 {
return "", fmt.Errorf("API 配置为空")
}
endpoint := strings.TrimSpace(anyString(cfg["url"]))
if endpoint == "" {
return "", fmt.Errorf("API 配置缺少 url")
}
method := strings.ToUpper(strings.TrimSpace(anyString(cfg["method"])))
if method == "" {
method = http.MethodGet
}
if method != http.MethodGet && method != http.MethodPost {
return "", fmt.Errorf("不支持的 HTTP 方法: %s", method)
}
timeoutSeconds := anyInt(cfg["timeout"])
if timeoutSeconds <= 0 {
timeoutSeconds = 10
}
if timeoutSeconds > 120 {
timeoutSeconds = 120
}
headers := parseAPIMap(cfg["headers"])
params := parseAPIMap(cfg["params"])
params = d.replaceAPIParams(ctx, params, orderID, itemID, buyerID, specName, specValue)
var lastErr error
for attempt := 0; attempt < 4; attempt++ {
if attempt > 0 {
if err := sleepCtx(ctx, time.Duration(attempt*2)*time.Second); err != nil {
return "", err
}
}
content, retry, err := d.callAPIOnce(ctx, endpoint, method, headers, params, time.Duration(timeoutSeconds)*time.Second)
if err == nil {
return content, nil
}
lastErr = err
if !retry {
break
}
}
return "", lastErr
}
func (d *DeliveryService) callAPIOnce(ctx context.Context, endpoint, method string, headers, params map[string]any, timeout time.Duration) (content string, retry bool, err error) {
reqCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var body io.Reader
if method == http.MethodPost {
raw, err := json.Marshal(params)
if err != nil {
return "", false, err
}
body = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(reqCtx, method, endpoint, body)
if err != nil {
return "", false, err
}
for k, v := range headers {
if strings.TrimSpace(k) == "" {
continue
}
req.Header.Set(k, anyString(v))
}
if method == http.MethodPost && req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/json")
}
if method == http.MethodGet && len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Set(k, anyString(v))
}
req.URL.RawQuery = q.Encode()
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", true, err
}
defer resp.Body.Close()
raw, readErr := io.ReadAll(resp.Body)
if readErr != nil {
return "", true, readErr
}
if resp.StatusCode != http.StatusOK {
retry := resp.StatusCode >= 500 || resp.StatusCode == http.StatusRequestTimeout
return "", retry, fmt.Errorf("API 返回状态 %d: %s", resp.StatusCode, trunc(string(raw), 200))
}
content = parseAPIContent(raw)
if strings.TrimSpace(content) == "" {
return "", false, fmt.Errorf("API 返回内容为空")
}
return content, false, nil
}
func parseAPIMap(v any) map[string]any {
if v == nil {
return map[string]any{}
}
switch x := v.(type) {
case map[string]any:
return x
case map[string]string:
out := make(map[string]any, len(x))
for k, v := range x {
out[k] = v
}
return out
case string:
x = strings.TrimSpace(x)
if x == "" {
return map[string]any{}
}
var m map[string]any
if err := json.Unmarshal([]byte(x), &m); err == nil {
return m
}
}
return map[string]any{}
}
func (d *DeliveryService) replaceAPIParams(ctx context.Context, params map[string]any, orderID, itemID, buyerID, specName, specValue string) map[string]any {
mapping := map[string]string{
"order_id": orderID,
"item_id": itemID,
"buyer_id": buyerID,
"cookie_id": d.cookieID,
"spec_name": specName,
"spec_value": specValue,
}
if orderID != "" {
if ord, err := d.store.Orders.Get(ctx, orderID); err == nil && ord != nil {
mapping["order_amount"] = ord.Amount
mapping["order_quantity"] = ord.Quantity
}
}
if itemID != "" {
if it, err := d.store.Items.Get(ctx, d.cookieID, itemID); err == nil && it != nil {
itemDetail := it.ItemDetail
var detail map[string]any
if json.Unmarshal([]byte(itemDetail), &detail) == nil {
if d, ok := detail["detail"].(string); ok {
itemDetail = d
}
}
mapping["item_detail"] = itemDetail
}
}
return replaceRecursive(params, mapping).(map[string]any)
}
func replaceRecursive(v any, mapping map[string]string) any {
switch x := v.(type) {
case map[string]any:
out := make(map[string]any, len(x))
for k, v := range x {
out[k] = replaceRecursive(v, mapping)
}
return out
case []any:
out := make([]any, len(x))
for i, v := range x {
out[i] = replaceRecursive(v, mapping)
}
return out
case string:
out := x
for k, v := range mapping {
out = strings.ReplaceAll(out, "{"+k+"}", v)
}
return out
default:
return v
}
}
func parseAPIContent(raw []byte) string {
var v any
if json.Unmarshal(raw, &v) != nil {
return strings.TrimSpace(string(raw))
}
if m, ok := v.(map[string]any); ok {
for _, key := range []string{"data", "content", "card"} {
if val, ok := m[key]; ok && val != nil {
return anyString(val)
}
}
}
return anyString(v)
}
func anyString(v any) string {
switch x := v.(type) {
case string:
return x
case nil:
return ""
default:
b, _ := json.Marshal(x)
return string(b)
}
}
func anyInt(v any) int {
switch x := v.(type) {
case int:
return x
case int64:
return int(x)
case float64:
return int(x)
case json.Number:
n, _ := strconv.Atoi(x.String())
return n
case string:
n, _ := strconv.Atoi(strings.TrimSpace(x))
return n
default:
return 0
}
}
// sendContent 发送一条发货内容(文本或图片)。
func (d *DeliveryService) sendContent(ctx context.Context, content, chatID, toUserID string) error {
if d.sender == nil {
return nil
}
if strings.HasPrefix(content, "__IMAGE_SEND__") {
rest := strings.TrimPrefix(content, "__IMAGE_SEND__")
var cardID int64
imageURL := rest
if i := strings.Index(rest, "|"); i >= 0 {
cardID = int64(parseIntSafe(rest[:i]))
imageURL = rest[i+1:]
}
return d.sender.SendImage(ctx, chatID, toUserID, imageURL, cardID)
}
return d.sender.SendText(ctx, chatID, toUserID, content)
}
// processDeliveryContentWithDescription 复刻 Python 备注/变量替换逻辑。
func processDeliveryContentWithDescription(content, description string) string {
if strings.HasPrefix(content, "__IMAGE_SEND__") {
return content
}
desc := strings.TrimSpace(description)
if desc == "" {
return content
}
if strings.Contains(desc, "{DELIVERY_CONTENT}") {
return strings.ReplaceAll(desc, "{DELIVERY_CONTENT}", content)
}
return desc + "\n\n" + content
}
func (d *DeliveryService) notify(buyerName, buyerID, itemID, message, chatID string) {
if d.notifier != nil {
d.notifier.NotifyDelivery(d.cookieID, buyerName, buyerID, itemID, message, chatID)
}
}
// ---- 防重状态机 ----
func (d *DeliveryService) isLockHeld(orderID string) bool {
d.mu.Lock()
defer d.mu.Unlock()
l, ok := d.locks[orderID]
return ok && l.locked
}
func (d *DeliveryService) canAutoDelivery(orderID string) bool {
if orderID == "" {
return true
}
d.mu.Lock()
defer d.mu.Unlock()
if last, ok := d.lastDelivery[orderID]; ok {
if time.Since(last) < DeliveryCooldown {
return false
}
}
return true
}
func (d *DeliveryService) markDeliverySent(orderID string) {
d.mu.Lock()
defer d.mu.Unlock()
d.lastDelivery[orderID] = time.Now()
// 设置延迟锁,10 分钟后释放。
l := &deliveryLock{locked: true}
if old, ok := d.locks[orderID]; ok && old.timer != nil {
old.timer.Stop()
}
l.timer = time.AfterFunc(DeliveryLockHold, func() {
d.mu.Lock()
defer d.mu.Unlock()
if cur, ok := d.locks[orderID]; ok {
cur.locked = false
cur.releasedAt = time.Now()
}
})
d.locks[orderID] = l
}
// acquireOrderLock 返回释放函数,对同一 order_id 串行化。
// 简化实现:用一个 per-order 互斥(map 里存 *sync.Mutex)。
func (d *DeliveryService) acquireOrderLock(orderID string) func() {
d.mu.Lock()
l, ok := d.locks[orderID]
if !ok {
l = &deliveryLock{}
d.locks[orderID] = l
}
d.mu.Unlock()
l.mux.Lock()
return l.mux.Unlock
}
func (d *DeliveryService) shouldConfirm(orderID string) bool {
d.mu.Lock()
defer d.mu.Unlock()
if last, ok := d.confirmedOrder[orderID]; ok {
if time.Since(last) < ConfirmCooldown {
return false
}
}
return true
}
func (d *DeliveryService) shouldAutoConfirm(ctx context.Context, orderID string) bool {
if orderID == "" {
return false
}
enabled, err := d.store.Cookies.GetAutoConfirm(ctx, d.cookieID)
if err != nil {
d.logger.Warn("读取自动确认发货设置失败,跳过确认发货", "err", err)
return false
}
if !enabled {
d.logger.Info("自动确认发货已关闭,跳过确认发货", "order_id", orderID)
return false
}
return d.shouldConfirm(orderID)
}
func (d *DeliveryService) recordConfirm(orderID string) {
d.mu.Lock()
defer d.mu.Unlock()
d.confirmedOrder[orderID] = time.Now()
}
// SetCookieSource 让 DeliveryService 与 Account 共享可变 cookie。
func (d *DeliveryService) SetCookieSource(src func() string, sink func(string)) {
d.cookieSrc = src
d.cookieSink = sink
}
// cookieStr 取当前 cookie。
func (d *DeliveryService) cookieStr() string {
if d.cookieSrc != nil {
return d.cookieSrc()
}
return ""
}
func (d *DeliveryService) setCookieStr(s string) {
if d.cookieSink != nil {
d.cookieSink(s)
}
}
// ---- 提取与辅助 ----
// 订单 ID 提取正则(复刻 Python _extract_order_id 的多模式兜底)。
var orderIDPatterns = []*regexp.Regexp{
regexp.MustCompile(`orderId[=:](\d{10,})`),
regexp.MustCompile(`order_detail\?id=(\d{10,})`),
regexp.MustCompile(`bizOrderId[=:](\d{10,})`),
}
// extractOrderID 从解密消息中提取订单 ID。
// 优先从 message["1"]["6"]["3"]["5"](dxCard JSON)的 button.targetUrl 中提取。
func extractOrderID(decrypted map[string]any) string {
// 方法1:从 button/main targetUrl 提取。
if contentJSON := nestedString(decrypted, "1", "6", "3", "5"); contentJSON != "" {
if id := extractOrderIDFromContent(contentJSON); id != "" {
return id
}
}
// 方法2:兜底——整个消息转字符串搜模式。
raw, _ := json.Marshal(decrypted)
rawStr := string(raw)
for _, p := range orderIDPatterns {
if m := p.FindStringSubmatch(rawStr); len(m) > 1 {
return m[1]
}
}
return ""
}
func extractOrderIDFromContent(contentJSON string) string {
var c map[string]any
if err := json.Unmarshal([]byte(contentJSON), &c); err != nil {
return ""
}
// dxCard.item.main.exContent.button.targetUrl → orderId=xxx
buttonURL := nestedString(c, "dxCard", "item", "main", "exContent", "button", "targetUrl")
if id := matchOrderID(buttonURL); id != "" {
return id
}
// dxCard.item.main.targetUrl → order_detail?id=xxx
mainURL := nestedString(c, "dxCard", "item", "main", "targetUrl")
if id := matchOrderID(mainURL); id != "" {
return id
}
// dynamicOperation.changeContent.dxCard...
dynURL := nestedString(c, "dynamicOperation", "changeContent", "dxCard", "item", "main", "exContent", "button", "targetUrl")
return matchOrderID(dynURL)
}
func matchOrderID(url string) string {
if url == "" {
return ""
}
for _, p := range orderIDPatterns {
if m := p.FindStringSubmatch(url); len(m) > 1 {
return m[1]
}
}
return ""
}
// nestedString 沿 path 取嵌套 map 中的字符串值。
func nestedString(m map[string]any, path ...string) string {
cur := m
for i, k := range path {
if i == len(path)-1 {
if s, ok := cur[k].(string); ok {
return s
}
return ""
}
next, ok := cur[k].(map[string]any)
if !ok {
return ""
}
cur = next
}
return ""
}
func filterMultiSpec(rules []db.DeliveryRule, multiSpec bool) []db.DeliveryRule {
out := rules[:0]
for _, r := range rules {
if r.IsMultiSpec == multiSpec {
out = append(out, r)
}
}
return out
}
func parseIntSafe(s string) int {
n, _ := strconv.Atoi(strings.TrimSpace(s))
return n
}
func trunc(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "..."
}
+269
View File
@@ -0,0 +1,269 @@
package engine
import (
"context"
"path/filepath"
"testing"
"time"
"xianyu-go/internal/db"
)
func newDeliveryStore(t *testing.T) (*db.Store, func()) {
t.Helper()
d, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
s := db.NewStore(d)
// 初始化 admin + 一个账号。
s.Users.Create(context.Background(), "admin", "[email protected]", "pw")
admin, _ := s.Users.GetByUsername(context.Background(), "admin")
s.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
return s, func() { d.Close() }
}
// TestIsAutoDeliveryTrigger 触发关键字检测。
func TestIsAutoDeliveryTrigger(t *testing.T) {
cases := map[string]bool{
"[我已付款,等待你发货]": true,
"买家说:[我已付款,等待你发货] 谢谢": true,
"[已付款,待发货]": true,
"[记得及时发货]": true,
"我已付款,等待你发货": true,
"你好,这个还在吗": false,
"已付款,待发货": false, // 无括号变体不在触发列表中
"": false,
}
for in, want := range cases {
if got := IsAutoDeliveryTrigger(in); got != want {
t.Errorf("IsAutoDeliveryTrigger(%q)=%v want %v", in, got, want)
}
}
}
// TestExtractOrderID 从真实样本结构提取订单 ID。
func TestExtractOrderID(t *testing.T) {
// dxCard 的 button.targetUrl 含 orderId。
msg := map[string]any{
"1": map[string]any{
"6": map[string]any{
"3": map[string]any{
"5": `{"dxCard":{"item":{"main":{"exContent":{"button":{"targetUrl":"fleamarket://adjust_price?bizOrderId=2503688126356636370"}}}}}}`,
},
},
},
}
if id := extractOrderID(msg); id != "2503688126356636370" {
t.Errorf("extractOrderID=%q want 2503688126356636370", id)
}
}
// TestExtractOrderID_FallbackString 整消息字符串兜底。
func TestExtractOrderID_FallbackString(t *testing.T) {
msg := map[string]any{
"raw": "some text with bizOrderId=98765432109987654 inside",
}
if id := extractOrderID(msg); id != "98765432109987654" {
t.Errorf("fallback extractOrderID=%q", id)
}
}
// TestDeliveryRuleMatching 验证双向模糊匹配 SQL 与多规格过滤。
func TestDeliveryRuleMatching(t *testing.T) {
s, cleanup := newDeliveryStore(t)
defer cleanup()
ctx := context.Background()
admin, _ := s.Users.GetByUsername(ctx, "admin")
// 一个 text 卡券 + 一个 data 卡券(非多规格)。
s.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,data_content,enabled,user_id) VALUES
(1,'VIP卡','text','您的卡密:ABC123',NULL,1,?),
(2,'数据卡','data',NULL,'line1\nline2\nline3',1,?)`, admin.ID, admin.ID)
// 多规格卡券。
s.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,enabled,is_multi_spec,spec_name,spec_value,user_id) VALUES
(3,'红色版','text','红色发货码',1,1,'颜色','红',?)`, admin.ID)
// 发货规则:关键字"VIP" → 卡券1;"商品" → 卡券2;"红色" → 卡券3。
s.DB.ExecContext(ctx, `INSERT INTO delivery_rules (id,keyword,card_id,enabled,user_id) VALUES
(1,'VIP',1,1,?),(2,'商品',2,1,?),(3,'红色',3,1,?)`, admin.ID, admin.ID, admin.ID)
// 非多规格匹配:商品文本"我的VIP商品"应命中规则1(VIP 含于文本,长度优先)+规则2("商品"含于文本)。
rules, err := s.DeliveryRules.MatchByKeyword(ctx, "我的VIP商品")
if err != nil {
t.Fatalf("MatchByKeyword: %v", err)
}
if len(rules) != 2 {
t.Fatalf("应匹配2条非多规格规则,got %d", len(rules))
}
// 长度降序:VIP(3) > 商品(2),规则1应在前。
if rules[0].ID != 1 {
t.Errorf("应按关键字长度降序,首条=%d want 1", rules[0].ID)
}
// 多规格匹配。
msRules, err := s.DeliveryRules.MatchByKeywordAndSpec(ctx, "红色商品", "颜色", "红")
if err != nil {
t.Fatalf("MatchByKeywordAndSpec: %v", err)
}
if len(msRules) != 1 || msRules[0].ID != 3 {
t.Fatalf("多规格应只匹配规则3,got %+v", msRules)
}
}
func TestDeliveryRuleMatchingByItemAndVariant(t *testing.T) {
s, cleanup := newDeliveryStore(t)
defer cleanup()
ctx := context.Background()
admin, _ := s.Users.GetByUsername(ctx, "admin")
_, _ = s.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,enabled,user_id) VALUES
(11,'30天库存','text','CODE30',1,?),
(12,'90天库存','text','CODE90',1,?)`, admin.ID, admin.ID)
_, _ = s.DB.ExecContext(ctx, `INSERT INTO delivery_rules
(id,keyword,card_id,delivery_count,enabled,user_id,cookie_id,item_id)
VALUES (21,'会员',11,1,1,?,'cid','item-vip')`, admin.ID)
_, _ = s.DB.ExecContext(ctx, `INSERT INTO delivery_rule_variants
(rule_id,spec_name,spec_value,card_id,delivery_count,enabled) VALUES
(21,'套餐','30天',11,1,1),(21,'套餐','90天',12,2,1)`)
rules, err := s.DeliveryRules.MatchForOrder(ctx, "cid", "item-vip", "任意标题", "套餐", "90天")
if err != nil {
t.Fatalf("MatchForOrder: %v", err)
}
if len(rules) != 1 || rules[0].CardID != 12 || rules[0].DeliveryCount != 2 {
t.Fatalf("规格映射错误: %+v", rules)
}
other, err := s.DeliveryRules.MatchForOrder(ctx, "other", "item-vip", "任意标题", "套餐", "90天")
if err != nil {
t.Fatal(err)
}
if len(other) != 0 {
t.Fatalf("其他账号不应命中规则: %+v", other)
}
}
// TestConsumeBatchData data 卡券逐行消费。
func TestConsumeBatchData(t *testing.T) {
s, cleanup := newDeliveryStore(t)
defer cleanup()
ctx := context.Background()
admin, _ := s.Users.GetByUsername(ctx, "admin")
// 创建一个 data 卡券(id=2)。
s.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,data_content,enabled,user_id) VALUES (2,'数据卡','data','line1'||char(10)||'line2'||char(10)||'line3',1,?)`, admin.ID)
c1, err := s.Cards.ConsumeBatchData(ctx, 2)
if err != nil {
t.Fatalf("ConsumeBatchData: %v", err)
}
if c1 != "line1" {
t.Errorf("首次消费=%q want line1", c1)
}
c2, _ := s.Cards.ConsumeBatchData(ctx, 2)
if c2 != "line2" {
t.Errorf("二次消费=%q want line2", c2)
}
c3, _ := s.Cards.ConsumeBatchData(ctx, 2)
if c3 != "line3" {
t.Errorf("三次消费=%q want line3", c3)
}
// 第四次应失败(已空)。
if _, err := s.Cards.ConsumeBatchData(ctx, 2); err == nil {
t.Fatal("数据耗尽应报错")
}
}
// TestDedupMachine 四重防重:冷却 + 延迟锁。
func TestDedupMachine(t *testing.T) {
s, cleanup := newDeliveryStore(t)
defer cleanup()
d := NewDeliveryService("cid", s, nil, nil, nil, nil)
d.SetCookieSource(func() string { return "" }, func(string) {})
// 冷却:无发货记录时允许。
if !d.canAutoDelivery("order1") {
t.Fatal("首次应允许发货")
}
// 标记已发货 → 10 分钟冷却。
d.markDeliverySent("order1")
if d.canAutoDelivery("order1") {
t.Fatal("发货后应进入冷却期")
}
if !d.isLockHeld("order1") {
t.Fatal("发货后延迟锁应持有")
}
// 不同订单不受影响。
if !d.canAutoDelivery("order2") {
t.Fatal("order2 不应受 order1 冷却影响")
}
}
func TestShouldAutoConfirmRespectsAccountSetting(t *testing.T) {
s, cleanup := newDeliveryStore(t)
defer cleanup()
ctx := context.Background()
d := NewDeliveryService("cid", s, nil, nil, nil, nil)
if !d.shouldAutoConfirm(ctx, "order1") {
t.Fatal("默认开启时应允许自动确认发货")
}
if _, err := s.DB.ExecContext(ctx, `UPDATE cookies SET auto_confirm=0 WHERE id=?`, "cid"); err != nil {
t.Fatalf("关闭 auto_confirm: %v", err)
}
if d.shouldAutoConfirm(ctx, "order2") {
t.Fatal("关闭设置后不应自动确认发货")
}
if d.shouldAutoConfirm(ctx, "") {
t.Fatal("缺少订单 ID 时不应自动确认发货")
}
}
// TestProcessDeliveryContentWithDescription 备注/变量替换。
func TestProcessDeliveryContentWithDescription(t *testing.T) {
// 有 {DELIVERY_CONTENT} 变量。
got := processDeliveryContentWithDescription("ABC123", "您的卡密是 {DELIVERY_CONTENT},请妥善保管")
want := "您的卡密是 ABC123,请妥善保管"
if got != want {
t.Errorf("变量替换: got %q want %q", got, want)
}
// 无变量:备注 + 内容。
got = processDeliveryContentWithDescription("ABC123", "温馨提示")
if got != "温馨提示\n\nABC123" {
t.Errorf("无变量组合: got %q", got)
}
// 图片标记不处理。
got = processDeliveryContentWithDescription("__IMAGE_SEND__1|http://x", "备注")
if got != "__IMAGE_SEND__1|http://x" {
t.Errorf("图片标记不应处理: got %q", got)
}
// 无备注直接返回。
got = processDeliveryContentWithDescription("ABC123", "")
if got != "ABC123" {
t.Errorf("无备注: got %q", got)
}
}
// TestAcquireOrderLockSerializes 同一 order_id 串行化。
func TestAcquireOrderLockSerializes(t *testing.T) {
s, cleanup := newDeliveryStore(t)
defer cleanup()
d := NewDeliveryService("cid", s, nil, nil, nil, nil)
done := make(chan struct{})
// 先获取锁。
unlock := d.acquireOrderLock("orderX")
go func() {
defer close(done)
d.acquireOrderLock("orderX") // 应阻塞
}()
select {
case <-done:
t.Fatal("锁未释放前第二个获取应阻塞")
case <-time.After(100 * time.Millisecond):
}
unlock()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("释放后第二个应能获取")
}
}
+438
View File
@@ -0,0 +1,438 @@
package engine
import (
"context"
"encoding/json"
"strings"
"time"
)
// dispatch 是 ws.ReceiveLoop 的回调,对每条解密后的消息做:
// 标记消息接收时间 → 提取消息 ID 去重 → 信号量限并发 → 分类(聊天/系统)→ 防抖投递。
func (a *Account) dispatch(decrypted map[string]any) {
a.mu.Lock()
a.lastMsgReceived = time.Now()
a.mu.Unlock()
// 信号量限并发(非阻塞获取,超限则丢弃并告警——避免阻塞 WS 读取)。
select {
case a.sem <- struct{}{}:
default:
a.logger.Warn("消息处理并发达上限,丢弃消息", "limit", MessageSemaphoreSize)
return
}
go func() {
defer func() { <-a.sem }()
a.handleMessage(decrypted)
}()
}
// handleMessage 分类并投递消息。
func (a *Account) handleMessage(decrypted map[string]any) {
chat := extractChatMessage(decrypted, a.CookieID, a.currentCookieStr())
if chat != nil && chat.Text != "" {
// 去重。
if !a.markAndCheckDedup(decrypted, chat) {
return
}
// 自动发货触发消息必须立即处理,不能进入普通聊天防抖。
// 否则闲鱼紧随其后的系统提示(如“不想宝贝被砍价”)可能覆盖付款卡片,
// 造成未发货且进入 AI 回复。
if IsAutoDeliveryTrigger(chat.Text) {
a.cancelDebouncedReply(chat.ChatID)
if a.delivery != nil {
if err := a.delivery.Handle(context.Background(), *chat); err != nil {
a.logger.Error("处理自动发货失败", "err", err, "chat_id", chat.ChatID)
}
}
if a.handler != nil {
if err := a.handler.HandleChatMessage(context.Background(), *chat); err != nil {
a.logger.Error("处理聊天消息失败", "err", err, "chat_id", chat.ChatID)
}
}
return
}
// 普通聊天消息走防抖,合并连续文本后再自动回复。
a.scheduleDebouncedReply(*chat)
return
}
sys := extractSystemMessage(decrypted, a.CookieID, a.currentCookieStr())
if sys != nil && sys.RedReminder != "" && a.handler != nil {
if err := a.handler.HandleSystemMessage(context.Background(), *sys); err != nil {
a.logger.Error("处理系统消息失败", "err", err)
}
}
}
func (a *Account) cancelDebouncedReply(chatID string) {
if chatID == "" {
return
}
a.debounceMu.Lock()
defer a.debounceMu.Unlock()
if old, ok := a.debounceTimers[chatID]; ok {
if old.timer != nil {
old.timer.Stop()
}
delete(a.debounceTimers, chatID)
}
}
// markAndCheckDedup 提取消息 ID,检查 1 小时内是否已处理;未处理则标记。
// 返回 true 表示应继续处理。移植自 _schedule_debounced_reply 的去重段。
func (a *Account) markAndCheckDedup(decrypted map[string]any, chat *ChatMessage) bool {
msgID := extractMessageID(decrypted)
if msgID == "" {
// 备用标识:chat_id + text + create_time。
createTime := "0"
if m1, ok := decrypted["1"].(map[string]any); ok {
if t, ok := m1["5"]; ok {
createTime = toString(t)
}
}
msgID = chat.ChatID + "_" + chat.Text + "_" + createTime
}
a.dedupMu.Lock()
defer a.dedupMu.Unlock()
now := time.Now()
if last, ok := a.processed[msgID]; ok {
if now.Sub(last) < MessageExpireTime {
a.logger.Info("消息已处理过,跳过", "msg_id", truncID(msgID))
return false
}
}
a.processed[msgID] = now
// 清理:超上限时删过期记录,仍超则删最旧一半。
if len(a.processed) > ProcessedIDsMaxSize {
a.cleanupDedupLocked(now)
}
return true
}
func (a *Account) cleanupDedupLocked(now time.Time) {
for id, t := range a.processed {
if now.Sub(t) > MessageExpireTime {
delete(a.processed, id)
}
}
if len(a.processed) > ProcessedIDsMaxSize {
// 删最旧一半。
type kv struct {
id string
t time.Time
}
all := make([]kv, 0, len(a.processed))
for id, t := range a.processed {
all = append(all, kv{id, t})
}
// 简单选择:按时间升序,删前一半。
for i := 0; i < len(all); i++ {
for j := i + 1; j < len(all); j++ {
if all[j].t.Before(all[i].t) {
all[i], all[j] = all[j], all[i]
}
}
}
remove := len(all) / 2
for i := 0; i < remove; i++ {
delete(a.processed, all[i].id)
}
}
}
// scheduleDebouncedReply 为 chat_id 调度防抖回复:
// 同一 chat_id 连续来消息时取消旧定时器、用最新消息重新计时,1s 后投递最后一条。
func (a *Account) scheduleDebouncedReply(chat ChatMessage) {
a.debounceMu.Lock()
defer a.debounceMu.Unlock()
deadline := time.Now()
// 取消旧定时器。
if old, ok := a.debounceTimers[chat.ChatID]; ok && old.timer != nil {
old.timer.Stop()
}
entry := &debounceEntry{lastMsg: chat, deadline: deadline}
a.debounceTimers[chat.ChatID] = entry
entry.timer = time.AfterFunc(MessageDebounceDelay, func() {
a.debounceMu.Lock()
cur, ok := a.debounceTimers[chat.ChatID]
if !ok || cur.deadline != deadline {
// 期间有新消息,跳过旧消息处理。
a.debounceMu.Unlock()
return
}
delete(a.debounceTimers, chat.ChatID)
lastMsg := cur.lastMsg
a.debounceMu.Unlock()
if a.delivery != nil {
if err := a.delivery.Handle(context.Background(), lastMsg); err != nil {
a.logger.Error("处理自动发货失败", "err", err, "chat_id", chat.ChatID)
}
if IsAutoDeliveryTrigger(lastMsg.Text) {
return
}
}
if a.reply != nil {
if err := a.reply.Handle(context.Background(), lastMsg); err != nil {
a.logger.Error("处理自动回复失败", "err", err, "chat_id", chat.ChatID)
}
}
if a.handler != nil {
if err := a.handler.HandleChatMessage(context.Background(), lastMsg); err != nil {
a.logger.Error("处理聊天消息失败", "err", err, "chat_id", chat.ChatID)
}
}
})
}
// extractMessageID 从 message["1"]["10"]["bizTag"] 或 extJson 中提取 messageId。
// 移植自 _extract_message_id。
func extractMessageID(decrypted map[string]any) string {
m1, ok := decrypted["1"].(map[string]any)
if !ok {
return ""
}
m10, ok := m1["10"].(map[string]any)
if !ok {
return ""
}
// bizTag 是 JSON 字符串:{"sourceId":"...","messageId":"..."}
if biz, _ := m10["bizTag"].(string); biz != "" {
if id := parseMessageIDFromJSON(biz); id != "" {
return id
}
}
if ext, _ := m10["extJson"].(string); ext != "" {
if id := parseMessageIDFromJSON(ext); id != "" {
return id
}
}
return ""
}
func parseMessageIDFromJSON(s string) string {
var m map[string]any
if err := json.Unmarshal([]byte(s), &m); err != nil {
return ""
}
if id, ok := m["messageId"].(string); ok {
return id
}
return ""
}
// extractChatMessage 从解密消息中提取聊天消息字段。
func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *ChatMessage {
m1, ok := decrypted["1"].(map[string]any)
if !ok {
return nil
}
m10, _ := m1["10"].(map[string]any)
if m10 == nil {
return nil
}
reminder, _ := m10["reminderContent"].(string)
if reminder == "" {
return nil
}
if isNonUserChatNotice(m1, m10, reminder) {
return nil
}
chatID := toString(m1["2"])
// chat_id 形如 "47983389096@goofish",去掉后缀。
if i := strings.Index(chatID, "@"); i >= 0 {
chatID = chatID[:i]
}
senderUserID, _ := m10["senderUserId"].(string)
senderName, _ := m10["senderNick"].(string)
reminderURL, _ := m10["reminderUrl"].(string)
itemID := extractItemID(reminderURL)
return &ChatMessage{
AccountID: accountID,
CookieStr: cookieStr,
ChatID: chatID,
SenderUserID: senderUserID,
SenderName: senderName,
Text: reminder,
ItemID: itemID,
Raw: decrypted,
}
}
// isNonUserChatNotice 判断闲鱼 IM 中不应进入自动回复/自动发货的系统提示或交易卡片。
// 典型样本:
// - contentType=14:“有蚂蚁森林能量可领”“不想宝贝被砍价?设置不砍价回复”“退款成功”
// - contentType=26:交易卡片,如“我已拍下,待付款”“我发起了退款申请”
// 例外:付款待发货卡片要进入自动发货,因此保留。
func isNonUserChatNotice(m1, m10 map[string]any, reminder string) bool {
contentType := messageContentType(m1, m10)
switch contentType {
case "14":
return true
case "26":
return !IsAutoDeliveryTrigger(reminder)
}
return false
}
func messageContentType(m1, m10 map[string]any) string {
if ext, _ := m10["extJson"].(string); ext != "" {
var extJSON map[string]any
if json.Unmarshal([]byte(ext), &extJSON) == nil {
if v := toString(extJSON["contentType"]); v != "" {
return v
}
}
}
m6, _ := m1["6"].(map[string]any)
if m6 == nil {
return ""
}
m63, _ := m6["3"].(map[string]any)
if m63 == nil {
return ""
}
if v := toString(m63["4"]); v != "" {
return v
}
if contentJSON, _ := m63["5"].(string); contentJSON != "" {
var content map[string]any
if json.Unmarshal([]byte(contentJSON), &content) == nil {
return toString(content["contentType"])
}
}
return ""
}
// extractSystemMessage 提取订单状态等系统消息(message["3"])。
func extractSystemMessage(decrypted map[string]any, accountID, cookieStr string) *SystemMessage {
m3, ok := decrypted["3"].(map[string]any)
if !ok {
return nil
}
red, _ := m3["redReminder"].(string)
uid, _ := m3["userId"].(string)
if red == "" && uid == "" {
return nil
}
return &SystemMessage{
AccountID: accountID,
CookieStr: cookieStr,
RedReminder: red,
UserID: uid,
Raw: decrypted,
}
}
// extractItemID 从 reminderUrl 中正则提取 itemId=xxx。
func extractItemID(url string) string {
const key = "itemId="
i := strings.Index(url, key)
if i < 0 {
return ""
}
s := url[i+len(key):]
if j := strings.IndexAny(s, "&\n\r"); j >= 0 {
s = s[:j]
}
return s
}
func (a *Account) currentCookieStr() string {
a.mu.Lock()
defer a.mu.Unlock()
return a.CookieStr
}
// ---- 小工具 ----
func contains(s, sub string) bool { return strings.Contains(strings.ToLower(s), strings.ToLower(sub)) }
func toString(v any) string {
switch x := v.(type) {
case string:
return x
case float64:
// JSON 数字 → 整数字符串。
return trimFloatInt(x)
default:
b, _ := json.Marshal(v)
return string(b)
}
}
func trimFloatInt(f float64) string {
if f == float64(int64(f)) {
return int64ToString(int64(f))
}
return ftoa(f)
}
func int64ToString(n int64) string {
if n == 0 {
return "0"
}
neg := n < 0
if neg {
n = -n
}
var b [20]byte
i := len(b)
for n > 0 {
i--
b[i] = byte('0' + n%10)
n /= 10
}
if neg {
i--
b[i] = '-'
}
return string(b[i:])
}
func ftoa(f float64) string { return jsonNumber(f) }
func jsonNumber(f float64) string {
b, _ := json.Marshal(f)
return string(b)
}
func truncID(id string) string {
if len(id) > 50 {
return id[:50] + "..."
}
return id
}
func errString(err error) string {
if err == nil {
return ""
}
return err.Error()
}
func sleepCtx(ctx context.Context, d time.Duration) error {
if d <= 0 {
return nil
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
+343
View File
@@ -0,0 +1,343 @@
package engine
import (
"context"
"encoding/json"
"fmt"
"path/filepath"
"sync"
"testing"
"time"
"xianyu-go/internal/db"
)
// recordingHandler 记录收到的聊天/系统消息,用于断言防抖与去重行为。
type recordingHandler struct {
mu sync.Mutex
chats []ChatMessage
systems []SystemMessage
refresh int
}
func (h *recordingHandler) HandleChatMessage(_ context.Context, m ChatMessage) error {
h.mu.Lock()
defer h.mu.Unlock()
h.chats = append(h.chats, m)
return nil
}
func (h *recordingHandler) HandleSystemMessage(_ context.Context, m SystemMessage) error {
h.mu.Lock()
defer h.mu.Unlock()
h.systems = append(h.systems, m)
return nil
}
func (h *recordingHandler) OnPasswordLoginRefresh(_ context.Context, _ string) bool {
h.mu.Lock()
defer h.mu.Unlock()
h.refresh++
return true
}
func newAccountForTest(t *testing.T) (*Account, *recordingHandler, *db.Store, func()) {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "test.db")
d, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
store := db.NewStore(d)
store.Users.Create(context.Background(), "admin", "[email protected]", "pw")
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
store.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
store.Cookies.SetStatus(context.Background(), "cid", true)
h := &recordingHandler{}
acc := New(Config{
CookieID: "cid",
CookieStr: "unb=123; _m_h5_tk=tk_1;",
Store: store,
Handler: h,
})
return acc, h, store, func() { d.Close() }
}
// TestExtractChatMessage_RealSample 用真实抓包样本验证消息字段提取。
func TestExtractChatMessage_RealSample(t *testing.T) {
decrypted := mustDecryptGoldenSample(t)
chat := extractChatMessage(decrypted, "cid", "cookie")
if chat == nil {
t.Fatal("应为聊天消息")
}
if chat.ChatID != "47983389009" {
t.Errorf("ChatID=%q want 47983389009", chat.ChatID)
}
if chat.Text != "[我已拍下,待付款]" {
t.Errorf("Text=%q want [我已拍下,待付款]", chat.Text)
}
if chat.ItemID != "900052644277" {
t.Errorf("ItemID=%q want 900052644277", chat.ItemID)
}
}
func TestExtractChatMessage_FiltersContentType14Notice(t *testing.T) {
decrypted := mustContentType14Notice(t)
if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
t.Fatalf("contentType=14 系统提示不应进入聊天回复: %+v", chat)
}
}
func TestExtractChatMessage_FiltersRefundTradeCard(t *testing.T) {
decrypted := mustRefundTradeCard(t)
if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
t.Fatalf("退款交易卡片不应进入聊天回复: %+v", chat)
}
}
func TestExtractChatMessage_KeepsPaidDeliveryCard(t *testing.T) {
decrypted := mustPaidDeliveryCard(t)
chat := extractChatMessage(decrypted, "cid", "cookie")
if chat == nil {
t.Fatal("付款待发货卡片应保留用于自动发货")
}
if chat.Text != "[我已付款,等待你发货]" {
t.Fatalf("Text=%q", chat.Text)
}
if chat.ItemID != "1063177864132" {
t.Fatalf("ItemID=%q", chat.ItemID)
}
}
func TestIsAutoDeliveryTriggerPaidCard(t *testing.T) {
if !IsAutoDeliveryTrigger("[我已付款,等待你发货]") {
t.Fatal("付款待发货卡片应触发自动发货")
}
if IsAutoDeliveryTrigger("[我已拍下,待付款]") {
t.Fatal("仅拍下未付款不应触发自动发货")
}
}
// TestDedup_SkipsDuplicateWithinExpiry 同一消息 ID 1 小时内只处理一次。
func TestDedup_SkipsDuplicateWithinExpiry(t *testing.T) {
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
decrypted := mustDecryptGoldenSample(t)
chat := extractChatMessage(decrypted, "cid", "cookie")
// 首次:标记并应继续。
if !acc.markAndCheckDedup(decrypted, chat) {
t.Fatal("首次应允许处理")
}
// 第二次同一消息 ID:应跳过。
if acc.markAndCheckDedup(decrypted, chat) {
t.Fatal("重复消息应被去重跳过")
}
h.mu.Lock()
defer h.mu.Unlock()
if len(h.chats) != 0 {
t.Errorf("去重阶段不应投递消息,got %d", len(h.chats))
}
}
// TestDebounce_CoalescesRapidMessages 连续消息只投递最后一条。
func TestDebounce_CoalescesRapidMessages(t *testing.T) {
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
decrypted := mustDecryptGoldenSample(t)
chat := extractChatMessage(decrypted, "cid", "cookie")
// 修改文本模拟连续多条。
chat1 := *chat
chat1.Text = "第一条"
chat2 := *chat
chat2.Text = "第二条"
chat3 := *chat
chat3.Text = "第三条"
// 用不同 decrypted(不同 msgID)触发防抖,验证同一 chat_id 合并。
acc.scheduleDebouncedReply(chat1)
acc.scheduleDebouncedReply(chat2)
acc.scheduleDebouncedReply(chat3)
// 等待防抖延迟 + 余量。
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
h.mu.Lock()
defer h.mu.Unlock()
if len(h.chats) != 1 {
t.Fatalf("防抖应只投递最后一条,got %d", len(h.chats))
}
if h.chats[0].Text != "第三条" {
t.Errorf("应投递最后一条,got %q", h.chats[0].Text)
}
}
// TestExtractItemID reminderUrl 中提取 itemId。
func TestExtractItemID(t *testing.T) {
cases := map[string]string{
"fleamarket://message_chat?itemId=900052644277&peerUserId=3149637063": "900052644277",
"noitemid": "",
"fleamarket://x?itemId=ABC123": "ABC123",
}
for in, want := range cases {
if got := extractItemID(in); got != want {
t.Errorf("extractItemID(%q)=%q want %q", in, got, want)
}
}
}
// mustDecryptGoldenSample 复用 protocol 包的真实样本:直接硬编码一条最小解密结构,
// 避免循环依赖。这里构造一个等价的最小消息用于字段提取测试。
func mustDecryptGoldenSample(t *testing.T) map[string]any {
t.Helper()
// 真实样本关键字段(来自 protocol golden test 解密输出):
// message["1"]["2"]="47983389009@goofish", ["1"]["10"]["reminderContent"]="[我已拍下,待付款]",
// ["1"]["10"]["reminderUrl"] 含 itemId=900052644277
s := `{
"1": {
"2": "47983389009@goofish",
"10": {
"reminderContent": "[我已拍下,待付款]",
"senderNick": "买家昵称",
"senderUserId": "3149637063",
"reminderUrl": "fleamarket://message_chat?itemId=900052644277&peerUserId=3149637063"
}
},
"3": {
"redReminder": "等待买家付款",
"userId": "3149637063"
}
}`
var m map[string]any
if err := json.Unmarshal([]byte(s), &m); err != nil {
t.Fatalf("unmarshal: %v", err)
}
return m
}
func mustContentType14Notice(t *testing.T) map[string]any {
t.Helper()
s := "{" +
"\"1\":{" +
"\"2\":\"63107041124@goofish\"," +
"\"10\":{" +
"\"extJson\":\"{\\\"contentType\\\":\\\"14\\\",\\\"messageId\\\":\\\"d050b73332b94d5a8901cff78519483a\\\"}\"," +
"\"reminderContent\":\"[不想宝贝被砍价?设置不砍价回复 ]\"," +
"\"senderUserId\":\"2222315258815\"," +
"\"reminderUrl\":\"fleamarket://message_chat?itemId=1063177864132&peerUserId=2222315258815\"" +
"}," +
"\"6\":{\"3\":{\"4\":14,\"5\":\"{\\\"contentType\\\":14,\\\"tip\\\":{\\\"argInfo\\\":{\\\"arg1\\\":\\\"NoBargainGuide\\\"}}}\"}}" +
"}" +
"}"
var m map[string]any
if err := json.Unmarshal([]byte(s), &m); err != nil {
t.Fatalf("unmarshal: %v", err)
}
return m
}
func mustRefundTradeCard(t *testing.T) map[string]any {
t.Helper()
s := "{" +
"\"1\":{" +
"\"2\":\"63107041124@goofish\"," +
"\"10\":{" +
"\"bizTag\":\"{\\\"sourceId\\\":\\\"C2C:eeg858GGuju9\\\",\\\"taskName\\\":\\\"发起退款申请_卖家-新逆向url\\\"}\"," +
"\"extJson\":\"{\\\"msgArg1\\\":\\\"MsgCard\\\",\\\"contentType\\\":\\\"26\\\",\\\"messageId\\\":\\\"3a03978b7a374da898b3d7a084cbedb6\\\"}\"," +
"\"redReminder\":\"买家申请退款\"," +
"\"reminderContent\":\"[我发起了退款申请]\"," +
"\"senderUserId\":\"2222315258815\"," +
"\"reminderUrl\":\"fleamarket://message_chat?itemId=1063177864132&peerUserId=2222315258815\"" +
"}," +
"\"6\":{\"3\":{\"4\":26,\"5\":\"{\\\"contentType\\\":26}\"}}" +
"}" +
"}"
var m map[string]any
if err := json.Unmarshal([]byte(s), &m); err != nil {
t.Fatalf("unmarshal: %v", err)
}
return m
}
func mustPaidDeliveryCard(t *testing.T) map[string]any {
t.Helper()
s := "{" +
"\"1\":{" +
"\"2\":\"63107041124@goofish\"," +
"\"10\":{" +
"\"bizTag\":\"{\\\"sourceId\\\":\\\"C2C:4Ytd4BSQKIiz\\\",\\\"taskName\\\":\\\"付款完成待发货_卖家-正向升级\\\"}\"," +
"\"extJson\":\"{\\\"msgArg1\\\":\\\"MsgCard\\\",\\\"contentType\\\":\\\"26\\\",\\\"messageId\\\":\\\"4e449a32c59c499594c4c5dffa5ddef0\\\"}\"," +
"\"redReminder\":\"等待卖家发货\"," +
"\"reminderContent\":\"[我已付款,等待你发货]\"," +
"\"senderUserId\":\"2222315258815\"," +
"\"reminderUrl\":\"fleamarket://message_chat?itemId=1063177864132&peerUserId=2222315258815\"" +
"}," +
"\"6\":{\"3\":{\"4\":26,\"5\":\"{\\\"contentType\\\":26}\"}}" +
"}" +
"}"
var m map[string]any
if err := json.Unmarshal([]byte(s), &m); err != nil {
t.Fatalf("unmarshal: %v", err)
}
return m
}
// TestExtractSystemMessage 系统消息提取。
func TestExtractSystemMessage(t *testing.T) {
m := mustDecryptGoldenSample(t)
sys := extractSystemMessage(m, "cid", "cookie")
if sys == nil {
t.Fatal("应为系统消息")
}
if sys.RedReminder != "等待买家付款" {
t.Errorf("RedReminder=%q", sys.RedReminder)
}
}
// TestRetryDelay 复刻 _calculate_retry_delay 的分段逻辑。
func TestRetryDelay(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
acc.connFailures = 1
if d := acc.retryDelay("no close frame received or sent"); d != 3*time.Second {
t.Errorf("close-frame failures=1: %v want 3s", d)
}
acc.connFailures = 10
if d := acc.retryDelay("no close frame received or sent"); d != 15*time.Second {
t.Errorf("close-frame failures=10: %v want 15s (capped)", d)
}
acc.connFailures = 2
if d := acc.retryDelay("connection refused"); d != 20*time.Second {
t.Errorf("refused failures=2: %v want 20s", d)
}
acc.connFailures = 10
if d := acc.retryDelay("connection refused"); d != 60*time.Second {
t.Errorf("refused failures=10: %v want 60s (capped)", d)
}
acc.connFailures = 1
if d := acc.retryDelay("some other error"); d != 5*time.Second {
t.Errorf("other failures=1: %v want 5s", d)
}
}
func TestRuntimeStatusClassifiesAuthenticationFailures(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
acc.setRuntimeError(fmt.Errorf("token API 登录凭证已失效: FAIL_SYS_TOKEN_EXOIRED"))
status := acc.RuntimeStatus()
if status.State != RuntimeAuthExpired || status.Connected {
t.Fatalf("status=%+v", status)
}
acc.setRuntimeError(fmt.Errorf("FAIL_SYS_USER_VALIDATE: captcha required"))
status = acc.RuntimeStatus()
if status.State != RuntimeVerificationRequired {
t.Fatalf("status=%+v", status)
}
}
+223
View File
@@ -0,0 +1,223 @@
// reply.go 四级回复引擎:API → 关键词 → AI → 默认回复。
// 移植自 Python _process_chat_message_reply + get_keyword_reply/get_default_reply/get_ai_reply。
//
// Phase 3 实现:关键词(含商品ID优先+变量替换+空回复标记)、默认回复(指定商品优先+reply_once+变量替换)。
// API 回复(调外部 /xianyu/reply 接口)和 AI 回复(OpenAI 兼容)留接口注入。
package engine
import (
"context"
"fmt"
"log/slog"
"strings"
"xianyu-go/internal/db"
)
// ReplyResult 回复结果。
type ReplyResult struct {
Text string // 文本回复(可空)
ImageURL string // 图片回复(可空)
Source string // 回复来源:API/关键词/AI/默认
Skip bool // true 表示匹配到空回复,不发送任何内容
}
// APIReplier 外部 API 回复(优先级1)。返回 nil 表示无回复。
type APIReplier interface {
Reply(ctx context.Context, m ChatMessage) (*ReplyResult, error)
}
// AIReplier AI 回复(优先级3)。返回 nil 表示无回复。
type AIReplier interface {
Reply(ctx context.Context, m ChatMessage) (*ReplyResult, error)
}
// ReplyService 单账号回复服务。
type ReplyService struct {
cookieID string
store *db.Store
api APIReplier // 可为 nil
ai AIReplier // 可为 nil
sender DeliverySender
logger *slog.Logger
}
// NewReplyService 构造。
func NewReplyService(cookieID string, store *db.Store, sender DeliverySender,
api APIReplier, ai AIReplier, logger *slog.Logger) *ReplyService {
if logger == nil {
logger = slog.Default()
}
return &ReplyService{
cookieID: cookieID,
store: store,
api: api,
ai: ai,
sender: sender,
logger: logger.With("account", cookieID, "subsys", "reply"),
}
}
// Handle 收到一条聊天消息,按四级优先级回复。
// 由 Account 在防抖后调用。返回是否产生了回复。
func (r *ReplyService) Handle(ctx context.Context, m ChatMessage) error {
res := r.resolve(ctx, m)
if res == nil || res.Skip {
return nil
}
// 发送:图片优先,文本随后。
if r.sender == nil {
return nil
}
if res.ImageURL != "" {
if err := r.sender.SendImage(ctx, m.ChatID, m.SenderUserID, res.ImageURL, 0); err != nil {
r.logger.Error("发送回复图片失败", "err", err)
}
}
if res.Text != "" {
if err := r.sender.SendText(ctx, m.ChatID, m.SenderUserID, res.Text); err != nil {
r.logger.Error("发送回复文本失败", "err", err)
}
}
return nil
}
// resolve 按优先级确定回复内容(不发送)。
func (r *ReplyService) resolve(ctx context.Context, m ChatMessage) *ReplyResult {
// 优先级1:API 回复。
if r.api != nil {
if res, err := r.api.Reply(ctx, m); err != nil {
r.logger.Error("API 回复失败", "err", err)
} else if res != nil {
res.Source = "API"
return res
}
}
// 优先级2:关键词匹配。
if res := r.keywordReply(ctx, m); res != nil {
return res
}
// 优先级3:AI 回复。
if r.ai != nil {
if res, err := r.ai.Reply(ctx, m); err != nil {
r.logger.Error("AI 回复失败", "err", err)
} else if res != nil {
res.Source = "AI"
return res
}
}
// 优先级4:默认回复。
return r.defaultReply(ctx, m)
}
// keywordReply 关键词匹配。返回 nil 表示无匹配;
// 返回 Skip=true 表示匹配到空回复(不发送)。
// 移植自 get_keyword_reply:商品ID关键词优先 → 通用关键词。
func (r *ReplyService) keywordReply(ctx context.Context, m ChatMessage) *ReplyResult {
kws, err := r.store.Keywords.AllWithType(ctx, r.cookieID)
if err != nil || len(kws) == 0 {
return nil
}
msgLower := strings.ToLower(m.Text)
// 1. 商品ID关键词优先。
if m.ItemID != "" {
for _, kw := range kws {
if kw.ItemID == m.ItemID && strings.Contains(msgLower, strings.ToLower(kw.Keyword)) {
return r.keywordResult(kw, m)
}
}
}
// 2. 通用关键词(无 item_id)。
for _, kw := range kws {
if kw.ItemID == "" && strings.Contains(msgLower, strings.ToLower(kw.Keyword)) {
return r.keywordResult(kw, m)
}
}
return nil
}
func (r *ReplyService) keywordResult(kw db.Keyword, m ChatMessage) *ReplyResult {
if kw.Type == "image" && kw.ImageURL != "" {
return &ReplyResult{ImageURL: kw.ImageURL, Source: "关键词"}
}
if strings.TrimSpace(kw.Reply) == "" {
return &ReplyResult{Skip: true, Source: "关键词"} // EMPTY_REPLY
}
return &ReplyResult{Text: formatReply(kw.Reply, m), Source: "关键词"}
}
// defaultReply 默认回复。移植自 get_default_reply:
// 指定商品回复优先 → 账号默认回复(reply_once 防重复 + 变量替换)。
func (r *ReplyService) defaultReply(ctx context.Context, m ChatMessage) *ReplyResult {
// 1. 指定商品回复。
if m.ItemID != "" {
if ir, err := r.store.ItemReps.Get(ctx, r.cookieID, m.ItemID); err == nil && ir != nil && strings.TrimSpace(ir.ReplyContent) != "" {
return &ReplyResult{Text: formatReplyWithItem(ir.ReplyContent, m), Source: "默认"}
}
}
// 2. 账号默认回复。
dr, err := r.store.DefaultReps.Get(ctx, r.cookieID)
if err != nil || dr == nil || !dr.Enabled {
return nil
}
// reply_once:已回复过则跳过。
if dr.ReplyOnce && m.ChatID != "" {
if r.store.DefaultReps.HasRecord(ctx, r.cookieID, m.ChatID) {
r.logger.Info("chat_id 已用过默认回复,跳过(reply_once)", "chat_id", m.ChatID)
return nil
}
}
// 文字和图片都为空 → 空回复标记。
if strings.TrimSpace(dr.ReplyContent) == "" && strings.TrimSpace(dr.ReplyImageURL) == "" {
return &ReplyResult{Skip: true, Source: "默认"}
}
// 记录已回复。
if dr.ReplyOnce && m.ChatID != "" {
_ = r.store.DefaultReps.AddRecord(ctx, r.cookieID, m.ChatID)
}
res := &ReplyResult{Source: "默认"}
if strings.TrimSpace(dr.ReplyContent) != "" {
res.Text = formatReply(dr.ReplyContent, m)
}
if strings.TrimSpace(dr.ReplyImageURL) != "" {
res.ImageURL = dr.ReplyImageURL
}
return res
}
// formatReply 变量替换:{send_user_name} {send_user_id} {send_message}。
// 复刻 Python reply.format(...);若替换出错返回原文。
func formatReply(template string, m ChatMessage) string {
return safeFormat(template, map[string]string{
"send_user_name": m.SenderName,
"send_user_id": m.SenderUserID,
"send_message": m.Text,
})
}
// formatReplyWithItem 含 {item_id} 变量。
func formatReplyWithItem(template string, m ChatMessage) string {
return safeFormat(template, map[string]string{
"send_user_name": m.SenderName,
"send_user_id": m.SenderUserID,
"send_message": m.Text,
"item_id": m.ItemID,
})
}
// safeFormat 实现 Python str.format 的命名占位符子集。
// Python 用 {send_user_name},Go 标准库不支持,手动替换。
func safeFormat(template string, vars map[string]string) string {
out := template
for k, v := range vars {
out = strings.ReplaceAll(out, "{"+k+"}", v)
}
return out
}
// 占位防未用 fmt(未来错误信息用)。
var _ = fmt.Sprintf
+169
View File
@@ -0,0 +1,169 @@
package engine
import (
"context"
"path/filepath"
"testing"
"xianyu-go/internal/db"
)
func newReplyStore(t *testing.T) (*db.Store, func()) {
t.Helper()
d, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
s := db.NewStore(d)
s.Users.Create(context.Background(), "admin", "[email protected]", "pw")
admin, _ := s.Users.GetByUsername(context.Background(), "admin")
s.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
return s, func() { d.Close() }
}
func chatMsg(text, itemID, chatID string) ChatMessage {
return ChatMessage{
AccountID: "cid", CookieStr: "",
ChatID: chatID, SenderUserID: "buyer1", SenderName: "买家",
Text: text, ItemID: itemID,
}
}
// TestKeywordReply_MatchAndVariableSubst 关键词匹配 + 变量替换。
func TestKeywordReply_MatchAndVariableSubst(t *testing.T) {
s, cleanup := newReplyStore(t)
defer cleanup()
ctx := context.Background()
// 关键词 "在吗" → "你好{send_user_name},在的,请问要{send_message}吗"
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,type) VALUES ('cid','在吗','你好{send_user_name},在的','text')`)
r := NewReplyService("cid", s, nil, nil, nil, nil)
res := r.resolve(ctx, chatMsg("老板在吗", "item1", "chat1"))
if res == nil || res.Source != "关键词" {
t.Fatalf("应命中关键词,got %+v", res)
}
if res.Text != "你好买家,在的" {
t.Errorf("变量替换: got %q want 你好买家,在的", res.Text)
}
}
// TestKeywordReply_ItemIDPriority 商品ID关键词优先于通用关键词。
func TestKeywordReply_ItemIDPriority(t *testing.T) {
s, cleanup := newReplyStore(t)
defer cleanup()
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,item_id,type) VALUES
('cid','价格','通用价格回复','','text'),
('cid','价格','该商品专属价格回复','item1','text')`)
r := NewReplyService("cid", s, nil, nil, nil, nil)
res := r.resolve(ctx, chatMsg("价格多少", "item1", "chat1"))
if res == nil || res.Text != "该商品专属价格回复" {
t.Errorf("应优先商品ID关键词,got %+v", res)
}
// 无 item_id 时走通用。
res2 := r.resolve(ctx, chatMsg("价格多少", "", "chat1"))
if res2 == nil || res2.Text != "通用价格回复" {
t.Errorf("无itemID应走通用,got %+v", res2)
}
}
// TestKeywordReply_EmptyReplySkip 匹配到空回复 → Skip。
func TestKeywordReply_EmptyReplySkip(t *testing.T) {
s, cleanup := newReplyStore(t)
defer cleanup()
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,type) VALUES ('cid','静默','','text')`)
r := NewReplyService("cid", s, nil, nil, nil, nil)
res := r.resolve(ctx, chatMsg("静默一下", "item1", "chat1"))
if res == nil || !res.Skip {
t.Fatalf("空回复应 Skip=true,got %+v", res)
}
}
// TestDefaultReply_ItemReplyFirst 指定商品回复优先于账号默认回复。
func TestDefaultReply_ItemReplyFirst(t *testing.T) {
s, cleanup := newReplyStore(t)
defer cleanup()
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'账号默认回复',0)`)
s.DB.ExecContext(ctx, `INSERT INTO item_replay (item_id,cookie_id,reply_content) VALUES ('item1','cid','该商品专属默认回复')`)
r := NewReplyService("cid", s, nil, nil, nil, nil)
res := r.resolve(ctx, chatMsg("任意消息", "item1", "chat1"))
if res == nil || res.Text != "该商品专属默认回复" {
t.Errorf("应优先指定商品回复,got %+v", res)
}
}
// TestDefaultReply_ReplyOnce reply_once 防重复。
func TestDefaultReply_ReplyOnce(t *testing.T) {
s, cleanup := newReplyStore(t)
defer cleanup()
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'默认问候',1)`)
r := NewReplyService("cid", s, nil, nil, nil, nil)
// 首次:应回复。
res1 := r.resolve(ctx, chatMsg("在吗", "item1", "chatX"))
if res1 == nil || res1.Text != "默认问候" {
t.Fatalf("首次应回复,got %+v", res1)
}
// 第二次同 chat_id:reply_once 应跳过。
res2 := r.resolve(ctx, chatMsg("还在吗", "item1", "chatX"))
if res2 != nil {
t.Fatalf("reply_once 应跳过第二次,got %+v", res2)
}
// 不同 chat_id:应回复。
res3 := r.resolve(ctx, chatMsg("在吗", "item1", "chatY"))
if res3 == nil || res3.Text != "默认问候" {
t.Fatalf("不同 chat_id 应回复,got %+v", res3)
}
}
// TestPriority_Order 四级优先级:关键词 > 默认(无API/AI时)。
func TestPriority_Order(t *testing.T) {
s, cleanup := newReplyStore(t)
defer cleanup()
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,type) VALUES ('cid','在吗','关键词回复','text')`)
s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'默认回复',0)`)
r := NewReplyService("cid", s, nil, nil, nil, nil)
// 命中关键词 → 关键词回复。
res := r.resolve(ctx, chatMsg("在吗", "", "chat1"))
if res == nil || res.Source != "关键词" {
t.Errorf("应优先关键词,got %+v", res)
}
// 不命中关键词 → 默认回复。
res2 := r.resolve(ctx, chatMsg("别的消息", "", "chat1"))
if res2 == nil || res2.Source != "默认" {
t.Errorf("无关键词应走默认,got %+v", res2)
}
}
// TestFormatReply 变量替换。
func TestFormatReply(t *testing.T) {
m := chatMsg("想买", "item1", "chat1")
m.SenderName = "张三"
got := formatReply("你好{send_user_name},你说{send_message}", m)
if got != "你好张三,你说想买" {
t.Errorf("formatReply=%q", got)
}
}
// TestParsePrice 价格解析。
func TestParsePrice(t *testing.T) {
cases := map[string]float64{
"¥99.5": 99.5,
"100元": 100,
"": 0,
"abc": 0,
"12.34": 12.34,
}
for in, want := range cases {
if got := parsePrice(in); got != want {
t.Errorf("parsePrice(%q)=%v want %v", in, got, want)
}
}
}