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
This commit is contained in:
1 parent
d7abbfb2b6
commit
67d7214930
59 files changed
+5202
-211
No files matched your search
@@ -0,0 +1,107 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
var accountTaskTimePattern = regexp.MustCompile(`^(?:[01]\d|2[0-3]):[0-5]\d$`)
|
||||
|
||||
func (s *Server) mountAccountTasks(r chi.Router) {
|
||||
r.Get("/api/account-tasks/{cid}", s.getAccountTaskSettings)
|
||||
r.Put("/api/account-tasks/{cid}", s.updateAccountTaskSettings)
|
||||
r.Get("/api/account-tasks/{cid}/runs", s.listAccountTaskRuns)
|
||||
r.Post("/api/account-tasks/{cid}/run", s.runAccountTask)
|
||||
}
|
||||
|
||||
func (s *Server) getAccountTaskSettings(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.ownsAccount(r, cid) {
|
||||
writeErr(w, http.StatusForbidden, "无权访问该账号")
|
||||
return
|
||||
}
|
||||
settings, err := s.Store.AccountTasks.Get(r.Context(), cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取账号任务配置失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, settings)
|
||||
}
|
||||
|
||||
func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.ownsAccount(r, cid) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
var input db.AccountTaskSettings
|
||||
if decodeJSON(r, &input) != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
input.CookieID = cid
|
||||
input.RateContent = strings.TrimSpace(input.RateContent)
|
||||
if input.AutoRateEnabled && input.RateContent == "" {
|
||||
writeErr(w, http.StatusBadRequest, "启用自动评价时评价内容不能为空")
|
||||
return
|
||||
}
|
||||
if len([]rune(input.RateContent)) > 500 {
|
||||
writeErr(w, http.StatusBadRequest, "评价内容不能超过 500 个字符")
|
||||
return
|
||||
}
|
||||
if !accountTaskTimePattern.MatchString(input.PolishTime) {
|
||||
writeErr(w, http.StatusBadRequest, "擦亮时间格式必须为 HH:mm")
|
||||
return
|
||||
}
|
||||
if err := s.Store.AccountTasks.Upsert(r.Context(), input); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存账号任务配置失败")
|
||||
return
|
||||
}
|
||||
stored, _ := s.Store.AccountTasks.Get(r.Context(), cid)
|
||||
writeJSON(w, http.StatusOK, stored)
|
||||
}
|
||||
|
||||
func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.ownsAccount(r, cid) {
|
||||
writeErr(w, http.StatusForbidden, "无权访问该账号")
|
||||
return
|
||||
}
|
||||
runs, err := s.Store.AccountTasks.RecentRuns(r.Context(), cid, parsePositiveInt(r.URL.Query().Get("limit"), 20))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取任务记录失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"runs": runs})
|
||||
}
|
||||
|
||||
func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.ownsAccount(r, cid) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
if s.automation == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "自动化中心未启用")
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
TaskType string `json:"task_type"`
|
||||
}
|
||||
if decodeJSON(r, &input) != nil || (input.TaskType != automation.TaskAutoRate && input.TaskType != automation.TaskAutoPolish) {
|
||||
writeErr(w, http.StatusBadRequest, "不支持的任务类型")
|
||||
return
|
||||
}
|
||||
summary, err := s.automation.RunAccountTask(r.Context(), cid, input.TaskType)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{"summary": summary, "error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "summary": summary})
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
func TestChatHistoryAndAccountTaskSettingsEndpoints(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
service := chat.New(store)
|
||||
srv.SetChatService(service)
|
||||
handler := srv.Router()
|
||||
cookie := loginHelper(t, handler)
|
||||
|
||||
_, _, err := store.Chats.SaveMessage(context.Background(), db.ChatSession{CookieID: "acc1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家甲"},
|
||||
db.ChatMessage{MessageKey: "platform-1", Direction: "incoming", SenderID: "buyer-1", SenderName: "买家甲", MessageType: "text", Content: "你好", Status: "received", SentAt: 1000}, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/chat/sessions?account_id=acc1", nil)
|
||||
request.AddCookie(cookie)
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "买家甲") {
|
||||
t.Fatalf("sessions status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodGet, "/api/chat/messages?account_id=acc1&chat_id=chat-1", nil)
|
||||
request.AddCookie(cookie)
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "你好") {
|
||||
t.Fatalf("messages status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodPut, "/api/account-tasks/acc1", strings.NewReader(`{
|
||||
"auto_rate_enabled":true,"rate_content":"交易愉快","auto_polish_enabled":true,"polish_time":"04:30"
|
||||
}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(cookie)
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "交易愉快") {
|
||||
t.Fatalf("task settings status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
settings, err := store.AccountTasks.Get(context.Background(), "acc1")
|
||||
if err != nil || !settings.AutoRateEnabled || !settings.AutoPolishEnabled || settings.PolishTime != "04:30" {
|
||||
t.Fatalf("settings=%+v err=%v", settings, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
service := chat.New(store)
|
||||
srv.SetChatService(service)
|
||||
handler := srv.Router()
|
||||
cookie := loginHelper(t, handler)
|
||||
httpServer := httptest.NewServer(handler)
|
||||
defer httpServer.Close()
|
||||
|
||||
header := make(http.Header)
|
||||
header.Set("Cookie", cookie.String())
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/chat/ws", &websocket.DialOptions{HTTPHeader: header})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()
|
||||
var ready map[string]any
|
||||
if err := wsjson.Read(ctx, conn, &ready); err != nil || ready["type"] != "ready" {
|
||||
t.Fatalf("ready=%+v err=%v", ready, err)
|
||||
}
|
||||
if _, _, err := service.RecordIncoming(ctx, chat.Incoming{AccountID: "acc1", ChatID: "chat-live", BuyerID: "buyer",
|
||||
BuyerName: "实时买家", Text: "实时消息", Raw: map[string]any{"messageId": "live-1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var event chat.Event
|
||||
if err := wsjson.Read(ctx, conn, &event); err != nil || event.Type != "message.created" || event.Message.Content != "实时消息" {
|
||||
t.Fatalf("event=%+v err=%v", event, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.SetChatService(chat.New(srv.Store))
|
||||
handler := srv.Router()
|
||||
cookie := loginHelper(t, handler)
|
||||
|
||||
cases := []struct {
|
||||
method, path, body string
|
||||
want int
|
||||
}{
|
||||
{http.MethodGet, "/api/chat/sessions?account_id=missing", "", http.StatusForbidden},
|
||||
{http.MethodGet, "/api/chat/messages?account_id=acc1", "", http.StatusBadRequest},
|
||||
{http.MethodPut, "/api/account-tasks/acc1", `{"auto_rate_enabled":true,"rate_content":"","auto_polish_enabled":false,"polish_time":"03:00"}`, http.StatusBadRequest},
|
||||
{http.MethodPut, "/api/account-tasks/acc1", `{"auto_rate_enabled":false,"rate_content":"x","auto_polish_enabled":true,"polish_time":"25:99"}`, http.StatusBadRequest},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
request := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(cookie)
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != tc.want {
|
||||
t.Errorf("%s %s status=%d want=%d body=%s", tc.method, tc.path, recorder.Code, tc.want, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
func (s *Server) mountChat(r chi.Router) {
|
||||
r.Get("/api/chat/sessions", s.listChatSessions)
|
||||
r.Get("/api/chat/messages", s.listChatMessages)
|
||||
r.Post("/api/chat/messages", s.sendChatMessage)
|
||||
r.Post("/api/chat/images", s.sendChatImage)
|
||||
r.Post("/api/chat/read", s.markChatRead)
|
||||
r.Get("/api/chat/ws", s.chatWebSocket)
|
||||
}
|
||||
|
||||
func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
accountID := strings.TrimSpace(r.URL.Query().Get("account_id"))
|
||||
if !s.ownsAccount(r, accountID) {
|
||||
writeErr(w, http.StatusForbidden, "无权访问该账号")
|
||||
return
|
||||
}
|
||||
cursor, _ := strconv.ParseInt(r.URL.Query().Get("cursor"), 10, 64)
|
||||
refresh := r.URL.Query().Get("refresh") == "1"
|
||||
var hasMore bool
|
||||
var nextCursor int64
|
||||
if err := s.Store.Chats.DeleteEmptySessions(r.Context(), accountID); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "清理无效聊天会话失败")
|
||||
return
|
||||
}
|
||||
if refresh && s.chat != nil && s.Manager != nil {
|
||||
if sender, ok := s.Manager.GetInstance(accountID); ok {
|
||||
if fetcher, ok := sender.(interface {
|
||||
FetchChatConversations(context.Context, int64, int) (map[string]any, string, error)
|
||||
}); ok {
|
||||
fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
body, myID, fetchErr := fetcher.FetchChatConversations(fetchCtx, cursor, 100)
|
||||
cancel()
|
||||
if fetchErr == nil {
|
||||
page, saveErr := s.chat.RecordConversationPage(r.Context(), accountID, myID, body)
|
||||
if saveErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存历史联系人失败")
|
||||
return
|
||||
}
|
||||
hasMore, nextCursor = page.HasMore, page.NextCursor
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rows, err := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, parsePositiveInt(r.URL.Query().Get("limit"), 200))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取聊天会话失败")
|
||||
return
|
||||
}
|
||||
if refresh {
|
||||
if cookieValue, cookieErr := s.Store.Cookies.GetValue(r.Context(), accountID); cookieErr == nil {
|
||||
client, canResolve := s.mtopClient().(interface {
|
||||
FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error)
|
||||
})
|
||||
if !canResolve {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"sessions": rows, "has_more": hasMore, "next_cursor": nextCursor})
|
||||
return
|
||||
}
|
||||
resolveCtx, resolveCancel := context.WithTimeout(r.Context(), 25*time.Second)
|
||||
defer resolveCancel()
|
||||
jobs := make(chan int)
|
||||
var workers sync.WaitGroup
|
||||
for worker := 0; worker < 8; worker++ {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
for index := range jobs {
|
||||
infoCtx, cancel := context.WithTimeout(resolveCtx, 3*time.Second)
|
||||
info, infoErr := client.FetchChatUserInfo(infoCtx, cookieValue, rows[index].ChatID)
|
||||
cancel()
|
||||
if infoErr != nil || info == nil {
|
||||
continue
|
||||
}
|
||||
if nickname := strings.TrimSpace(info.Nickname); nickname != "" {
|
||||
rows[index].BuyerName = nickname
|
||||
}
|
||||
if info.AvatarURL != "" {
|
||||
rows[index].BuyerAvatar = info.AvatarURL
|
||||
}
|
||||
_ = s.Store.Chats.UpdateSessionIdentity(resolveCtx, accountID, rows[index].ChatID,
|
||||
rows[index].BuyerID, rows[index].BuyerName, rows[index].BuyerAvatar)
|
||||
}
|
||||
}()
|
||||
}
|
||||
queue:
|
||||
for index := range rows {
|
||||
if rows[index].BuyerID == "1400" {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case jobs <- index:
|
||||
case <-resolveCtx.Done():
|
||||
break queue
|
||||
}
|
||||
}
|
||||
close(jobs)
|
||||
workers.Wait()
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"sessions": rows, "has_more": hasMore, "next_cursor": nextCursor})
|
||||
}
|
||||
|
||||
func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
|
||||
if s.chat == nil || s.Manager == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 10<<20)
|
||||
if err := r.ParseMultipartForm(10 << 20); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "图片不能为空且不能超过 10MB")
|
||||
return
|
||||
}
|
||||
accountID := strings.TrimSpace(r.FormValue("account_id"))
|
||||
chatID := strings.TrimSpace(r.FormValue("chat_id"))
|
||||
buyerID := strings.TrimSpace(r.FormValue("buyer_id"))
|
||||
if !s.ownsAccount(r, accountID) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
if chatID == "" || buyerID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "会话和买家不能为空")
|
||||
return
|
||||
}
|
||||
file, header, err := r.FormFile("image")
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请选择图片")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
contentType := header.Header.Get("Content-Type")
|
||||
if !strings.HasPrefix(strings.ToLower(contentType), "image/") {
|
||||
writeErr(w, http.StatusBadRequest, "只支持图片文件")
|
||||
return
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(file, (10<<20)+1))
|
||||
if err != nil || len(data) == 0 || len(data) > 10<<20 {
|
||||
writeErr(w, http.StatusBadRequest, "图片不能为空且不能超过 10MB")
|
||||
return
|
||||
}
|
||||
sender, ok := s.Manager.GetInstance(accountID)
|
||||
if !ok || sender == nil {
|
||||
writeErr(w, http.StatusConflict, "账号当前离线,无法发送图片")
|
||||
return
|
||||
}
|
||||
cookies, err := s.Store.Cookies.GetValue(r.Context(), accountID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取账号凭证失败")
|
||||
return
|
||||
}
|
||||
uploader, ok := s.mtopClient().(interface {
|
||||
UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error)
|
||||
})
|
||||
if !ok {
|
||||
writeErr(w, http.StatusServiceUnavailable, "图片上传服务未启用")
|
||||
return
|
||||
}
|
||||
upload, err := uploader.UploadChatImage(r.Context(), cookies, header.Filename, contentType, data)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadGateway, "图片上传到闲鱼失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
if upload.UpdatedCookies != "" && upload.UpdatedCookies != cookies {
|
||||
_ = s.Store.Cookies.UpdateValueExisting(r.Context(), accountID, upload.UpdatedCookies)
|
||||
sender.UpdateCookie(upload.UpdatedCookies)
|
||||
}
|
||||
session := db.ChatSession{CookieID: accountID, ChatID: chatID, BuyerID: buyerID,
|
||||
BuyerName: r.FormValue("buyer_name"), BuyerAvatar: r.FormValue("buyer_avatar_url"),
|
||||
ItemID: r.FormValue("item_id"), ItemTitle: r.FormValue("item_title")}
|
||||
message, err := s.chat.CreateOutgoingMedia(r.Context(), session, "image", upload.URL)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存待发送图片失败")
|
||||
return
|
||||
}
|
||||
if err := sender.SendImage(engine.WithOutgoingMessageKey(r.Context(), message.MessageKey), chatID, buyerID, upload.URL, 0); err != nil {
|
||||
failed, _ := s.chat.SetOutgoingStatus(context.Background(), accountID, message.MessageKey, "failed")
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{"message": failed, "error": "图片发送失败,请重试"})
|
||||
return
|
||||
}
|
||||
sent, err := s.chat.SetOutgoingStatus(r.Context(), accountID, message.MessageKey, "sent")
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "图片已发送,但状态保存失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"message": sent})
|
||||
}
|
||||
|
||||
func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
accountID := strings.TrimSpace(r.URL.Query().Get("account_id"))
|
||||
chatID := strings.TrimSpace(r.URL.Query().Get("chat_id"))
|
||||
if !s.ownsAccount(r, accountID) {
|
||||
writeErr(w, http.StatusForbidden, "无权访问该账号")
|
||||
return
|
||||
}
|
||||
if chatID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "缺少 chat_id")
|
||||
return
|
||||
}
|
||||
beforeID, _ := strconv.ParseInt(r.URL.Query().Get("before_id"), 10, 64)
|
||||
cursor, _ := strconv.ParseInt(r.URL.Query().Get("cursor"), 10, 64)
|
||||
limit := parsePositiveInt(r.URL.Query().Get("limit"), 50)
|
||||
if s.chat != nil && s.Manager != nil {
|
||||
if sender, ok := s.Manager.GetInstance(accountID); ok {
|
||||
if fetcher, ok := sender.(interface {
|
||||
FetchChatHistory(context.Context, string, int64, int) (map[string]any, string, error)
|
||||
}); ok {
|
||||
fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
body, myID, fetchErr := fetcher.FetchChatHistory(fetchCtx, chatID, cursor, limit)
|
||||
cancel()
|
||||
if fetchErr == nil {
|
||||
sessions, _ := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, 500)
|
||||
var current db.ChatSession
|
||||
for _, candidate := range sessions {
|
||||
if candidate.ChatID == chatID {
|
||||
current = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
page, saveErr := s.chat.RecordHistoryPage(r.Context(), accountID, chatID, myID, current, body)
|
||||
if saveErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存聊天历史失败")
|
||||
return
|
||||
}
|
||||
current = s.resolveSelectedChatIdentity(r.Context(), accountID, current)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"messages": page.Messages, "has_more": page.HasMore, "next_cursor": page.NextCursor, "session": current})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rows, err := s.Store.Chats.ListMessages(r.Context(), sess.UserID, accountID, chatID, beforeID,
|
||||
limit)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取聊天消息失败")
|
||||
return
|
||||
}
|
||||
var current db.ChatSession
|
||||
if sessions, sessionErr := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, 500); sessionErr == nil {
|
||||
for _, candidate := range sessions {
|
||||
if candidate.ChatID == chatID {
|
||||
current = s.resolveSelectedChatIdentity(r.Context(), accountID, candidate)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"messages": rows, "has_more": len(rows) == limit, "session": current})
|
||||
}
|
||||
|
||||
func (s *Server) resolveSelectedChatIdentity(ctx context.Context, accountID string, session db.ChatSession) db.ChatSession {
|
||||
if session.BuyerID != "1400" {
|
||||
cookies, cookieErr := s.Store.Cookies.GetValue(ctx, accountID)
|
||||
client, supported := s.mtopClient().(interface {
|
||||
FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error)
|
||||
})
|
||||
if cookieErr == nil && supported {
|
||||
resolveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
info, err := client.FetchChatUserInfo(resolveCtx, cookies, session.ChatID)
|
||||
cancel()
|
||||
if err == nil && info != nil {
|
||||
if nickname := strings.TrimSpace(info.Nickname); nickname != "" {
|
||||
session.BuyerName = nickname
|
||||
}
|
||||
if info.AvatarURL != "" {
|
||||
session.BuyerAvatar = info.AvatarURL
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = s.Store.Chats.UpdateSessionIdentity(ctx, accountID, session.ChatID, session.BuyerID, session.BuyerName, session.BuyerAvatar)
|
||||
return session
|
||||
}
|
||||
|
||||
type sendChatMessageRequest struct {
|
||||
AccountID string `json:"account_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
BuyerID string `json:"buyer_id"`
|
||||
BuyerName string `json:"buyer_name"`
|
||||
ItemID string `json:"item_id"`
|
||||
ItemTitle string `json:"item_title"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
|
||||
if s.chat == nil || s.Manager == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
return
|
||||
}
|
||||
var input sendChatMessageRequest
|
||||
if err := decodeJSON(r, &input); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
input.AccountID, input.ChatID, input.BuyerID = strings.TrimSpace(input.AccountID), strings.TrimSpace(input.ChatID), strings.TrimSpace(input.BuyerID)
|
||||
input.Text = strings.TrimSpace(input.Text)
|
||||
if !s.ownsAccount(r, input.AccountID) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
if input.ChatID == "" || input.BuyerID == "" || input.Text == "" {
|
||||
writeErr(w, http.StatusBadRequest, "会话、买家和消息内容不能为空")
|
||||
return
|
||||
}
|
||||
if len([]rune(input.Text)) > 2000 {
|
||||
writeErr(w, http.StatusBadRequest, "消息不能超过 2000 个字符")
|
||||
return
|
||||
}
|
||||
sender, ok := s.Manager.GetInstance(input.AccountID)
|
||||
if !ok || sender == nil {
|
||||
writeErr(w, http.StatusConflict, "账号当前离线,无法发送消息")
|
||||
return
|
||||
}
|
||||
message, err := s.chat.CreateOutgoing(r.Context(), db.ChatSession{CookieID: input.AccountID, ChatID: input.ChatID,
|
||||
BuyerID: input.BuyerID, BuyerName: input.BuyerName, ItemID: input.ItemID, ItemTitle: input.ItemTitle}, input.Text)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存待发送消息失败")
|
||||
return
|
||||
}
|
||||
sendContext := engine.WithOutgoingMessageKey(r.Context(), message.MessageKey)
|
||||
if err := sender.SendText(sendContext, input.ChatID, input.BuyerID, input.Text); err != nil {
|
||||
failed, _ := s.chat.SetOutgoingStatus(context.Background(), input.AccountID, message.MessageKey, "failed")
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{"message": failed, "error": "发送失败,请重试"})
|
||||
return
|
||||
}
|
||||
sent, err := s.chat.SetOutgoingStatus(r.Context(), input.AccountID, message.MessageKey, "sent")
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "消息已发送,但状态保存失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"message": sent})
|
||||
}
|
||||
|
||||
func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
AccountID string `json:"account_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
}
|
||||
if decodeJSON(r, &input) != nil || input.ChatID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if !s.ownsAccount(r, input.AccountID) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if err := s.Store.Chats.MarkRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新已读状态失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
if s.chat == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
return
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
events, unsubscribe, err := s.chat.Subscribe(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "订阅聊天消息失败")
|
||||
return
|
||||
}
|
||||
defer unsubscribe()
|
||||
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionContextTakeover})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()
|
||||
ctx, cancel := context.WithCancel(r.Context())
|
||||
defer cancel()
|
||||
conn.SetReadLimit(8 << 10)
|
||||
go func() {
|
||||
for {
|
||||
if _, _, readErr := conn.Read(ctx); readErr != nil {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
if err := wsjson.Write(ctx, conn, map[string]any{"type": "ready", "at": time.Now().UTC().UnixMilli()}); err != nil {
|
||||
return
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case event, ok := <-events:
|
||||
if !ok || wsjson.Write(ctx, conn, event) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) ownsAccount(r *http.Request, accountID string) bool {
|
||||
if accountID == "" {
|
||||
return false
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
accounts, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
_, ok := accounts[accountID]
|
||||
return ok
|
||||
}
|
||||
|
||||
func parsePositiveInt(raw string, fallback int) int {
|
||||
value, err := strconv.Atoi(raw)
|
||||
if err != nil || value <= 0 {
|
||||
return fallback
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -381,23 +381,31 @@ func (s *Server) listCookieDetails(w http.ResponseWriter, r *http.Request) {
|
||||
if err != nil || d == nil {
|
||||
continue
|
||||
}
|
||||
tasks, _ := s.Store.AccountTasks.Get(r.Context(), cid)
|
||||
result = append(result, map[string]any{
|
||||
"id": d.ID,
|
||||
"has_cookie": true,
|
||||
"enabled": s.Store.Cookies.GetStatus(r.Context(), cid),
|
||||
"auto_confirm": d.AutoConfirm,
|
||||
"remark": d.Remark,
|
||||
"pause_duration": d.PauseDuration,
|
||||
"paused_until": d.PausedUntil,
|
||||
"paused": d.PausedUntil > time.Now().UTC().Unix(),
|
||||
"show_browser": d.ShowBrowser,
|
||||
"username": d.Username,
|
||||
"nickname": cachedAccountNickname(d),
|
||||
"avatar_url": d.AvatarURL,
|
||||
"login_method": d.LoginMethod,
|
||||
"last_login_at": d.LastLoginAt,
|
||||
"profile_error": "",
|
||||
"ai_enabled": false,
|
||||
"id": d.ID,
|
||||
"has_cookie": true,
|
||||
"enabled": s.Store.Cookies.GetStatus(r.Context(), cid),
|
||||
"auto_confirm": d.AutoConfirm,
|
||||
"remark": d.Remark,
|
||||
"pause_duration": d.PauseDuration,
|
||||
"paused_until": d.PausedUntil,
|
||||
"paused": d.PausedUntil > time.Now().UTC().Unix(),
|
||||
"show_browser": d.ShowBrowser,
|
||||
"username": d.Username,
|
||||
"nickname": cachedAccountNickname(d),
|
||||
"avatar_url": d.AvatarURL,
|
||||
"login_method": d.LoginMethod,
|
||||
"last_login_at": d.LastLoginAt,
|
||||
"profile_error": "",
|
||||
"ai_enabled": false,
|
||||
"auto_rate_enabled": tasks.AutoRateEnabled,
|
||||
"rate_content": tasks.RateContent,
|
||||
"auto_polish_enabled": tasks.AutoPolishEnabled,
|
||||
"polish_time": tasks.PolishTime,
|
||||
"last_rate_scan_at": tasks.LastRateScanAt,
|
||||
"last_polish_date": tasks.LastPolishDate,
|
||||
"last_polish_at": tasks.LastPolishAt,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
@@ -417,22 +425,30 @@ func (s *Server) getCookieDetails(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusNotFound, "账号不存在")
|
||||
return
|
||||
}
|
||||
tasks, _ := s.Store.AccountTasks.Get(r.Context(), cid)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"id": d.ID,
|
||||
"enabled": s.Store.Cookies.GetStatus(r.Context(), cid),
|
||||
"auto_confirm": d.AutoConfirm,
|
||||
"remark": d.Remark,
|
||||
"pause_duration": d.PauseDuration,
|
||||
"paused_until": d.PausedUntil,
|
||||
"paused": d.PausedUntil > time.Now().UTC().Unix(),
|
||||
"show_browser": d.ShowBrowser,
|
||||
"username": d.Username,
|
||||
"nickname": cachedAccountNickname(d),
|
||||
"avatar_url": d.AvatarURL,
|
||||
"login_method": d.LoginMethod,
|
||||
"last_login_at": d.LastLoginAt,
|
||||
"profile_error": "",
|
||||
"has_cookie": true,
|
||||
"id": d.ID,
|
||||
"enabled": s.Store.Cookies.GetStatus(r.Context(), cid),
|
||||
"auto_confirm": d.AutoConfirm,
|
||||
"remark": d.Remark,
|
||||
"pause_duration": d.PauseDuration,
|
||||
"paused_until": d.PausedUntil,
|
||||
"paused": d.PausedUntil > time.Now().UTC().Unix(),
|
||||
"show_browser": d.ShowBrowser,
|
||||
"username": d.Username,
|
||||
"nickname": cachedAccountNickname(d),
|
||||
"avatar_url": d.AvatarURL,
|
||||
"login_method": d.LoginMethod,
|
||||
"last_login_at": d.LastLoginAt,
|
||||
"profile_error": "",
|
||||
"has_cookie": true,
|
||||
"auto_rate_enabled": tasks.AutoRateEnabled,
|
||||
"rate_content": tasks.RateContent,
|
||||
"auto_polish_enabled": tasks.AutoPolishEnabled,
|
||||
"polish_time": tasks.PolishTime,
|
||||
"last_rate_scan_at": tasks.LastRateScanAt,
|
||||
"last_polish_date": tasks.LastPolishDate,
|
||||
"last_polish_at": tasks.LastPolishAt,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"xianyu-go/internal/account"
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/notify"
|
||||
"xianyu-go/internal/webui"
|
||||
@@ -60,6 +61,7 @@ type Server struct {
|
||||
Manager *account.Manager
|
||||
automation *automation.Center
|
||||
notifier *notify.Notifier
|
||||
chat *chat.Service
|
||||
MTop mtop.Client
|
||||
CookieRenew xrenew.Service
|
||||
QRLogin qrLoginService
|
||||
@@ -85,6 +87,9 @@ type Server struct {
|
||||
loginLimiter *loginFailureLimiter
|
||||
}
|
||||
|
||||
// SetChatService installs the shared chat persistence and live event hub.
|
||||
func (s *Server) SetChatService(service *chat.Service) { s.chat = service }
|
||||
|
||||
// New 构造。autoCenter/notifier 由调用方完成创建后注入(创建顺序:
|
||||
// adapter → manager → automation → notifier → server)。
|
||||
func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier) *Server {
|
||||
@@ -151,6 +156,9 @@ func (s *Server) Router() http.Handler {
|
||||
|
||||
// 账号 cookie
|
||||
s.mountCookies(r)
|
||||
s.mountAccountTasks(r)
|
||||
// 在线聊天(历史 REST + 应用层 WebSocket)
|
||||
s.mountChat(r)
|
||||
// 扫码登录
|
||||
s.mountQRLoginReal(r)
|
||||
// 密码登录
|
||||
|
||||
Reference in new issue
Block a user