Files
Ydisks-Xianyu-Helper/internal/server/keyword_handlers.go
T
Christ 16d63dc7c9 完善系统可靠性、登录风控与跨数据库回归
可靠性与数据一致性:为 SQLite、MySQL、PostgreSQL 增加 00017 至 00021 迁移,引入账号暂停时间、默认回复和批量铺货租约、自动化运行恢复、延迟任务、动作检查点与通知 outbox。补强订单、卡密发货、Cookie、批量铺货和自动化任务的原子认领、幂等更新、并发控制、失败分类、重试与进程重启恢复,并扩展跨方言覆盖。

登录与风控恢复:完善扫码、密码登录、Cookie 续期、MTOP token、UA 与 WebSocket 生命周期;加入账号级持久化浏览器目录、Playwright 主引擎和直接 Chromium/CDP 备用引擎、严格的新 x5sec 成功判定、失败控件恢复及真实浏览器集成测试。增加可配置远程滑块服务,在明确失败、链接过期和服务不可用场景中保持既定的本地回退语义。

安全与配置:通过 XIANYU_DATA_KEY 为 Cookie、登录密码、设备与访问令牌、AI/SMTP 密钥及通知配置提供 AES-256-GCM 落库加密和历史明文升级。新增出站网络目标分级、防 DNS rebinding、登录限流、HTTP 客户端超时与 SMTP 目标校验;管理员配置的 AI 服务允许可信内网地址,非可信 Webhook 和远程资源继续限制为公网目标。

自动化与通知:为发货、评价赠送、邀评和回复动作增加断点、租约、延迟执行及人工继续/重试/取消入口;通知改为 outbox 驱动的可恢复投递。同步完善账号运行态、暂停状态、续期冷却、告警审计和异常查询接口。

前端体验:新增风控验证面板、方形二维码、账号运行态合并、暂停状态保护、自动化异常处置、批量铺货状态选择、订单导入结果和最新请求门禁。完善订单搜索与导入、规则编辑、批次恢复、通知与设置页面,并为请求取消、超时、陈旧响应和主要状态转换补充 Vitest 覆盖。

测试与部署:扩展三库功能编排、SQLite 一致性备份、数据卷持久化、浏览器集成镜像、前端类型检查和构建资产分包;功能测试覆盖健康检查、订单、铺货、自动化异常、账号暂停、关键词和系统设置。更新 README 中数据密钥、可信 AI 地址和测试端口说明。

验证结果:go vet ./...、go build ./cmd/server、gofmt 检查、npm run typecheck、npm test(17 个文件、95 个用例)及 npm run build 通过。go test ./... 未完全通过:internal/adapter 仍有 2 个密码续期用例失败,internal/renewal 仍有 4 个浏览器续期调度用例失败;其余 Go 包通过,失败现状随本次既有工作区一并提交。
2026-07-14 21:20:22 +08:00

363 lines
11 KiB
Go

package server
import (
"errors"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// mountKeywordsReal 关键字端点。
func (s *Server) mountKeywordsReal(r chi.Router) {
r.Get("/keywords/{cid}", s.listKeywords)
r.Post("/keywords/{cid}", s.addKeyword)
r.Get("/keywords-with-item-id/{cid}", s.listKeywordsWithItemID)
r.Post("/keywords-with-item-id/{cid}", s.addKeywordWithItemID)
r.Get("/keywords-with-type/{cid}", s.listKeywordsWithType)
r.Put("/keywords-with-type/{cid}/{id}", s.updateKeywordByID)
r.Delete("/keywords-with-type/{cid}/{id}", s.deleteKeywordByID)
r.Delete("/keywords/{cid}/{index}", s.deleteKeyword)
}
func (s *Server) listKeywords(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
out := make([]map[string]any, 0, len(rows))
for _, k := range rows {
out = append(out, map[string]any{"keyword": k.Keyword, "reply": k.Reply})
}
writeJSON(w, http.StatusOK, out)
}
func (s *Server) listKeywordsWithItemID(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
out := make([]map[string]any, 0, len(rows))
for _, k := range rows {
out = append(out, map[string]any{"keyword": k.Keyword, "reply": k.Reply, "item_id": k.ItemID})
}
writeJSON(w, http.StatusOK, out)
}
func (s *Server) listKeywordsWithType(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
out := make([]map[string]any, 0, len(rows))
for _, k := range rows {
out = append(out, map[string]any{
"id": k.ID, "keyword": k.Keyword, "reply": k.Reply, "item_id": k.ItemID,
"type": k.Type, "image_url": k.ImageURL,
})
}
writeJSON(w, http.StatusOK, out)
}
func (s *Server) addKeyword(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
var req struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
}
if err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.Keyword) == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
if strings.TrimSpace(req.Reply) == "" {
writeErr(w, http.StatusBadRequest, "文字回复内容不能为空")
return
}
if _, err := s.Store.Keywords.Add(r.Context(), cid, req.Keyword, req.Reply, "", "text", ""); err != nil {
writeErr(w, http.StatusInternalServerError, "添加失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
var req struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Type string `json:"type"`
ImageURL string `json:"image_url"`
Keywords *[]struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Type string `json:"type"`
ImageURL string `json:"image_url"`
} `json:"keywords"`
}
if err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if req.Keywords != nil {
rows := make([]db.KeywordRow, 0, len(*req.Keywords))
for _, item := range *req.Keywords {
if strings.TrimSpace(item.Keyword) == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
item.Type = strings.ToLower(strings.TrimSpace(item.Type))
if item.Type == "" {
item.Type = "text"
}
switch item.Type {
case "text":
if strings.TrimSpace(item.Reply) == "" {
writeErr(w, http.StatusBadRequest, "文字回复内容不能为空")
return
}
item.ImageURL = ""
case "image":
if strings.TrimSpace(item.ImageURL) == "" {
writeErr(w, http.StatusBadRequest, "图片回复 URL 不能为空")
return
}
item.Reply = ""
default:
writeErr(w, http.StatusBadRequest, "回复类型必须是 text 或 image")
return
}
rows = append(rows, db.KeywordRow{
CookieID: cid,
Keyword: item.Keyword,
Reply: item.Reply,
ItemID: item.ItemID,
Type: item.Type,
ImageURL: item.ImageURL,
})
}
if err := s.Store.Keywords.ReplaceForCookie(r.Context(), cid, rows); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
return
}
if strings.TrimSpace(req.Keyword) == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
req.Type = strings.ToLower(strings.TrimSpace(req.Type))
if req.Type == "" {
req.Type = "text"
}
if req.Type == "text" && strings.TrimSpace(req.Reply) == "" {
writeErr(w, http.StatusBadRequest, "文字回复内容不能为空")
return
}
if req.Type == "image" && strings.TrimSpace(req.ImageURL) == "" {
writeErr(w, http.StatusBadRequest, "图片回复 URL 不能为空")
return
}
if req.Type != "text" && req.Type != "image" {
writeErr(w, http.StatusBadRequest, "回复类型必须是 text 或 image")
return
}
if req.Type == "image" {
req.Reply = ""
} else {
req.ImageURL = ""
}
id, err := s.Store.Keywords.Add(r.Context(), cid, req.Keyword, req.Reply, req.ItemID, req.Type, req.ImageURL)
if err != nil {
writeErr(w, http.StatusInternalServerError, "添加失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": id})
}
func (s *Server) updateKeywordByID(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil || id <= 0 {
writeErr(w, http.StatusBadRequest, "无效关键词ID")
return
}
var req struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Type string `json:"type"`
ImageURL string `json:"image_url"`
}
if err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.Keyword) == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
req.Type = strings.ToLower(strings.TrimSpace(req.Type))
if req.Type == "" {
req.Type = "text"
}
switch req.Type {
case "text":
if strings.TrimSpace(req.Reply) == "" {
writeErr(w, http.StatusBadRequest, "文字回复内容不能为空")
return
}
req.ImageURL = ""
case "image":
if strings.TrimSpace(req.ImageURL) == "" {
writeErr(w, http.StatusBadRequest, "图片回复 URL 不能为空")
return
}
req.Reply = ""
default:
writeErr(w, http.StatusBadRequest, "回复类型必须是 text 或 image")
return
}
err = s.Store.Keywords.UpdateByID(r.Context(), db.KeywordRow{
ID: id, CookieID: cid, Keyword: req.Keyword, Reply: req.Reply,
ItemID: req.ItemID, Type: req.Type, ImageURL: req.ImageURL,
})
if err != nil {
if errors.Is(err, db.ErrNotFound) {
writeErr(w, http.StatusNotFound, "关键字不存在")
return
}
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func (s *Server) deleteKeywordByID(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil || id <= 0 {
writeErr(w, http.StatusBadRequest, "无效关键词ID")
return
}
if err := s.Store.Keywords.DeleteByID(r.Context(), cid, id); err != nil {
writeErr(w, http.StatusNotFound, "关键字不存在")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func (s *Server) deleteKeyword(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
index := atoiDefault(chi.URLParam(r, "index"), -1)
if err := s.Store.Keywords.DeleteByIndex(r.Context(), cid, index); err != nil {
writeErr(w, http.StatusNotFound, "关键字不存在")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
// ---- 指定商品回复 ----
func (s *Server) mountItemRepliesReal(r chi.Router) {
r.Get("/itemReplays", s.listItemReplies)
r.Get("/item-reply/{cookie_id}/{item_id}", s.getItemReply)
r.Put("/item-reply/{cookie_id}/{item_id}", s.setItemReply)
r.Delete("/item-reply/{cookie_id}/{item_id}", s.deleteItemReply)
}
func (s *Server) listItemReplies(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
all, _ := s.Store.Cookies.AllForUser(r.Context(), sess.UserID)
var result []map[string]any
for cid := range all {
rows, _ := s.Store.ItemReps.AllForUser(r.Context(), cid)
for _, ir := range rows {
result = append(result, map[string]any{
"item_id": ir.ItemID, "cookie_id": ir.CookieID, "reply_content": ir.ReplyContent,
})
}
}
writeJSON(w, http.StatusOK, result)
}
func (s *Server) getItemReply(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
itemID := chi.URLParam(r, "item_id")
ir, err := s.Store.ItemReps.Get(r.Context(), cid, itemID)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"reply_content": ""})
return
}
writeJSON(w, http.StatusOK, map[string]any{
"item_id": ir.ItemID, "cookie_id": ir.CookieID, "reply_content": ir.ReplyContent,
})
}
func (s *Server) setItemReply(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
itemID := chi.URLParam(r, "item_id")
var req struct {
ReplyContent string `json:"reply_content"`
}
if err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if err := s.Store.ItemReps.Set(r.Context(), cid, itemID, req.ReplyContent); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func (s *Server) deleteItemReply(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
itemID := chi.URLParam(r, "item_id")
if err := s.Store.ItemReps.Delete(r.Context(), cid, itemID); err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}