From d7abbfb2b648c0a3350123896fe505930a4a977e Mon Sep 17 00:00:00 2001 From: Christ Date: Sat, 8 Aug 2026 12:05:43 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E5=AE=8C=E5=96=84=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E7=AB=AF=E4=BA=A4=E4=BA=92=E6=97=A5=E5=BF=97=E4=B8=8E=E5=88=9D?= =?UTF-8?q?=E5=A7=8B=E5=8C=96=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 统一划分 MTOP 与 WebSocket 日志等级,增加 Token 安全指纹和请求耗时诊断;补充 init-admin 临时数据库测试;同步 README 的镜像发布说明。 --- README.md | 7 +- cmd/init-admin/main.go | 64 +++++++++------- cmd/init-admin/main_test.go | 106 +++++++++++++++++++++++++++ internal/engine/account.go | 17 ++++- internal/engine/token_cache_test.go | 16 ++++ internal/xianyu/mtop/client.go | 57 +++++++++++++- internal/xianyu/mtop/consign.go | 5 +- internal/xianyu/mtop/item_detail.go | 5 +- internal/xianyu/mtop/items.go | 5 +- internal/xianyu/mtop/login_status.go | 5 +- internal/xianyu/mtop/order_detail.go | 5 +- internal/xianyu/mtop/publish.go | 10 +-- internal/xianyu/mtop/sold_orders.go | 5 +- internal/xianyu/mtop/token.go | 5 +- internal/xianyu/mtop/user_profile.go | 5 +- internal/xianyu/ws/client.go | 31 +++++++- 16 files changed, 274 insertions(+), 74 deletions(-) create mode 100644 cmd/init-admin/main_test.go diff --git a/README.md b/README.md index e268b78..5846878 100644 --- a/README.md +++ b/README.md @@ -310,7 +310,7 @@ LocalAI 或兼容网关。只有在明确了解数据流向时才应向外部 AI GitHub Actions 会将同一标签发布为多架构镜像: ```text -ghcr.io/christ9038/ydisks-xianyu-helper:dev +ghcr.io/christ9038/ydisks-xianyu-helper:latest ├── linux/amd64 └── linux/arm64 ``` @@ -322,10 +322,13 @@ ARM64 Linux 拉取 arm64,不需要手动设置 `platform`。 | Git 引用 | 镜像标签 | | --- | --- | -| `dev` 分支 | `dev`、`sha-<完整提交号>` | | `main` 分支 | `main`、`latest`、`sha-<完整提交号>` | | `v1.2.3` 标签 | `1.2.3`、`1.2`、`sha-<完整提交号>` | +当前 Docker 发布工作流只在 `main` 分支推送和发布镜像;`dev` 分支不会自动生成 +GHCR 标签。开发分支如需验证镜像,请在本地使用源码构建 Compose 文件,或手动运行 +对应的构建流程。 + 生产环境建议使用明确的版本标签或 SHA 标签,避免上游更新导致未经验证的自动升级。 ### Compose 服务 diff --git a/cmd/init-admin/main.go b/cmd/init-admin/main.go index 048f132..fa2f597 100644 --- a/cmd/init-admin/main.go +++ b/cmd/init-admin/main.go @@ -7,8 +7,10 @@ package main import ( "bufio" "context" + "errors" "flag" "fmt" + "io" "os" "strings" @@ -32,66 +34,72 @@ func main() { resolved = *dbPath } - ctx := context.Background() + if err := run(context.Background(), resolved, bufio.NewReader(os.Stdin), os.Stdout); err != nil { + fatalf("初始化管理员失败: %v", err) + } +} + +// run 执行一次初始化流程。把数据库、输入和输出显式注入后,CLI 的核心行为 +// 可以在临时数据库中回归测试,而不会调用 os.Exit 或污染用户数据。 +func run(ctx context.Context, resolved string, reader *bufio.Reader, out io.Writer) error { database, dialect, err := db.Open(ctx, resolved) if err != nil { - fatalf("打开数据库失败: %v", err) + return fmt.Errorf("打开数据库失败: %w", err) } defer database.Close() store := db.NewStore(database, dialect) - reader := bufio.NewReader(os.Stdin) - existing, err := store.Users.GetAdmin(ctx) if err != nil && !isNotFound(err) { - fatalf("查询 admin 失败: %v", err) + return fmt.Errorf("查询 admin 失败: %w", err) } if existing != nil { - fmt.Printf("管理员用户 %s 已存在\n", existing.Username) - fmt.Print("是否重置管理员密码?(y/N): ") + fmt.Fprintf(out, "管理员用户 %s 已存在\n", existing.Username) + fmt.Fprint(out, "是否重置管理员密码?(y/N): ") ans, _ := reader.ReadString('\n') if !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ans)), "y") { - fmt.Println("跳过初始化") - return + fmt.Fprintln(out, "跳过初始化") + return nil } - pw := promptPasswordTwice(reader) + pw := promptPasswordTwice(reader, out) if _, err := auth.InitAdmin(ctx, store, "", pw); err != nil { - fatalf("重置 admin 密码失败: %v", err) + return fmt.Errorf("重置 admin 密码失败: %w", err) } - fmt.Printf("重置完成:已更新 %s 的密码\n", existing.Username) - return + fmt.Fprintf(out, "重置完成:已更新 %s 的密码\n", existing.Username) + return nil } - fmt.Println("=== 初始化管理员账号(CLI)===") - fmt.Print("请输入管理员邮箱: ") + fmt.Fprintln(out, "=== 初始化管理员账号(CLI)===") + fmt.Fprint(out, "请输入管理员邮箱: ") email, _ := reader.ReadString('\n') email = strings.TrimSpace(email) if email == "" { - fatalf("邮箱不能为空") + return errors.New("邮箱不能为空") } - pw := promptPasswordTwice(reader) + pw := promptPasswordTwice(reader, out) created, err := auth.InitAdmin(ctx, store, email, pw) if err != nil { - fatalf("创建 admin 用户失败:%v", err) + return fmt.Errorf("创建 admin 用户失败:%w", err) } if created { - fmt.Println("初始化完成:已创建 admin 用户") + fmt.Fprintln(out, "初始化完成:已创建 admin 用户") } + return nil } // promptPasswordTwice 两次输入密码(不回显)并校验一致性。 -func promptPasswordTwice(reader *bufio.Reader) string { +func promptPasswordTwice(reader *bufio.Reader, out io.Writer) string { for { - p1 := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ") + p1 := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ", out) if p1 == "" { - fmt.Println("密码不能为空") + fmt.Fprintln(out, "密码不能为空") continue } - p2 := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ") + p2 := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ", out) if p1 != p2 { - fmt.Println("两次输入不一致,请重试") + fmt.Fprintln(out, "两次输入不一致,请重试") continue } return p1 @@ -100,11 +108,11 @@ func promptPasswordTwice(reader *bufio.Reader) string { // readPasswordNoEcho 不回显读取密码。非 TTY 时回退到普通读取(如管道), // 共用同一 bufio.Reader 避免缓冲吞掉后续输入。 -func readPasswordNoEcho(reader *bufio.Reader, prompt string) string { - fmt.Print(prompt) +func readPasswordNoEcho(reader *bufio.Reader, prompt string, out io.Writer) string { + fmt.Fprint(out, prompt) if term.IsTerminal(int(os.Stdin.Fd())) { b, err := term.ReadPassword(int(os.Stdin.Fd())) - fmt.Println() + fmt.Fprintln(out) if err != nil { fatalf("读取密码失败: %v", err) } @@ -116,7 +124,7 @@ func readPasswordNoEcho(reader *bufio.Reader, prompt string) string { return strings.TrimSpace(s) } -func isNotFound(err error) bool { return err == db.ErrNotFound } +func isNotFound(err error) bool { return errors.Is(err, db.ErrNotFound) } func fatalf(format string, a ...any) { fmt.Fprintf(os.Stderr, format+"\n", a...) diff --git a/cmd/init-admin/main_test.go b/cmd/init-admin/main_test.go new file mode 100644 index 0000000..4d02243 --- /dev/null +++ b/cmd/init-admin/main_test.go @@ -0,0 +1,106 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "flag" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "xianyu-go/internal/db" +) + +func TestRunCreatesAdminInTemporaryDatabase(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "init-admin.db") + var out bytes.Buffer + err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nsecret\nsecret\n")), &out) + if err != nil { + t.Fatalf("run create: %v", err) + } + if !strings.Contains(out.String(), "初始化完成") { + t.Fatalf("missing create confirmation: %s", out.String()) + } + d, dialect, err := db.Open(context.Background(), dbPath) + if err != nil { + t.Fatal(err) + } + defer d.Close() + admin, err := db.NewStore(d, dialect).Users.GetAdmin(context.Background()) + if err != nil || admin == nil || admin.Email != "admin@example.com" { + t.Fatalf("admin=%+v err=%v", admin, err) + } +} + +func TestRunExistingAdminCanSkipReset(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "init-admin.db") + input := "admin@example.com\nsecret\nsecret\n" + if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("n\n")), &out); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "跳过初始化") { + t.Fatalf("missing skip confirmation: %s", out.String()) + } +} + +func TestRunExistingAdminResetsPasswordAfterMismatchRetry(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "init-admin.db") + if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nold\nold\n")), &bytes.Buffer{}); err != nil { + t.Fatal(err) + } + input := "y\nnew\nnot-the-same\nnew\nnew\n" + if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil { + t.Fatal(err) + } + d, dialect, err := db.Open(context.Background(), dbPath) + if err != nil { + t.Fatal(err) + } + defer d.Close() + store := db.NewStore(d, dialect) + if _, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "old"); ok { + t.Fatal("old password should be invalid") + } + if _, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "new"); !ok { + t.Fatal("new password should be valid") + } +} + +func TestRunRejectsEmptyEmail(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "init-admin.db") + err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("\n")), &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), "邮箱不能为空") { + t.Fatalf("err=%v, want empty email error", err) + } +} + +func TestMainCLIEntrypointUsesDatabaseFlag(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "main.db") + stdin, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + oldArgs, oldStdin, oldEnv, oldCommandLine := os.Args, os.Stdin, os.Getenv("DATABASE_URL"), flag.CommandLine + defer func() { + os.Args, os.Stdin, flag.CommandLine = oldArgs, oldStdin, oldCommandLine + _ = os.Setenv("DATABASE_URL", oldEnv) + _ = stdin.Close() + }() + os.Args = []string{"init-admin", "-db", dbPath} + os.Stdin = stdin + flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError) + flag.CommandLine.SetOutput(io.Discard) + _ = os.Unsetenv("DATABASE_URL") + go func() { + _, _ = writer.Write([]byte("admin@example.com\nmain-secret\nmain-secret\n")) + _ = writer.Close() + }() + main() +} diff --git a/internal/engine/account.go b/internal/engine/account.go index 2152802..b9c37d4 100644 --- a/internal/engine/account.go +++ b/internal/engine/account.go @@ -8,6 +8,7 @@ package engine import ( "context" "crypto/rand" + "crypto/sha256" "errors" "fmt" "log/slog" @@ -192,6 +193,7 @@ type Account struct { tokenAcquiredAt time.Time tokenExpiresAt time.Time tokenRefreshAt time.Time + tokenFingerprint string // 仅用于诊断,不保存原始 Token // 去重 dedupMu sync.Mutex @@ -1539,12 +1541,15 @@ func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken stri } now := time.Now() expiresAt, refreshAt := tokenRotationSchedule(serverExpireAt, now) + tokenFP := tokenFingerprint(accessToken) a.mu.Lock() + previousTokenFP := a.tokenFingerprint + a.tokenFingerprint = tokenFP a.tokenAcquiredAt = now a.tokenExpiresAt = expiresAt a.tokenRefreshAt = refreshAt a.mu.Unlock() - a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second)) + a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second), "token_fp", tokenFP, "previous_token_fp", previousTokenFP, "token_changed", previousTokenFP == "" || previousTokenFP != tokenFP) if a.store == nil || a.store.Tokens == nil { return } @@ -1561,8 +1566,18 @@ func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken stri } } +// tokenFingerprint 用不可逆摘要标识 Token,便于判断服务端是否轮换了 Token, +// 同时避免日志泄露可用于 WS 注册的凭证原文。 +func tokenFingerprint(token string) string { + sum := sha256.Sum256([]byte(token)) + return fmt.Sprintf("%x", sum[:6]) +} + // clearTokenCache 清除账号 token 缓存(session 失效 / 短连接可疑 / cookie 被外部更新时调用)。 func (a *Account) clearTokenCache(ctx context.Context) { + a.mu.Lock() + a.tokenFingerprint = "" + a.mu.Unlock() if a.store == nil || a.store.Tokens == nil { return } diff --git a/internal/engine/token_cache_test.go b/internal/engine/token_cache_test.go index 0036841..741780d 100644 --- a/internal/engine/token_cache_test.go +++ b/internal/engine/token_cache_test.go @@ -76,3 +76,19 @@ func TestCredentialStateFingerprintIncludesAuthoritativeSnapshot(t *testing.T) { t.Fatal("权威空 Jar 必须与没有快照的历史状态区分") } } + +func TestTokenFingerprintIsStableNonReversibleDiagnosticID(t *testing.T) { + first := tokenFingerprint("access-token-a") + if first == "" || len(first) != 12 { + t.Fatalf("token fingerprint=%q, want 12 hex chars", first) + } + if first != tokenFingerprint("access-token-a") { + t.Fatal("same token must produce stable fingerprint") + } + if first == tokenFingerprint("access-token-b") { + t.Fatal("different tokens must produce different fingerprints") + } + if first == "access-token-a" { + t.Fatal("fingerprint must not expose the token") + } +} diff --git a/internal/xianyu/mtop/client.go b/internal/xianyu/mtop/client.go index 97729dd..e9d6b21 100644 --- a/internal/xianyu/mtop/client.go +++ b/internal/xianyu/mtop/client.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "io" + "log/slog" "net/http" "strconv" "strings" @@ -61,7 +62,10 @@ type Client interface { // ClientImpl 是 Client 接口的 HTTP 实现。零值可用;HTTP 超时默认 30s。 // 仍导出 HTTPClient/TokenURL 等字段以便调用方覆盖(如测试注入 RoundTripper)。 type ClientImpl struct { - HTTPClient *http.Client + HTTPClient *http.Client + // Logger 记录 MTOP 请求的安全摘要(不会输出 Cookie、签名或响应正文)。 + // 未设置时使用 slog.Default,测试可传入丢弃日志的 logger。 + Logger *slog.Logger TokenURL string ConsignURL string OrderDetailURL string @@ -70,6 +74,57 @@ type ClientImpl struct { LoginUserURL string } +// httpClient 返回带统一请求/响应日志的 HTTP 客户端副本。统一放在传输层, +// 确保 token、续期、订单、商品和发布等所有 MTOP 调用都具备一致的可观测性。 +func (c *ClientImpl) httpClient() *http.Client { + return c.httpClientWithTimeout(30 * time.Second) +} + +func (c *ClientImpl) httpClientWithTimeout(defaultTimeout time.Duration) *http.Client { + hc := c.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: defaultTimeout} + } + clone := *hc + transport := hc.Transport + if transport == nil { + transport = http.DefaultTransport + } + clone.Transport = loggingTransport{base: transport, logger: c.Logger} + return &clone +} + +type loggingTransport struct { + base http.RoundTripper + logger *slog.Logger +} + +func (t loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) { + logger := t.logger + if logger == nil { + logger = slog.Default() + } + started := time.Now() + logger.Debug("MTOP 请求开始", "method", req.Method, "path", req.URL.Path) + resp, err := t.base.RoundTrip(req) + attrs := []any{"method", req.Method, "path", req.URL.Path, "duration", time.Since(started).Round(time.Millisecond)} + if err != nil { + if errors.Is(err, context.Canceled) { + logger.Debug("MTOP 请求取消", append(attrs, "err", err)...) + } else { + logger.Warn("MTOP 请求失败", append(attrs, "err", err)...) + } + return nil, err + } + responseAttrs := append(attrs, "status", resp.StatusCode, "content_length", resp.ContentLength) + if resp.StatusCode >= http.StatusBadRequest { + logger.Warn("MTOP HTTP 响应异常", responseAttrs...) + } else { + logger.Debug("MTOP 响应收到", responseAttrs...) + } + return resp, nil +} + // NewClient 构造纯 Go HTTP 的 MTOP 客户端。Chromium 只用于读取本机指纹 // 和处理滑块,不能成为登录、续期、token 或 WebSocket 的传输层。 func NewClient() *ClientImpl { diff --git a/internal/xianyu/mtop/consign.go b/internal/xianyu/mtop/consign.go index 10faf82..3310bfe 100644 --- a/internal/xianyu/mtop/consign.go +++ b/internal/xianyu/mtop/consign.go @@ -68,10 +68,7 @@ func (c *ClientImpl) ConsignContext(ctx context.Context, cookiesStr, orderID str } func (c *ClientImpl) consignOnce(ctx context.Context, cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error) { - hc := c.HTTPClient - if hc == nil { - hc = &http.Client{Timeout: 30 * time.Second} - } + hc := c.httpClient() consignURL := c.ConsignURL if consignURL == "" { consignURL = ConsignAPI diff --git a/internal/xianyu/mtop/item_detail.go b/internal/xianyu/mtop/item_detail.go index 4c9d30d..23be89b 100644 --- a/internal/xianyu/mtop/item_detail.go +++ b/internal/xianyu/mtop/item_detail.go @@ -49,10 +49,7 @@ func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID st req.Header.Set("Origin", "https://www.goofish.com") req.Header.Set("Referer", documentURL) - hc := c.HTTPClient - if hc == nil { - hc = &http.Client{Timeout: 30 * time.Second} - } + hc := c.httpClient() resp, err := hc.Do(req) if err != nil { return false, fmt.Errorf("商品详情请求失败: %w", err) diff --git a/internal/xianyu/mtop/items.go b/internal/xianyu/mtop/items.go index 5acae54..de08bc1 100644 --- a/internal/xianyu/mtop/items.go +++ b/internal/xianyu/mtop/items.go @@ -59,10 +59,7 @@ func (c *ClientImpl) FetchItemsPage(ctx context.Context, cookiesStr string, page } func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string, pageNumber, pageSize int) (*ItemListResult, []string, string, error) { - hc := c.HTTPClient - if hc == nil { - hc = &http.Client{Timeout: 30 * time.Second} - } + hc := c.httpClient() signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", ItemListAPI) cookies := protocol.TransCookies(signingCookies) userID := cookies["unb"] diff --git a/internal/xianyu/mtop/login_status.go b/internal/xianyu/mtop/login_status.go index ea4a67e..eef2a76 100644 --- a/internal/xianyu/mtop/login_status.go +++ b/internal/xianyu/mtop/login_status.go @@ -38,10 +38,7 @@ func (c *ClientImpl) CheckLoginStatusContext(ctx context.Context, cookiesStr str if session := cookieSessionFromContext(ctx); session != nil { cookiesStr, _, _ = session.State() } - hc := c.HTTPClient - if hc == nil { - hc = &http.Client{Timeout: 20 * time.Second} - } + hc := c.httpClientWithTimeout(20 * time.Second) loginURL := c.LoginUserURL if loginURL == "" { loginURL = LoginUserAPI diff --git a/internal/xianyu/mtop/order_detail.go b/internal/xianyu/mtop/order_detail.go index fe955af..a898d2a 100644 --- a/internal/xianyu/mtop/order_detail.go +++ b/internal/xianyu/mtop/order_detail.go @@ -66,10 +66,7 @@ func (c *ClientImpl) FetchOrderDetail(ctx context.Context, cookiesStr, orderID s } func (c *ClientImpl) fetchOrderDetailOnce(ctx context.Context, cookiesStr, orderID string) (*OrderDetailResult, []string, string, error) { - hc := c.HTTPClient - if hc == nil { - hc = &http.Client{Timeout: 30 * time.Second} - } + hc := c.httpClient() endpoint := c.OrderDetailURL if endpoint == "" { endpoint = OrderDetailAPI diff --git a/internal/xianyu/mtop/publish.go b/internal/xianyu/mtop/publish.go index 338f75f..7ce4bb1 100644 --- a/internal/xianyu/mtop/publish.go +++ b/internal/xianyu/mtop/publish.go @@ -208,10 +208,7 @@ func (c *ClientImpl) RecommendPublishCategory(ctx context.Context, cookiesStr, k } func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string, img PublishImage) (uploadedImage, string, error) { - hc := c.HTTPClient - if hc == nil { - hc = &http.Client{Timeout: 60 * time.Second} - } + hc := c.httpClientWithTimeout(60 * time.Second) if img.ContentType == "" { img.ContentType = "application/octet-stream" } @@ -495,10 +492,7 @@ func (c *ClientImpl) publishItemOnce(ctx context.Context, cookiesStr string, req } func (c *ClientImpl) callMTop(ctx context.Context, cookiesStr, endpoint, api, version, spmCnt, spmPre, logID string, data any) (map[string]any, string, error) { - hc := c.HTTPClient - if hc == nil { - hc = &http.Client{Timeout: 30 * time.Second} - } + hc := c.httpClient() rawData, _ := json.Marshal(data) dataVal := string(rawData) signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", endpoint) diff --git a/internal/xianyu/mtop/sold_orders.go b/internal/xianyu/mtop/sold_orders.go index a21e91f..1c70989 100644 --- a/internal/xianyu/mtop/sold_orders.go +++ b/internal/xianyu/mtop/sold_orders.go @@ -88,10 +88,7 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa req.Header.Set("Referer", soldOrdersReferer) req.Header.Set("idle_site_biz_code", "COMMONPRO") - hc := c.HTTPClient - if hc == nil { - hc = &http.Client{Timeout: 30 * time.Second} - } + hc := c.httpClient() resp, err := hc.Do(req) if err != nil { return nil, fmt.Errorf("订单列表请求失败: %w", err) diff --git a/internal/xianyu/mtop/token.go b/internal/xianyu/mtop/token.go index 995fe88..95c6d27 100644 --- a/internal/xianyu/mtop/token.go +++ b/internal/xianyu/mtop/token.go @@ -154,10 +154,7 @@ func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesS } func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string, cookieSnapshot []cookierefresh.BrowserCookie) (string, int64, []string, string, []cookierefresh.BrowserCookie, string, int, bool, bool, error) { - hc := c.HTTPClient - if hc == nil { - hc = &http.Client{Timeout: 20 * time.Second} - } + hc := c.httpClientWithTimeout(20 * time.Second) tokenURL := c.TokenURL if tokenURL == "" { diff --git a/internal/xianyu/mtop/user_profile.go b/internal/xianyu/mtop/user_profile.go index d5dae7c..fec109a 100644 --- a/internal/xianyu/mtop/user_profile.go +++ b/internal/xianyu/mtop/user_profile.go @@ -53,10 +53,7 @@ func (c *ClientImpl) FetchUserProfile(ctx context.Context, cookiesStr string) (* } func (c *ClientImpl) fetchUserProfileOnce(ctx context.Context, cookiesStr string) (*UserProfileResult, []string, string, error) { - hc := c.HTTPClient - if hc == nil { - hc = &http.Client{Timeout: 30 * time.Second} - } + hc := c.httpClient() dataVal := "{}" signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", UserPageNavAPI) diff --git a/internal/xianyu/ws/client.go b/internal/xianyu/ws/client.go index db3d00e..5f4be5d 100644 --- a/internal/xianyu/ws/client.go +++ b/internal/xianyu/ws/client.go @@ -5,6 +5,7 @@ import ( "context" "encoding/base64" "encoding/json" + "errors" "fmt" "log/slog" "net/http" @@ -232,9 +233,11 @@ func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logg if result.conn != nil { _ = result.conn.CloseNow() } + logger.Warn("闲鱼 WebSocket 握手失败", "url", target, "err", result.err) return nil, fmt.Errorf("WS dial: %w", result.err) } result.conn.SetReadLimit(8 << 20) + logger.Info("闲鱼 WebSocket 握手成功", "url", target) return newConn(result.conn, cfg, logger), nil } @@ -350,6 +353,8 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any, headers["mid"] = mid } key := midKey(mid) + started := time.Now() + c.logger.Debug("WS 请求发送", "path", path, "mid", key) responseCh := make(chan map[string]any, 1) c.pendingMu.Lock() c.pending[key] = responseCh @@ -365,10 +370,13 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any, frame["body"] = body } if err := c.sendJSON(requestCtx, frame); err != nil { + c.logger.Warn("WS 请求发送失败", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err) return nil, err } select { case response := <-responseCh: + code, _ := responseCode(response["code"]) + c.logResponse(path, key, code, time.Since(started)) return response, nil case <-c.readDone: // readPump always dispatches a decoded response before it can observe the @@ -376,15 +384,34 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any, // matching browser event ordering (message before close). select { case response := <-responseCh: + code, _ := responseCode(response["code"]) + c.logResponse(path, key, code, time.Since(started)) return response, nil default: } - return nil, c.connectionReadError() + err := c.connectionReadError() + c.logger.Warn("WS 请求因连接结束失败", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err) + return nil, err case <-requestCtx.Done(): - return nil, requestCtx.Err() + err := requestCtx.Err() + if errors.Is(err, context.Canceled) { + c.logger.Debug("WS 请求取消", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err) + } else { + c.logger.Warn("WS 请求超时", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err) + } + return nil, err } } +func (c *Conn) logResponse(path, mid string, code int, duration time.Duration) { + attrs := []any{"path", path, "mid", mid, "code", code, "duration", duration.Round(time.Millisecond)} + if code >= 400 { + c.logger.Warn("WS 业务响应异常", attrs...) + return + } + c.logger.Debug("WS 响应收到", attrs...) +} + func (c *Conn) readPump() { defer close(c.readDone) for { From 67d72149304ba4fc9302cf1b95f46a64a28a0591 Mon Sep 17 00:00:00 2001 From: Christ Date: Sat, 8 Aug 2026 22:16:35 +0800 Subject: [PATCH 2/2] feat: add account automation and isolated chat - add account-level auto rating and daily polish tasks\n- add cached historical chat, media, emoji, and per-account realtime sync\n- add SQLite, MySQL, and PostgreSQL migrations and regression coverage\n- align account, sidebar, and chat interfaces with the new workflows --- cmd/server/main.go | 4 + frontend/App.tsx | 15 +- frontend/chatEmojis.test.tsx | 22 + frontend/chatEmojis.tsx | 516 +++++++++++++++++ frontend/chatFeature.test.ts | 46 ++ .../components/AccountAutomationModal.tsx | 156 ++++++ frontend/components/AccountList.tsx | 67 ++- frontend/components/Chat.tsx | 523 ++++++++++++++++++ frontend/components/Sidebar.tsx | 104 ++-- frontend/components/sidebarState.test.ts | 28 + frontend/components/sidebarState.ts | 18 + frontend/services/api.test.ts | 36 ++ frontend/services/api.ts | 62 +++ frontend/types.ts | 55 ++ frontend/vite.config.ts | 1 + internal/adapter/adapter.go | 34 +- internal/automation/account_tasks.go | 229 ++++++++ internal/automation/account_tasks_test.go | 156 ++++++ internal/automation/center.go | 25 +- internal/automation/scheduler.go | 1 + internal/chat/service.go | 498 +++++++++++++++++ internal/chat/service_test.go | 241 ++++++++ internal/db/account_tasks.go | 189 +++++++ internal/db/chat.go | 272 +++++++++ internal/db/migrate_test.go | 13 +- .../mysql/00024_chat_account_tasks.sql | 75 +++ .../mysql/00025_chat_direction_repair.sql | 12 + .../postgres/00024_chat_account_tasks.sql | 72 +++ .../postgres/00025_chat_direction_repair.sql | 12 + .../sqlite/00024_chat_account_tasks.sql | 75 +++ .../sqlite/00025_chat_direction_repair.sql | 12 + internal/db/multidb_test.go | 102 +++- internal/db/store.go | 4 + internal/engine/account.go | 69 ++- internal/engine/dispatch.go | 6 + internal/engine/engine_test.go | 11 + internal/engine/outgoing_chat_test.go | 43 ++ internal/engine/reply_extra_test.go | 3 + internal/server/account_task_handlers.go | 107 ++++ internal/server/chat_account_tasks_test.go | 123 ++++ internal/server/chat_handlers.go | 435 +++++++++++++++ internal/server/cookie_handlers.go | 78 +-- internal/server/server.go | 8 + ...-B_BfwiL0.js => charts-vendor-BxxJOyEX.js} | 2 +- ...r-RenKjhri.js => icons-vendor-DjsKcZkz.js} | 191 ++++--- .../webui/static/assets/index-2_f0Vmhn.js | 19 - .../webui/static/assets/index-BIyp4is6.js | 19 + .../webui/static/assets/index-DMeflf1O.css | 1 - .../webui/static/assets/index-DtBcYu3b.css | 1 + ...r-DZnRGM0-.js => react-vendor-C_od1ZSF.js} | 2 +- ...{vendor-w5t2K9ux.js => vendor-D-Edl3pr.js} | 2 +- internal/webui/static/index.html | 12 +- internal/xianyu/mtop/account_tasks.go | 269 +++++++++ .../account_tasks_live_integration_test.go | 54 ++ internal/xianyu/mtop/account_tasks_test.go | 103 ++++ internal/xianyu/mtop/chat_media.go | 54 ++ internal/xianyu/mtop/chat_media_test.go | 48 ++ internal/xianyu/mtop/client.go | 19 +- internal/xianyu/ws/client.go | 59 ++ 59 files changed, 5202 insertions(+), 211 deletions(-) create mode 100644 frontend/chatEmojis.test.tsx create mode 100644 frontend/chatEmojis.tsx create mode 100644 frontend/chatFeature.test.ts create mode 100644 frontend/components/AccountAutomationModal.tsx create mode 100644 frontend/components/Chat.tsx create mode 100644 frontend/components/sidebarState.test.ts create mode 100644 frontend/components/sidebarState.ts create mode 100644 internal/automation/account_tasks.go create mode 100644 internal/automation/account_tasks_test.go create mode 100644 internal/chat/service.go create mode 100644 internal/chat/service_test.go create mode 100644 internal/db/account_tasks.go create mode 100644 internal/db/chat.go create mode 100644 internal/db/migrations/mysql/00024_chat_account_tasks.sql create mode 100644 internal/db/migrations/mysql/00025_chat_direction_repair.sql create mode 100644 internal/db/migrations/postgres/00024_chat_account_tasks.sql create mode 100644 internal/db/migrations/postgres/00025_chat_direction_repair.sql create mode 100644 internal/db/migrations/sqlite/00024_chat_account_tasks.sql create mode 100644 internal/db/migrations/sqlite/00025_chat_direction_repair.sql create mode 100644 internal/engine/outgoing_chat_test.go create mode 100644 internal/server/account_task_handlers.go create mode 100644 internal/server/chat_account_tasks_test.go create mode 100644 internal/server/chat_handlers.go rename internal/webui/static/assets/{charts-vendor-B_BfwiL0.js => charts-vendor-BxxJOyEX.js} (99%) rename internal/webui/static/assets/{icons-vendor-RenKjhri.js => icons-vendor-DjsKcZkz.js} (59%) delete mode 100644 internal/webui/static/assets/index-2_f0Vmhn.js create mode 100644 internal/webui/static/assets/index-BIyp4is6.js delete mode 100644 internal/webui/static/assets/index-DMeflf1O.css create mode 100644 internal/webui/static/assets/index-DtBcYu3b.css rename internal/webui/static/assets/{react-vendor-DZnRGM0-.js => react-vendor-C_od1ZSF.js} (99%) rename internal/webui/static/assets/{vendor-w5t2K9ux.js => vendor-D-Edl3pr.js} (99%) create mode 100644 internal/xianyu/mtop/account_tasks.go create mode 100644 internal/xianyu/mtop/account_tasks_live_integration_test.go create mode 100644 internal/xianyu/mtop/account_tasks_test.go create mode 100644 internal/xianyu/mtop/chat_media.go create mode 100644 internal/xianyu/mtop/chat_media_test.go diff --git a/cmd/server/main.go b/cmd/server/main.go index b8fd85f..291ad1f 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -28,6 +28,7 @@ import ( "xianyu-go/internal/auth" "xianyu-go/internal/automation" "xianyu-go/internal/browser" + "xianyu-go/internal/chat" "xianyu-go/internal/db" "xianyu-go/internal/logging" "xianyu-go/internal/notify" @@ -149,6 +150,8 @@ func main() { } var mgr *account.Manager ap := adapter.New(store, bm, logger) + chatService := chat.New(store) + ap.SetChatService(chatService) mgr = account.NewManager(store, ap, logger) autoCenter := automation.New(store, mgr, logger) autoCenter.SetOrderDetailFetcher(ap) @@ -167,6 +170,7 @@ func main() { // 3) HTTP 服务。 srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier) + srv.SetChatService(chatService) srv.StartPublishBatchRecovery(ctx) if err := srv.Run(ctx); err != nil { logger.Error("HTTP 服务退出", "err", err) diff --git a/frontend/App.tsx b/frontend/App.tsx index ba7cd10..e8313f6 100644 --- a/frontend/App.tsx +++ b/frontend/App.tsx @@ -8,6 +8,8 @@ import ItemList from './components/ItemList'; import Settings from './components/Settings'; import Rules from './components/Rules'; import Notifications from './components/Notifications'; +import Chat from './components/Chat'; +import { readSidebarCollapsed, writeSidebarCollapsed } from './components/sidebarState'; import { YdisksBrandIcon } from './components/YdisksLogo'; import { login, logout, verifySession } from './services/api'; import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react'; @@ -24,6 +26,7 @@ interface DeliveryRuleTarget { const ROUTES: Record = { '/app/dashboard': 'dashboard', '/app/accounts': 'accounts', + '/app/chat': 'chat', '/app/orders': 'orders', '/app/cards': 'cards', '/app/items': 'items', @@ -50,6 +53,7 @@ const App: React.FC = () => { const [loginLoading, setLoginLoading] = useState(false); const [loginError, setLoginError] = useState(''); const [deliveryRuleTarget, setDeliveryRuleTarget] = useState(); + const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed); // 切换 tab 并同步 URL。若 tab 没有对应 path(不应发生)则只切 tab。 const navigate = (tab: string) => { @@ -266,6 +270,7 @@ const App: React.FC = () => { switch (activeTab) { case 'dashboard': return ; case 'accounts': return ; + case 'chat': return ; case 'orders': return ; case 'cards': return ; case 'items': return { @@ -287,15 +292,21 @@ const App: React.FC = () => { setSidebarCollapsed(current => { + const next = !current; + writeSidebarCollapsed(next); + return next; + })} onNavigate={navigate} onLogout={handleLogout} /> -
+
{/* Subtle background decoration */}
-
+
{renderContent()}
diff --git a/frontend/chatEmojis.test.tsx b/frontend/chatEmojis.test.tsx new file mode 100644 index 0000000..fd8631e --- /dev/null +++ b/frontend/chatEmojis.test.tsx @@ -0,0 +1,22 @@ +import { renderToStaticMarkup } from 'react-dom/server'; +import { describe, expect, test } from 'vitest'; +import { renderXianyuText, xianyuEmojis } from './chatEmojis'; + +describe('official Xianyu emoji mapping', () => { + test('contains the complete official panel in official order', () => { + expect(xianyuEmojis).toHaveLength(126); + expect(xianyuEmojis[0][0]).toBe('尊嘟假嘟'); + expect(xianyuEmojis.at(-1)?.[0]).toBe('爱心'); + expect(new Set(xianyuEmojis.map(([name]) => name)).size).toBe(126); + }); + + test('uses official CDN assets and renders bracket codes inline', () => { + for (const [, url] of xianyuEmojis) { + expect(url).toMatch(/^https:\/\/img\.alicdn\.com\//); + } + const html = renderToStaticMarkup(<>{renderXianyuText('你好[捂脸哭][送花]')}); + expect(html).toContain('你好'); + expect(html).toContain('alt="[捂脸哭]"'); + expect(html).toContain('alt="[送花]"'); + }); +}); diff --git a/frontend/chatEmojis.tsx b/frontend/chatEmojis.tsx new file mode 100644 index 0000000..df310ee --- /dev/null +++ b/frontend/chatEmojis.tsx @@ -0,0 +1,516 @@ +import React from 'react'; + +export const xianyuEmojis = [ + [ + "尊嘟假嘟", + "https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp" + ], + [ + "鸡哔你", + "https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp" + ], + [ + "谁懂啊", + "https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp" + ], + [ + "吗喽", + "https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp" + ], + [ + "功德+1", + "https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp" + ], + [ + "city不city啊", + "https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp" + ], + [ + "激推", + "https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp" + ], + [ + "微笑", + "https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "龇牙", + "https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "流泪", + "https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "尴尬", + "https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "撇嘴", + "https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "破涕为笑", + "https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "捂脸哭", + "https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "害羞", + "https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "感动", + "https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "滴泪", + "https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "暗中观察", + "https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "偷笑", + "https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "ok", + "https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "送花", + "https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "大哭", + "https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "色", + "https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "惊慌", + "https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "惊讶", + "https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "得意", + "https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "睡", + "https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "不好意思", + "https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "托腮", + "https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "发怒", + "https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "难过", + "https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "调皮", + "https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "愉快", + "https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "白眼", + "https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "拒绝", + "https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "期待", + "https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "困", + "https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "流汗", + "https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "憨笑", + "https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "耶", + "https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "奋斗", + "https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "咒骂", + "https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "疑问", + "https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "嘘", + "https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "晕", + "https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "开心到模糊", + "https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "衰", + "https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "委屈", + "https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "再见", + "https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "鼓掌", + "https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "吐", + "https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "坏笑", + "https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "抠鼻", + "https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "叹气", + "https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "无聊", + "https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "思考", + "https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "呆", + "https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "哇哦", + "https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "飞吻", + "https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "好喜欢", + "https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "拜托", + "https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "真棒", + "https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "流鼻血", + "https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "费解", + "https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "秃头", + "https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "嘿哈", + "https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "吃土", + "https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "机智", + "https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "举杯", + "https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "握手", + "https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "挥手", + "https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "yeah", + "https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "666", + "https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "棒", + "https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "爱你", + "https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "比心", + "https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "感谢", + "https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "拍手", + "https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "拉钩", + "https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "没钱", + "https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "小刀", + "https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "不刀", + "https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "同出", + "https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "递钱", + "https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "数钱", + "https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "打call", + "https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "号外", + "https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "包邮", + "https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "求赞", + "https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "非主流", + "https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "吃瓜", + "https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "种草", + "https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "佛系", + "https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "超便宜", + "https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "拥抱", + "https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "摊手", + "https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "举手", + "https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "蹲", + "https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "跪了", + "https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "拜", + "https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "排", + "https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "旺财", + "https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "招财猫", + "https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "酸了", + "https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "鸭鸭", + "https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "方了", + "https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "白菜", + "https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "桃子", + "https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "打包", + "https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "沙发", + "https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "南", + "https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "盯", + "https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "hot", + "https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "new", + "https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "cool", + "https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "1", + "https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "可", + "https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "搬砖", + "https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "菜狗", + "https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "开心面具", + "https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "快递", + "https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "裂开", + "https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "啤酒", + "https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "瑞思拜", + "https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "小丑", + "https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp" + ], + [ + "爱心", + "https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp" + ] +] as const; + +export const emojiURL = (url: string) => url; +const emojiLookup = new Map(xianyuEmojis.map(([name, url]) => [name, url])); + +export const renderXianyuText = (text: string) => text.split(/(\[[^\]]+\])/g).map((part, index) => { + const url = part.startsWith('[') ? emojiLookup.get(part.slice(1, -1)) : undefined; + return url ? {part} : {part}; +}); diff --git a/frontend/chatFeature.test.ts b/frontend/chatFeature.test.ts new file mode 100644 index 0000000..af255f1 --- /dev/null +++ b/frontend/chatFeature.test.ts @@ -0,0 +1,46 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { describe, expect, test } from 'vitest'; + +const source = (path: string) => readFileSync(resolve(__dirname, path), 'utf8'); + +describe('online chat UI contract', () => { + test('uses account tabs above a two-column buyer/chat layout', () => { + const chat = source('components/Chat.tsx'); + expect(chat).toContain('role="tablist"'); + expect(chat).toContain('grid-cols-[320px_minmax(0,1fr)]'); + expect(chat).toContain('min-h-0 min-w-0 flex-col overflow-hidden'); + expect(chat).not.toContain('grid-cols-[320px_minmax(0,1fr)_'); + expect(chat).toContain('activeAccountID'); + expect(chat).toContain('activeChatID'); + }); + + test('uses neutral user labels instead of assuming buyer role', () => { + const chat = source('components/Chat.tsx'); + expect(chat).toContain('用户 ID:'); + expect(chat).not.toContain('买家 ID:'); + expect(chat).not.toContain('选择一个买家'); + }); + + test('frontend connects only to the application chat websocket', () => { + const chat = source('components/Chat.tsx'); + expect(chat).toContain('/api/chat/ws'); + expect(chat).not.toContain('wss-goofish.dingtalk.com'); + }); + + test('renders peer/self identity and verified media capabilities', () => { + const chat = source('components/Chat.tsx'); + expect(chat).toContain('selectedSession.buyer_avatar_url'); + expect(chat).toContain('activeAccount?.avatar_url'); + expect(chat).toContain("message.message_type === 'image'"); + expect(chat).toContain("message.message_type === 'video'"); + expect(chat).toContain('sendChatImage'); + }); + + test('sidebar exposes collapse control and chat primary navigation', () => { + const sidebar = source('components/Sidebar.tsx'); + expect(sidebar).toContain("id: 'chat'"); + expect(sidebar).toContain('onToggleCollapsed'); + expect(sidebar).toContain('collapsed ? \'w-16\' : \'w-64\''); + }); +}); diff --git a/frontend/components/AccountAutomationModal.tsx b/frontend/components/AccountAutomationModal.tsx new file mode 100644 index 0000000..6b3177b --- /dev/null +++ b/frontend/components/AccountAutomationModal.tsx @@ -0,0 +1,156 @@ +import React, { useState } from 'react'; +import { CalendarClock, Loader2, MessageSquareQuote, Play, Save, Sparkles, X } from 'lucide-react'; +import { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../types'; +import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from '../services/api'; + +interface Props { + account: AccountDetail; + onClose: () => void; + onSaved: (settings: AccountTaskSettings) => void; +} + +const Toggle: React.FC<{checked: boolean; onChange: () => void; label: string}> = ({ checked, onChange, label }) => ( + +); + +const AccountAutomationModal: React.FC = ({ account, onClose, onSaved }) => { + const [form, setForm] = useState({ + account_id: account.id, + auto_rate_enabled: account.auto_rate_enabled === true, + rate_content: account.rate_content || '不错的买家,交易愉快', + auto_polish_enabled: account.auto_polish_enabled === true, + polish_time: account.polish_time || '03:00', + last_rate_scan_at: account.last_rate_scan_at, + last_polish_date: account.last_polish_date, + last_polish_at: account.last_polish_at, + }); + const [saving, setSaving] = useState(false); + const [running, setRunning] = useState<'' | 'auto_rate' | 'auto_polish'>(''); + const [error, setError] = useState(''); + const [summary, setSummary] = useState(null); + + const save = async () => { + setSaving(true); + setError(''); + try { + const stored = await updateAccountTaskSettings(account.id, form); + setForm(stored); + onSaved(stored); + } catch (saveError) { + setError(saveError instanceof Error ? saveError.message : '保存失败'); + } finally { + setSaving(false); + } + }; + + const run = async (taskType: 'auto_rate' | 'auto_polish') => { + setRunning(taskType); + setError(''); + setSummary(null); + try { + await updateAccountTaskSettings(account.id, form); + const result = await runAccountTask(account.id, taskType); + const stored = await getAccountTaskSettings(account.id); + setSummary(result.summary); + setForm(stored); + onSaved(stored); + } catch (runError) { + setError(runError instanceof Error ? runError.message : '任务执行失败'); + } finally { + setRunning(''); + } + }; + + return ( +
+
+
+
+

账号自动任务

+

{account.nickname || account.remark || account.id}

+
+ +
+ +
+
+
+
+
+
+
+

自动评价

+

持续扫描待评价订单,按订单执行;不是每日任务。

+
+ setForm(current => ({ ...current, auto_rate_enabled: !current.auto_rate_enabled }))} label="自动评价" /> +
+ +