diff --git a/cmd/server/main.go b/cmd/server/main.go index 836996a..f7aff72 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -1,4 +1,4 @@ -// cmd/server 是闲鱼管家 Go 主进程入口。 +// Package main 是闲鱼管家 Go 主进程入口。 // 启动:DB 迁移 → 加载账号引擎 → HTTP API 服务。 // // 用法: @@ -8,8 +8,8 @@ // // 首次使用可直接用本二进制初始化管理员,不再需要单独 init-admin。 // -// 浏览器自动化(扫码风控验证、滑块、密码登录、搜索、订单抓取)内置 playwright-go, -// 首次使用时自动下载 Chromium,无需手动启动 sidecar。加 -no-browser 可禁用。 +// 浏览器自动化(扫码风控验证、密码登录、订单抓取)内置 playwright-go, +// 首次使用时自动下载 Chromium。加 -no-browser 可禁用。 package main import ( @@ -25,9 +25,11 @@ import ( "time" "xianyu-go/internal/account" + "xianyu-go/internal/automation" "xianyu-go/internal/browser" "xianyu-go/internal/db" "xianyu-go/internal/engine" + "xianyu-go/internal/notify" "xianyu-go/internal/server" ) @@ -36,7 +38,7 @@ func main() { addr := flag.String("addr", ":8080", "HTTP 监听地址") webDir := flag.String("web", "", "前端静态资源目录(含 index.html)") secure := flag.Bool("secure", false, "HTTPS 模式(Cookie 加 Secure)") - noBrowser := flag.Bool("no-browser", false, "禁用内置浏览器自动化(扫码风控验证/滑块/搜索/订单抓取将不可用)") + noBrowser := flag.Bool("no-browser", false, "禁用内置浏览器自动化(扫码风控验证/密码登录/订单抓取将不可用)") verbose := flag.Bool("v", false, "调试日志") initAdmin := flag.Bool("init-admin", false, "初始化或重置 admin 管理员后退出") adminEmail := flag.String("admin-email", "admin@example.com", "初始化 admin 的邮箱") @@ -80,25 +82,46 @@ func main() { if !*noBrowser { bm = browser.NewManager(logger) } - mgr := account.NewManager(store, &handlerAdapter{store: store, browser: bm, logger: logger}, logger) + var mgr *account.Manager + adapter := &handlerAdapter{store: store, browser: bm, logger: logger} + mgr = account.NewManager(store, adapter, logger) + autoCenter := automation.New(store, mgr, logger) + autoCenter.SetOrderDetailFetcher(adapter) + notifier := notify.New("", store, logger) + autoCenter.SetNotifier(notifier) + adapter.automation = autoCenter if err := mgr.StartAll(ctx); err != nil { logger.Error("启动账号引擎失败", "err", err) } + go automation.NewScheduler(autoCenter).Run(ctx) // 3) HTTP 服务。 srv := server.New(store, mgr, bm, *secure, *webDir, *addr, logger) + srv.Automation = autoCenter + srv.Notifier = notifier if err := srv.Run(ctx); err != nil { logger.Error("HTTP 服务退出", "err", err) + // 即便出错也尝试清理已启动的账号与浏览器。 + mgr.StopAll() + if bm != nil { + _ = bm.Close() + } os.Exit(1) } + // HTTP 服务正常退出(ctx 取消触发 Shutdown):停账号引擎、关浏览器。 + mgr.StopAll() + if bm != nil { + _ = bm.Close() + } } -// handlerAdapter 实现 engine.Handler,把系统消息/密码登录刷新接到浏览器。 -// 聊天消息的发货/回复由 Account 内部 DeliveryService/ReplyService 处理。 +// handlerAdapter 实现 engine.Handler,把系统消息、订单详情抓取和密码登录刷新接到浏览器。 +// 自动发货只走 automation.Center;用户聊天消息由 Account 内部 ReplyService 处理。 type handlerAdapter struct { - store *db.Store - browser *browser.Manager - logger *slog.Logger + store *db.Store + browser *browser.Manager + logger *slog.Logger + automation *automation.Center mu sync.Mutex lastLoginByCID map[string]time.Time @@ -110,28 +133,31 @@ func (h *handlerAdapter) HandleChatMessage(ctx context.Context, m engine.ChatMes return nil } -func (h *handlerAdapter) HandleSystemMessage(ctx context.Context, m engine.SystemMessage) error { - h.logger.Info("系统消息", "account", m.AccountID, "reminder", m.RedReminder) - return nil +func (h *handlerAdapter) HandleSystemEvent(ctx context.Context, task automation.Task) error { + if h.automation == nil { + return nil + } + h.logger.Info("系统自动化事件", "account", task.AccountID, "trigger", task.TriggerType, "order_id", task.OrderID) + return h.automation.HandleTask(ctx, task) } -// Fetch 实现 engine.OrderDetailFetcher。只在本地订单缺少规格时启动浏览器, +// FetchOrderDetail 实现 automation.OrderDetailFetcher。只在本地订单缺少关键字段时启动浏览器, // 并将所有账号的详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。 -func (h *handlerAdapter) Fetch(ctx context.Context, cookieID, orderID, itemID, buyerID, cookieStr string) (*engine.OrderDetail, error) { +func (h *handlerAdapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, cookieStr string) (*automation.OrderDetail, error) { if order, err := h.store.Orders.Get(ctx, orderID); err == nil && order != nil && order.Amount != "" && order.Quantity != "" && - (!h.store.Items.IsMultiSpec(ctx, cookieID, itemID) || (order.SpecName != "" && order.SpecValue != "")) { - return &engine.OrderDetail{Quantity: order.Quantity, SpecName: order.SpecName, SpecValue: order.SpecValue, Amount: order.Amount, OrderStatus: order.OrderStatus}, nil + order.SpecName != "" && order.SpecValue != "" { + return &automation.OrderDetail{Quantity: order.Quantity, SpecName: order.SpecName, SpecValue: order.SpecValue, Amount: order.Amount, OrderStatus: order.OrderStatus}, nil } if h.browser == nil { - return nil, fmt.Errorf("订单缺少规格信息且浏览器自动化未启用") + return nil, fmt.Errorf("订单缺少规格/数量信息且浏览器自动化未启用") } h.orderFetchMu.Lock() defer h.orderFetchMu.Unlock() // 等锁期间其他流程可能已经补齐订单,再检查一次。 if order, err := h.store.Orders.Get(ctx, orderID); err == nil && order != nil && order.Amount != "" && order.Quantity != "" && - (!h.store.Items.IsMultiSpec(ctx, cookieID, itemID) || (order.SpecName != "" && order.SpecValue != "")) { - return &engine.OrderDetail{Quantity: order.Quantity, SpecName: order.SpecName, SpecValue: order.SpecValue, Amount: order.Amount, OrderStatus: order.OrderStatus}, nil + order.SpecName != "" && order.SpecValue != "" { + return &automation.OrderDetail{Quantity: order.Quantity, SpecName: order.SpecName, SpecValue: order.SpecValue, Amount: order.Amount, OrderStatus: order.OrderStatus}, nil } if remain := 3*time.Second - time.Since(h.lastOrderFetch); !h.lastOrderFetch.IsZero() && remain > 0 { timer := time.NewTimer(remain) @@ -143,14 +169,14 @@ func (h *handlerAdapter) Fetch(ctx context.Context, cookieID, orderID, itemID, b } } h.lastOrderFetch = time.Now() - detail, err := h.browser.FetchOrderDetail(ctx, orderID, cookieID, cookieStr, h.store.Items.IsMultiSpec(ctx, cookieID, itemID)) + detail, err := h.browser.FetchOrderDetail(ctx, orderID, cookieID, cookieStr, true) if err != nil { return nil, err } if detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr { _ = h.store.Cookies.Save(ctx, cookieID, detail.UpdatedCookies, 0) } - return &engine.OrderDetail{ + return &automation.OrderDetail{ Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue, Amount: detail.Amount, OrderStatus: detail.OrderStatus, }, nil diff --git a/internal/account/manager.go b/internal/account/manager.go index d816c76..20b7286 100644 --- a/internal/account/manager.go +++ b/internal/account/manager.go @@ -2,7 +2,7 @@ // 从 DB 加载启用的闲鱼账号,为每个账号起一个 engine.Account goroutine, // 支持动态启停、状态查询、跨层 GetInstance(供 HTTP 手动发货等操作调用)。 // -// 对应 Python cookie_manager.CookieManager + XianyuLive._instances。 +// Manager 管理所有启用账号的运行实例。 package account import ( @@ -12,6 +12,7 @@ import ( "sync" "time" + "xianyu-go/internal/automation" "xianyu-go/internal/db" "xianyu-go/internal/engine" ) @@ -137,19 +138,6 @@ func (m *Manager) Stop(cookieID string) { m.logger.Info("账号已停止", "account", cookieID) } -// StopAll 停止所有账号。 -func (m *Manager) StopAll() { - m.mu.Lock() - ids := make([]string, 0, len(m.accounts)) - for id := range m.accounts { - ids = append(ids, id) - } - m.mu.Unlock() - for _, id := range ids { - m.Stop(id) - } -} - // GetInstance 跨层获取账号运行时(供 HTTP 手动发货等操作)。 func (m *Manager) GetInstance(cookieID string) (*engine.Account, bool) { m.mu.Lock() @@ -161,20 +149,9 @@ func (m *Manager) GetInstance(cookieID string) (*engine.Account, bool) { return ma.acc, true } -// RunningAccounts 返回当前运行的账号 ID 列表(用于状态展示)。 -func (m *Manager) RunningAccounts() []string { - m.mu.Lock() - defer m.mu.Unlock() - ids := make([]string, 0, len(m.accounts)) - for id, ma := range m.accounts { - select { - case <-ma.done: - continue - default: - ids = append(ids, id) - } - } - return ids +// Sender 实现 automation.SenderProvider,供自动化中心复用当前在线账号的 WS 发送能力。 +func (m *Manager) Sender(cookieID string) (automation.MessageSender, bool) { + return m.GetInstance(cookieID) } // RuntimeStatuses 返回所有已启动账号的实时状态快照。 @@ -211,3 +188,17 @@ func (m *Manager) Restart(ctx context.Context, cookieID string) error { } return m.Start(ctx, cookieID, d.Value) } + +// StopAll 停止所有运行中的账号,用于进程优雅退出。 +// 先在锁内收集 cookieID 列表再解锁逐个停,避免持锁等待 goroutine 退出。 +func (m *Manager) StopAll() { + m.mu.Lock() + ids := make([]string, 0, len(m.accounts)) + for id := range m.accounts { + ids = append(ids, id) + } + m.mu.Unlock() + for _, id := range ids { + m.Stop(id) + } +} diff --git a/internal/server/order_handlers.go b/internal/server/order_handlers.go index fa10a39..8c6f963 100644 --- a/internal/server/order_handlers.go +++ b/internal/server/order_handlers.go @@ -454,21 +454,21 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) { continue } if req.ShipMode == "full_delivery" { - if s.Manager == nil { + if s.Manager == nil || s.Automation == nil { failedCount++ - results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "账号管理器未初始化"}) + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "自动化中心未初始化"}) continue } - acc, running := s.Manager.GetInstance(order.CookieID) - if !running { + if _, running := s.Manager.GetInstance(order.CookieID); !running { failedCount++ results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "该账号未在线运行,无法执行完整发货"}) continue } - sent, err := acc.ManualFullDelivery(r.Context(), order) + sent, err := s.Automation.ManualFullDelivery(r.Context(), order) if err != nil { failedCount++ results = append(results, map[string]any{"order_id": orderID, "success": false, "message": err.Error()}) + s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动完整发货失败: "+err.Error()) continue } successCount++ @@ -477,6 +477,8 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) { "success": true, "message": fmt.Sprintf("完整发货成功,已发送%d条卡券信息给买家", sent), }) + s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, + fmt.Sprintf("手动完整发货成功(订单 %s,已发送 %d 条)", orderID, sent)) continue } if s.MTop == nil { @@ -488,6 +490,7 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) { if err != nil { failedCount++ results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "确认发货异常: " + err.Error()}) + s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动确认发货异常: "+err.Error()) continue } if updatedCookies != "" && updatedCookies != cookieValue { @@ -505,6 +508,7 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) { msg += ": " + strings.Join(ret, "; ") } results = append(results, map[string]any{"order_id": orderID, "success": false, "message": msg}) + s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动确认发货失败: "+msg) continue } sysShip := true @@ -526,6 +530,8 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) { }) successCount++ results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "已成功修改闲鱼发货状态"}) + s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, + fmt.Sprintf("手动确认发货成功(订单 %s)", orderID)) } writeJSON(w, http.StatusOK, map[string]any{ "success": failedCount == 0, @@ -537,7 +543,7 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) { } func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) { - orders, err := parseImportedOrders(r) + orders, err := parseImportedOrders(w, r) if err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return @@ -644,6 +650,14 @@ func isStableOrderStatus(status string) bool { } } +// notifyDelivery 在 Notifier 已注入时发送发货结果通知,未注入则跳过。 +func (s *Server) notifyDelivery(cookieID, buyerID, itemID, chatID, message string) { + if s.Notifier == nil { + return + } + s.Notifier.NotifyDelivery(cookieID, "", buyerID, itemID, message, chatID) +} + func stringFromAny(v any) string { switch x := v.(type) { case nil: @@ -668,9 +682,12 @@ func stringFromAny(v any) string { } } -func parseImportedOrders(r *http.Request) ([]map[string]any, error) { +func parseImportedOrders(w http.ResponseWriter, r *http.Request) ([]map[string]any, error) { ct := r.Header.Get("Content-Type") if strings.HasPrefix(ct, "multipart/form-data") { + // 订单文件上限 32 MiB;MaxBytesReader 必须在 ParseMultipartForm 前应用。 + r.Body = http.MaxBytesReader(w, r.Body, 32<<20) + // #nosec G120 -- 请求体已由 MaxBytesReader 限制为 32 MiB。 if err := r.ParseMultipartForm(32 << 20); err != nil { return nil, fmt.Errorf("解析上传文件失败: %w", err) } @@ -679,16 +696,22 @@ func parseImportedOrders(r *http.Request) ([]map[string]any, error) { return nil, fmt.Errorf("缺少上传文件") } defer file.Close() - raw, err := io.ReadAll(file) + raw, err := io.ReadAll(io.LimitReader(file, (32<<20)+1)) if err != nil { return nil, fmt.Errorf("读取上传文件失败: %w", err) } + if len(raw) > 32<<20 { + return nil, fmt.Errorf("上传文件不能超过 32 MiB") + } return parseImportedOrderBytes(raw, header.Filename) } - raw, err := io.ReadAll(r.Body) + raw, err := io.ReadAll(io.LimitReader(r.Body, (32<<20)+1)) if err != nil { return nil, fmt.Errorf("读取请求失败: %w", err) } + if len(raw) > 32<<20 { + return nil, fmt.Errorf("导入内容不能超过 32 MiB") + } return parseImportedOrderBytes(raw, "orders.json") } diff --git a/internal/server/server.go b/internal/server/server.go index b8264b4..aeeb0f1 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -1,4 +1,4 @@ -// Package server 实现 HTTP API 服务(chi 路由),移植自 Python reply_server.py 的 ~115 端点。 +// Package server 实现 HTTP API 服务(chi 路由)。 // 复用 internal/auth 中间件、internal/db.Store、internal/account.Manager。 // 端点按分组组织在同一 package 的多个 handler 文件中。 package server @@ -19,8 +19,10 @@ import ( "xianyu-go/internal/account" "xianyu-go/internal/auth" + "xianyu-go/internal/automation" "xianyu-go/internal/browser" "xianyu-go/internal/db" + "xianyu-go/internal/notify" "xianyu-go/internal/webui" "xianyu-go/internal/xianyu/mtop" "xianyu-go/internal/xianyu/qrlogin" @@ -28,15 +30,17 @@ import ( // Server 聚合 HTTP 服务依赖。 type Server struct { - Store *db.Store - Auth *auth.Service - Manager *account.Manager - Browser *browser.Manager - MTop *mtop.Client - QRLogin *qrlogin.Manager - Logger *slog.Logger - WebDir string // 前端静态资源目录(含 index.html) - Addr string + Store *db.Store + Auth *auth.Service + Manager *account.Manager + Automation *automation.Center + Browser *browser.Manager + Notifier *notify.Notifier + MTop *mtop.Client + QRLogin *qrlogin.Manager + Logger *slog.Logger + WebDir string // 前端静态资源目录(含 index.html) + Addr string } // New 构造。bm 为浏览器管理器(风控验证后用浏览器提取 cookie;为 nil 则禁用浏览器自动化)。 @@ -46,7 +50,7 @@ func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure } qrMgr := qrlogin.NewManager(logger) if bm != nil { - qrMgr.SetSidecarRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) { + qrMgr.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) { return bm.QRCookieRefresh(ctx, tmpCookies, verificationURL, onScreenshot) }) } @@ -66,7 +70,6 @@ func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure // Router 构建完整路由树。 func (s *Server) Router() http.Handler { r := chi.NewRouter() - r.Use(middleware.RealIP) r.Use(middleware.RequestID) r.Use(middleware.Recoverer) // 请求日志(精简)。 @@ -101,6 +104,8 @@ func (s *Server) Router() http.Handler { s.mountAnalyticsReal(r) // 卡密 + 发货规则 s.mountCardsReal(r) + // 自动化规则 + s.mountAutomation(r) // 商品 s.mountItemsReal(r) // 关键字 + 指定商品回复 @@ -111,16 +116,16 @@ func (s *Server) Router() http.Handler { // 通知 s.mountNotificationsReal(r) // 系统设置(已认证) - s.mountSettings(r) + s.mountSettingsReal(r) // AI 设置 - s.mountAIReply(r) + s.mountAIReplyReal(r) // 用户 - s.mountUser(r) + s.mountUserReal(r) // 管理员专用。 r.Group(func(r chi.Router) { r.Use(auth.RequireAdmin) - s.mountAdmin(r) + s.mountAdminReal(r) }) }) @@ -247,22 +252,18 @@ func setNoStore(w http.ResponseWriter) { } // isAPIPath 判断是否为 API 路径(不应被 SPA 拦截)。 -// 覆盖前端 vite proxy 列表中的所有后端前缀。 +// 仅保留实际挂载的路由前缀,与 Router() 中的 mount* 一一对应。 func isAPIPath(path string) bool { apiPrefixes := []string{ "/api/", "/admin/", "/health", "/login", "/logout", "/verify", "/change-password", "/change-admin-password", "/account/", "/cookies", "/cookie/", "/orders", "/analytics", - "/cards", "/delivery-rules", "/items", "/keywords", "/default-replies", "/default-reply", + "/cards", "/automation-rules", "/items", "/keywords", "/default-replies", "/default-reply", "/notification-channels", "/message-notifications", - "/system-settings", "/ai-reply", "/ai-reply-settings", - "/ai-models", - "/user-settings", "/logs", "/risk-control", + "/system-settings", "/ai-reply", "/ai-models", + "/user-settings", "/item-reply", "/itemReplays", - "/register", "/registration-status", "/login-info-status", - "/qr-login", "/password-login", "/face-verification", - "/generate-captcha", "/verify-captcha", "/geetest", "/send-verification-code", - "/backup", "/upload-image", "/send-message", "/xianyu", + "/qr-login", "/static/", // 静态资源(由 /static/* handler 处理,不进 catch-all) } for _, p := range apiPrefixes { @@ -278,15 +279,19 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"status": "ok"}) } -// 占位:各分组 mount 方法在 handlers 文件中实现。 -// 为避免大文件,mount* 方法分文件定义但属于 Server。 +// 各分组 mount*Real 方法在 handlers 文件中实现;为避免单文件过大,按业务域分文件。 // Run 启动 HTTP 服务(阻塞)。 func (s *Server) Run(ctx context.Context) error { srv := &http.Server{ - Addr: s.Addr, - Handler: s.Router(), + Addr: s.Addr, + Handler: s.Router(), + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 2 * time.Minute, + IdleTimeout: 2 * time.Minute, } + // #nosec G118 -- 关闭协程由传入的服务生命周期上下文控制。 go func() { <-ctx.Done() shCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)