推进P1聊天通知与凭证应用端口迁移

This commit is contained in:
Christ committed 2026-08-16 00:55:03 +08:00
1 parent 25531c05cb
commit 550aee8aae
17 files changed
+1677 -289

No files matched your search

+6 -1
View File
@@ -89,7 +89,12 @@ func (r storeAccountLoginRepository) LoadPlatformDetail(ctx context.Context, acc
if err != nil {
return nil, err
}
return &db.CookieDetail{ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser}, nil
// summary 只补充非敏感版本字段,避免为乐观冲突检查读取或解密登录密码。
summary, summaryErr := r.store.Cookies.GetSummaryOwned(ctx, data.UserID, accountID)
if summaryErr != nil {
return nil, summaryErr
}
return &db.CookieDetail{ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser, LastRefreshAt: summary.LastRefreshAt}, nil
}
// UpdateFlatCookieOwned 委托扁平 Cookie 更新并清除旧的完整 Cookie Jar 快照。
+40 -31
View File
@@ -36,7 +36,9 @@ func (p serverLoginLifecyclePort) AfterSuccessfulLogin(ctx context.Context, user
if p.server == nil {
return
}
p.server.markSuccessfulLogin(ctx, accountID, userID, method, "账号登录成功")
if strings.TrimSpace(method) != "" {
p.server.markSuccessfulLogin(ctx, accountID, userID, method, "账号登录成功")
}
p.server.accountLoginApplication().refreshAndRestartAccount(ctx, userID, accountID)
}
@@ -71,6 +73,36 @@ func (w serverCookieWriter) CreateOwnedCookie(ctx context.Context, accountID str
return nil
}
// UpdateOwnedCookie 在账号凭证短锁内完成归属复核、Cookie 写入和旧 Token 清理;慢速资料刷新由应用服务在解锁后触发。
func (w serverCookieWriter) UpdateOwnedCookie(ctx context.Context, accountID string, userID, expectedRevision int64) error {
if w.repository == nil {
return errors.New("账号登录凭证 repository 未初始化")
}
// unlock 只保护凭证快照读取、数据库写入和旧 Token 清理,不跨越网络或运行时操作。
unlock := w.repository.LockCredentials(accountID)
defer unlock()
// detail 保存锁内读取的平台凭证窄视图;该视图不会把登录密码传入应用层。
detail, loadErr := w.repository.LoadPlatformDetail(ctx, accountID)
if loadErr != nil {
return loadErr
}
if detail == nil || detail.UserID != userID {
return db.ErrForbidden
}
if expectedRevision != 0 && detail.LastRefreshAt != expectedRevision {
return accountapp.ErrCredentialConflict
}
// updateErr 保存归属已确认后的 Cookie 持久化结果;适配器负责清除旧完整快照。
if updateErr := w.repository.UpdateFlatCookieOwned(ctx, detail, w.cookies); updateErr != nil {
return updateErr
}
// clearErr 保存旧连接 Token 清理错误;凭证已成功写入时清理失败仅记录并继续。
if clearErr := w.repository.ClearTokens(ctx, accountID); clearErr != nil && w.logger != nil {
w.logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", accountID, "err", clearErr)
}
return nil
}
// newAccountLoginCreateApplication 构造手动 Cookie 登录应用服务及其 Server 生命周期适配器。
func newAccountLoginCreateApplication(server *Server) (*accountapp.LoginService, error) {
return accountapp.NewLoginService(serverLoginLifecyclePort{server: server})
@@ -144,6 +176,8 @@ type accountCookieUpdateInput struct {
UserID int64
// LoginMethod 是可选的登录方式。
LoginMethod string
// ExpectedRevision 是客户端读取到的最近 Cookie 刷新时间,用于检测并发覆盖。
ExpectedRevision int64
}
// CreateCookie 创建账号凭证并完成登录审计、资料刷新和运行时重启。
@@ -158,37 +192,12 @@ func (svc *accountLoginService) CreateCookie(ctx context.Context, input accountL
// UpdateCookie 更新账号凭证并完成登录审计、资料刷新和运行时重启。
func (svc *accountLoginService) UpdateCookie(ctx context.Context, input accountCookieUpdateInput) error {
// s 是当前账号登录应用服务依赖的 Server。
s := svc.server
// unlock 保护账号凭证更新、连接凭证清理和登录审计。
unlock := svc.repository.LockCredentials(input.AccountID)
// detail 和 err 保存账号凭证详情查询结果。
detail, err := s.loadCookiePlatformDetail(ctx, input.AccountID)
if err != nil || detail == nil || detail.UserID != input.UserID {
unlock()
if err == nil {
return db.ErrNotFound
}
return err
if svc == nil || svc.createApplication == nil || svc.server == nil {
return errors.New("账号登录应用服务未初始化")
}
// err 表示扁平 Cookie 更新错误。
if err := svc.repository.UpdateFlatCookieOwned(ctx, detail, input.Cookies); err != nil {
unlock()
return err
}
{
// err 表示清理旧连接凭证的错误,仅记录不阻断登录。
if err := svc.repository.ClearTokens(ctx, input.AccountID); err != nil && s.Logger != nil {
s.Logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", input.AccountID, "err", err)
}
}
// loginMethod 是可选的归一化登录方式。
if loginMethod := normalizeLoginMethod(input.LoginMethod); loginMethod != "" {
s.markSuccessfulLogin(ctx, input.AccountID, input.UserID, loginMethod, "账号登录成功")
}
unlock()
svc.refreshAndRestartAccount(ctx, input.UserID, input.AccountID)
return nil
return svc.createApplication.UpdateCookie(ctx, accountapp.UpdateCookieInput{
AccountID: input.AccountID, UserID: input.UserID, LoginMethod: input.LoginMethod, ExpectedRevision: input.ExpectedRevision,
}, serverCookieWriter{repository: svc.repository, cookies: input.Cookies, logger: svc.server.Logger})
}
// serverQRLoginLifecycle 将扫码登录成功后的审计、资料刷新和运行时同步适配到应用端口。
+4 -1
View File
@@ -28,6 +28,8 @@ type applicationServices struct {
chat *chatapp.Service
// uncertainNotifications 是通知不确定状态运维查询应用服务。
uncertainNotifications *notificationsapp.Service
// notificationChannels 是通知渠道 CRUD 与账号绑定应用服务。
notificationChannels *notificationsapp.ChannelService
// analytics 是订单分析应用服务。
analytics *analyticsService
}
@@ -73,8 +75,9 @@ func newApplicationServices(server *Server) *applicationServices {
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store), createApplication: accountLoginCreate, qrApplication: accountQRLogin},
accountProfile: accountProfile,
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
chat: chatapp.New(newStoreChatApplicationRepository(server.Store)),
chat: newChatSendingApplication(server),
uncertainNotifications: notificationsapp.New(newStoreNotificationUncertainRepository(server.Store)),
notificationChannels: notificationsapp.NewChannelService(newStoreNotificationChannelRepository(server.Store), server.notifier),
analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)},
}
}
+15 -15
View File
@@ -281,27 +281,27 @@ func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "图片不能为空且不能超过 10MB")
return
}
// session 保存会话,供当前处理流程使用
session := db.ChatSession{CookieID: accountID, ChatID: chatID, BuyerID: buyerID,
// session 保存已完成账号归属校验的应用层会话摘要。
session := chatapp.Session{AccountID: 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")}
// sent、err 保存sent、err,供当前处理流程使用
sent, err := s.communicationApplication().SendChatImage(r.Context(), chatImageInput{Session: session, Filename: header.Filename, ContentType: contentType, Data: data})
sent, err := s.chatApplication().SendImage(r.Context(), chatapp.ImageInput{Session: session, Filename: header.Filename, ContentType: contentType, Data: data})
if err != nil {
if errors.Is(err, errCommunicationUnavailable) {
if errors.Is(err, chatapp.ErrUnavailable) {
writeErr(w, http.StatusServiceUnavailable, "图片上传服务未启用")
} else if errors.Is(err, errChatOffline) {
} else if errors.Is(err, chatapp.ErrOffline) {
writeErr(w, http.StatusConflict, "账号当前离线,无法发送图片")
} else if errors.Is(err, errChatSend) {
} else if errors.Is(err, chatapp.ErrSend) {
writeErrDetails(w, http.StatusBadGateway, "chat_image_send_failed", "图片发送失败,请重试", "", map[string]any{"outgoing_message": sent})
} else if errors.Is(err, errChatStatusSave) {
} else if errors.Is(err, chatapp.ErrStatusSave) {
writeErr(w, http.StatusInternalServerError, "图片已发送,但状态保存失败")
} else {
writeErr(w, http.StatusInternalServerError, "保存待发送图片失败")
}
return
}
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromPointer(sent)})
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromApplication(sent)})
}
// listChatMessages 负责list聊天消息列表相关处理。
@@ -447,23 +447,23 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "消息不能超过 2000 个字符")
return
}
// sent、err 保存sent、err,供当前处理流程使用
sent, err := s.communicationApplication().SendChatText(r.Context(), chatTextInput{Session: db.ChatSession{CookieID: input.AccountID, ChatID: input.ChatID, BuyerID: input.BuyerID, BuyerName: input.BuyerName, ItemID: input.ItemID, ItemTitle: input.ItemTitle}, Text: input.Text})
// sent、err 保存应用层发送结果及错误;应用层返回的消息不含凭证。
sent, err := s.chatApplication().SendText(r.Context(), chatapp.OutgoingInput{Session: chatapp.Session{AccountID: input.AccountID, ChatID: input.ChatID, BuyerID: input.BuyerID, BuyerName: input.BuyerName, ItemID: input.ItemID, ItemTitle: input.ItemTitle}, Text: input.Text})
if err != nil {
if errors.Is(err, errCommunicationUnavailable) {
if errors.Is(err, chatapp.ErrUnavailable) {
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
} else if errors.Is(err, errChatOffline) {
} else if errors.Is(err, chatapp.ErrOffline) {
writeErr(w, http.StatusConflict, "账号当前离线,无法发送消息")
} else if errors.Is(err, errChatSend) {
} else if errors.Is(err, chatapp.ErrSend) {
writeErrDetails(w, http.StatusBadGateway, "chat_message_send_failed", "发送失败,请重试", "", map[string]any{"outgoing_message": sent})
} else if errors.Is(err, errChatStatusSave) {
} else if errors.Is(err, chatapp.ErrStatusSave) {
writeErr(w, http.StatusInternalServerError, "消息已发送,但状态保存失败")
} else {
writeErr(w, http.StatusInternalServerError, "保存待发送消息失败")
}
return
}
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromPointer(sent)})
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromApplication(sent)})
}
// markChatRead 负责mark聊天Read相关处理。
+189 -111
View File
@@ -3,10 +3,12 @@ package server
import (
"context"
"errors"
"fmt"
"strings"
"xianyu-go/internal/account"
chatapp "xianyu-go/internal/application/chat"
"xianyu-go/internal/automation"
domainchat "xianyu-go/internal/chat"
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
"xianyu-go/internal/xianyu/mtop"
@@ -15,12 +17,6 @@ import (
var (
// errCommunicationUnavailable 表示聊天或自动化依赖尚未初始化。
errCommunicationUnavailable = errors.New("通信服务未启用")
// errChatOffline 表示目标账号当前没有在线运行实例。
errChatOffline = errors.New("账号当前离线")
// errChatSend 表示远端聊天消息发送失败。
errChatSend = errors.New("聊天消息发送失败")
// errChatStatusSave 表示远端消息已发送但本地状态保存失败。
errChatStatusSave = errors.New("聊天发送状态保存失败")
)
// communicationService 是聊天、账号任务和通知应用服务。
@@ -39,26 +35,6 @@ type accountTaskUpdateInput struct {
Settings db.AccountTaskSettings
}
// chatTextInput 是发送文字消息的业务输入。
type chatTextInput struct {
// Session 是聊天会话及买家信息。
Session db.ChatSession
// Text 是待发送的文字内容。
Text string
}
// chatImageInput 是发送图片消息的业务输入。
type chatImageInput struct {
// Session 是聊天会话及买家信息。
Session db.ChatSession
// Filename 是上传图片文件名。
Filename string
// ContentType 是图片 MIME 类型。
ContentType string
// Data 是图片二进制内容。
Data []byte
}
// notificationBindingRow 是通知绑定列表的一行业务数据。
type notificationBindingRow struct {
// ID 是绑定记录标识。
@@ -213,91 +189,193 @@ func (svc *communicationService) DeleteAccountNotificationBindings(ctx context.C
return svc.repository.DeleteAccountNotificationBindings(ctx, userID, cookieID)
}
// SendChatText 创建并发送一条文字消息,失败时保留可重试的本地失败状态。
func (svc *communicationService) SendChatText(ctx context.Context, input chatTextInput) (*db.ChatMessage, error) {
// s 是当前通信应用服务依赖的 Server。
s := svc.server
if s.chat == nil || s.Manager == nil {
return nil, errCommunicationUnavailable
}
// sender 保存目标账号的在线发送句柄。
sender, ok := s.Manager.GetInstance(input.Session.CookieID)
if !ok || sender == nil {
return nil, errChatOffline
}
// message 和 err 保存待发送消息落库结果。
message, err := s.chat.CreateOutgoing(ctx, input.Session, input.Text)
if err != nil {
return nil, fmt.Errorf("保存待发送消息失败: %w", err)
}
// err 表示文字发送错误。
if err := sender.SendText(engine.WithOutgoingMessageKey(ctx, message.MessageKey), input.Session.ChatID, input.Session.BuyerID, input.Text); err != nil {
// failed 保存发送失败后的本地消息状态。
failed, _ := s.chat.SetOutgoingStatus(context.Background(), input.Session.CookieID, message.MessageKey, "failed")
return failed, fmt.Errorf("%w: %v", errChatSend, err)
}
// sent 和 err 保存远端发送成功后的本地状态。
sent, err := s.chat.SetOutgoingStatus(ctx, input.Session.CookieID, message.MessageKey, "sent")
if err != nil {
return sent, fmt.Errorf("%w: %v", errChatStatusSave, err)
}
return sent, nil
}
// SendChatImage 上传并发送一条图片消息,失败时保留可重试的本地失败状态。
func (svc *communicationService) SendChatImage(ctx context.Context, input chatImageInput) (*db.ChatMessage, error) {
// s 是当前通信应用服务依赖的 Server。
s := svc.server
if s.chat == nil || s.Manager == nil {
return nil, errCommunicationUnavailable
}
// sender 和 ok 保存目标账号的在线发送句柄及存在性。
sender, ok := s.Manager.GetInstance(input.Session.CookieID)
if !ok || sender == nil {
return nil, errChatOffline
}
// cookies 和 err 保存图片上传使用的账号凭证。
cookies, err := svc.repository.GetCookieValue(ctx, input.Session.CookieID)
if err != nil {
return nil, fmt.Errorf("读取账号凭证失败: %w", err)
}
// uploader 和 ok 表示图片上传客户端及其能力支持情况。
uploader, ok := s.mtopClient().(interface {
UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error)
})
if !ok {
return nil, errCommunicationUnavailable
}
// upload 和 err 保存图片上传结果。
upload, err := uploader.UploadChatImage(ctx, cookies, input.Filename, input.ContentType, input.Data)
if err != nil {
return nil, fmt.Errorf("%w: %v", errChatSend, err)
}
if upload.UpdatedCookies != "" && upload.UpdatedCookies != cookies {
// err 表示保存图片上传后刷新 Cookie 的错误,仅忽略并继续发送。
_ = svc.repository.UpdateCookieValue(ctx, input.Session.CookieID, upload.UpdatedCookies)
sender.UpdateCookie(upload.UpdatedCookies)
}
// message 和 err 保存图片消息落库结果。
message, err := s.chat.CreateOutgoingMedia(ctx, input.Session, "image", upload.URL)
if err != nil {
return nil, fmt.Errorf("保存待发送图片失败: %w", err)
}
// err 表示图片发送错误。
if err := sender.SendImage(engine.WithOutgoingMessageKey(ctx, message.MessageKey), input.Session.ChatID, input.Session.BuyerID, upload.URL, 0); err != nil {
// failed 保存图片发送失败后的本地消息状态。
failed, _ := s.chat.SetOutgoingStatus(context.Background(), input.Session.CookieID, message.MessageKey, "failed")
return failed, fmt.Errorf("%w: %v", errChatSend, err)
}
// sent 和 err 保存图片发送成功后的本地状态。
sent, err := s.chat.SetOutgoingStatus(ctx, input.Session.CookieID, message.MessageKey, "sent")
if err != nil {
return sent, fmt.Errorf("%w: %v", errChatStatusSave, err)
}
return sent, nil
}
// MarkChatRead 将指定聊天会话标记为已读。
func (svc *communicationService) MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error {
return svc.repository.MarkChatRead(ctx, userID, accountID, chatID)
}
// storeChatOutgoingRepository 将领域聊天服务适配为实时发送应用端口。
type storeChatOutgoingRepository struct {
// service 保存聊天消息幂等写入和实时事件发布能力。
service *domainchat.Service
}
// CreateOutgoing 创建文字消息并转换为应用层非敏感模型。
func (r storeChatOutgoingRepository) CreateOutgoing(ctx context.Context, session chatapp.Session, text string) (chatapp.Message, error) {
if r.service == nil {
return chatapp.Message{}, chatapp.ErrUnavailable
}
// message、err 保存领域服务返回的消息及写入错误。
message, err := r.service.CreateOutgoing(ctx, dbChatSessionFromApplication(session), text)
return applicationChatMessage(message), err
}
// CreateOutgoingMedia 创建媒体消息并转换为应用层非敏感模型。
func (r storeChatOutgoingRepository) CreateOutgoingMedia(ctx context.Context, session chatapp.Session, messageType, content string) (chatapp.Message, error) {
if r.service == nil {
return chatapp.Message{}, chatapp.ErrUnavailable
}
// message、err 保存领域服务返回的媒体消息及写入错误。
message, err := r.service.CreateOutgoingMedia(ctx, dbChatSessionFromApplication(session), messageType, content)
return applicationChatMessage(message), err
}
// SetOutgoingStatus 更新外发消息状态并转换为应用层非敏感模型。
func (r storeChatOutgoingRepository) SetOutgoingStatus(ctx context.Context, accountID, key, status string) (chatapp.Message, error) {
if r.service == nil {
return chatapp.Message{}, chatapp.ErrUnavailable
}
// message、err 保存领域服务返回的状态消息及更新错误。
message, err := r.service.SetOutgoingStatus(ctx, accountID, key, status)
return applicationChatMessage(message), err
}
// managerChatSenderProvider 将账号管理器适配为聊天应用的在线发送端口。
type managerChatSenderProvider struct {
// manager 保存当前进程内的账号运行时管理器。
manager *account.Manager
}
// Sender 返回指定账号的在线发送能力。
func (p managerChatSenderProvider) Sender(accountID string) (chatapp.Sender, bool) {
if p.manager == nil {
return nil, false
}
// sender、ok 保存账号管理器返回的运行时发送器及存在性。
sender, ok := p.manager.GetInstance(accountID)
if !ok || sender == nil {
return nil, false
}
return managerChatSender{sender: sender}, true
}
// managerChatSender 将自动化消息发送接口收敛为应用聊天端口,并注入幂等键上下文。
type managerChatSender struct {
// sender 保存账号运行时提供的最小消息发送能力。
sender automation.MessageSender
}
// SendText 发送文字并将应用层幂等键传递给运行时旁路观察器。
func (s managerChatSender) SendText(ctx context.Context, chatID, toUserID, text, messageKey string) error {
return s.sender.SendText(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, text)
}
// SendImage 发送图片并将应用层幂等键传递给运行时接口。
func (s managerChatSender) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64, messageKey string) error {
return s.sender.SendImage(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, imageURL, cardID)
}
// storeChatCredentialRepository 将账号 Cookie 仓储适配为图片发送端口。
type storeChatCredentialRepository struct {
// store 保存数据库聚合入口,仅在凭证适配器内读取和更新 Cookie。
store *db.Store
}
// GetCookieValue 读取图片上传所需的账号凭证;调用方不得记录返回值。
func (r storeChatCredentialRepository) GetCookieValue(ctx context.Context, accountID string) (string, error) {
if r.store == nil || r.store.Cookies == nil {
return "", chatapp.ErrUnavailable
}
return r.store.Cookies.GetValue(ctx, accountID)
}
// UpdateCookieValue 保存图片上传后平台刷新的账号凭证。
func (r storeChatCredentialRepository) UpdateCookieValue(ctx context.Context, accountID, cookieValue string) error {
if r.store == nil || r.store.Cookies == nil {
return chatapp.ErrUnavailable
}
return r.store.Cookies.UpdateValueExisting(ctx, accountID, cookieValue)
}
// serverChatImageUploader 将 Server 当前 MTOP 客户端适配为图片上传端口。
type serverChatImageUploader struct {
// server 提供可动态替换的 MTOP 客户端,便于测试注入平台替身。
server *Server
// credentials 负责在平台刷新后持久化明文凭证,但不向应用层返回。
credentials storeChatCredentialRepository
// manager 负责将刷新后的凭证同步到在线运行时。
manager *account.Manager
}
// UploadChatImage 在适配器内部读取和刷新凭证,只向应用层返回图片地址。
func (u serverChatImageUploader) UploadChatImage(ctx context.Context, accountID, filename, contentType string, data []byte) (chatapp.ImageUpload, error) {
if u.server == nil {
return chatapp.ImageUpload{}, chatapp.ErrUnavailable
}
// cookieValue 和 err 保存平台调用所需的短暂明文凭证及读取错误,不得离开适配器。
cookieValue, err := u.credentials.GetCookieValue(ctx, accountID)
if err != nil {
return chatapp.ImageUpload{}, err
}
// uploader、ok 保存 MTOP 图片上传能力及接口支持情况。
uploader, ok := u.server.mtopClient().(interface {
UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error)
})
if !ok {
return chatapp.ImageUpload{}, chatapp.ErrUnavailable
}
// upload、err 保存图片平台返回结果及调用错误。
upload, err := uploader.UploadChatImage(ctx, cookieValue, filename, contentType, data)
if err != nil {
return chatapp.ImageUpload{}, err
}
if upload == nil {
return chatapp.ImageUpload{}, chatapp.ErrSend
}
if upload.UpdatedCookies != "" && upload.UpdatedCookies != cookieValue {
// persistErr 保存刷新凭证的持久化错误;该错误必须反馈给调用方,避免静默丢失会话状态。
if persistErr := u.credentials.UpdateCookieValue(ctx, accountID, upload.UpdatedCookies); persistErr != nil {
return chatapp.ImageUpload{}, persistErr
}
if u.manager != nil {
// sender、senderOK 保存刷新凭证同步到运行时的结果。
sender, senderOK := u.manager.GetInstance(accountID)
if senderOK && sender != nil {
sender.UpdateCookie(upload.UpdatedCookies)
}
}
}
return chatapp.ImageUpload{URL: upload.URL}, nil
}
// newChatSendingApplication 创建实时聊天发送应用服务及其 Server 适配器。
func newChatSendingApplication(server *Server) *chatapp.Service {
// domainService 保存聊天领域服务;空值表示发送能力未装配。
var domainService *domainchat.Service
if server != nil {
domainService = server.chat
}
// store 保存聊天适配器可用的数据库入口;空 Server 仍返回可安全调用的不可用服务。
var store *db.Store
// manager 保存账号运行时管理器;空值表示无法发送平台消息。
var manager *account.Manager
if server != nil {
store, manager = server.Store, server.Manager
}
return chatapp.NewWithSending(
newStoreChatApplicationRepository(store),
storeChatOutgoingRepository{service: domainService},
managerChatSenderProvider{manager: manager},
serverChatImageUploader{server: server, credentials: storeChatCredentialRepository{store: store}, manager: manager},
)
}
// applicationChatMessage 将数据库消息转换为应用层模型;空指针保持零值。
func applicationChatMessage(message *db.ChatMessage) chatapp.Message {
if message == nil {
return chatapp.Message{}
}
return chatapp.Message{
ID: message.ID, AccountID: message.CookieID, ChatID: message.ChatID, MessageKey: message.MessageKey,
Direction: message.Direction, SenderID: message.SenderID, SenderName: message.SenderName,
MessageType: message.MessageType, Content: message.Content, Status: message.Status, SentAt: message.SentAt,
}
}
// 确保各 Server 适配器覆盖聊天应用服务定义的最小端口。
var (
_ chatapp.OutgoingRepository = storeChatOutgoingRepository{}
_ chatapp.SenderProvider = managerChatSenderProvider{}
_ chatapp.Sender = managerChatSender{}
_ chatapp.ImageUploader = serverChatImageUploader{}
)
+17 -6
View File
@@ -554,6 +554,16 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, accountMutationResponse{Success: true, ID: req.ID})
}
// updateCookieRequest 是更新账号 Cookie 的 HTTP 请求 DTO;last_refresh_at 用于兼容客户端的并发覆盖检测。
type updateCookieRequest struct {
// Value 是本次请求携带的明文 Cookie;只在 Server 请求作用域内传递。
Value string `json:"value"`
// LoginMethod 是可选登录方式,用于成功审计和账号启用语义。
LoginMethod string `json:"login_method"`
// LastRefreshAt 是客户端读取到的最近凭证刷新时间;零值表示旧客户端不启用冲突检查。
LastRefreshAt int64 `json:"last_refresh_at"`
}
// updateCookie 更新 cookie 值。
func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
@@ -563,11 +573,8 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Value string `json:"value"`
LoginMethod string `json:"login_method"`
}
// req 保存请求中的 Cookie、登录方式和可选凭证版本。
var req updateCookieRequest
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
@@ -576,7 +583,11 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
err := s.accountLoginApplication().UpdateCookie(r.Context(), accountCookieUpdateInput{AccountID: cid, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil {
err := s.accountLoginApplication().UpdateCookie(r.Context(), accountCookieUpdateInput{AccountID: cid, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod, ExpectedRevision: req.LastRefreshAt}); err != nil {
if errors.Is(err, accountapp.ErrCredentialConflict) {
writeErr(w, http.StatusConflict, err.Error())
return
}
if errors.Is(err, db.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
+50
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
@@ -534,6 +535,55 @@ func TestUpdateCookie(t *testing.T) {
requireCookieSnapshotCleared(t, store, "acc1")
}
// TestUpdateCookieRejectsStaleRevision 验证客户端携带过期凭证版本时不会覆盖较新的 Cookie。
func TestUpdateCookieRejectsStaleRevision(t *testing.T) {
// srv、store、cleanup 保存测试服务器、数据库和资源释放函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存本次测试使用的数据库上下文。
ctx := context.Background()
// baselineValue 保存建立可比较版本所需的旧 Cookie 值。
baselineValue := "unb=baseline; _m_h5_tk=baseline_token;"
// baselineErr 表示写入可比较版本基线时的数据库错误。
if baselineErr := store.Cookies.UpdateRenewalCookie(ctx, "acc1", baselineValue, `{}`, 100); baselineErr != nil {
t.Fatalf("写入基线 Cookie 失败: %v", baselineErr)
}
// initialErr 保存读取初始账号详情时的错误。
initial, initialErr := store.Cookies.GetDetails(ctx, "acc1")
if initialErr != nil {
t.Fatalf("读取初始账号详情失败: %v", initialErr)
}
// newerValue 是并发请求已经写入的新 Cookie 值。
newerValue := "unb=latest; _m_h5_tk=latest_token;"
// updateErr 表示写入并发新 Cookie 时的数据库错误。
if updateErr := store.Cookies.UpdateRenewalCookie(ctx, "acc1", newerValue, initial.MetadataJSON, 200); updateErr != nil {
t.Fatalf("写入并发新 Cookie 失败: %v", updateErr)
}
// h 保存 HTTP 路由;session 保存当前用户的会话 Cookie。
h := srv.Router()
// session 保存当前用户登录后的 HttpOnly 会话 Cookie。
session := loginHelper(t, h)
// body 保存携带旧版本的更新请求体。
body := fmt.Sprintf(`{"value":"unb=stale; _m_h5_tk=stale_token;","last_refresh_at":%d}`, initial.LastRefreshAt)
// req、rec 保存 HTTP 请求与响应记录器。
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1", strings.NewReader(body))
req.AddCookie(session)
// rec 记录过期版本请求的 HTTP 响应,供状态码与错误契约断言。
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("过期版本应返回 409,got %d body=%s", rec.Code, rec.Body.String())
}
// latest、latestErr 保存冲突后数据库中的凭证值和读取错误。
latest, latestErr := store.Cookies.GetDetails(ctx, "acc1")
if latestErr != nil {
t.Fatalf("读取冲突后账号详情失败: %v", latestErr)
}
if latest.Value != newerValue {
t.Fatalf("过期版本覆盖了新 Cookie: %q", latest.Value)
}
}
// TestUpdateRunningCookieWakesCredentialBlockedAutomationWithoutManager 负责TestUpdateRunning登录凭证WakesCredentialBlocked自动化WithoutManager相关处理。
func TestUpdateRunningCookieWakesCredentialBlockedAutomationWithoutManager(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
+256 -116
View File
@@ -13,6 +13,176 @@ import (
"xianyu-go/internal/db"
)
// notificationChannelCreateRequest 是创建通知渠道的具名 HTTP 请求 DTO;Config 只写入应用端口。
type notificationChannelCreateRequest struct {
// Name 是渠道名称。
Name string `json:"name"`
// Type 是渠道协议类型。
Type string `json:"type"`
// Config 是渠道敏感配置 JSON,禁止进入响应或日志。
Config string `json:"config"`
// EventTypes 是渠道订阅事件类型编码。
EventTypes string `json:"event_types"`
// Enabled 表示渠道是否启用。
Enabled bool `json:"enabled"`
}
// notificationChannelPatchRequest 是更新通知渠道的具名部分更新 DTO。
type notificationChannelPatchRequest struct {
// Name 是可选的新渠道名称。
Name *string `json:"name"`
// Type 是可选的新渠道协议类型。
Type *string `json:"type"`
// Config 是可选的新敏感配置 JSON,禁止进入响应或日志。
Config *string `json:"config"`
// EventTypes 是可选的新订阅事件类型编码。
EventTypes *string `json:"event_types"`
// Enabled 是可选的新启用状态。
Enabled *bool `json:"enabled"`
}
// notificationBindingRequest 是账号通知绑定更新的具名 HTTP 请求 DTO。
type notificationBindingRequest struct {
// ChannelIDs 是覆盖式保存的渠道 ID 列表。
ChannelIDs []int64 `json:"channel_ids"`
// ChannelID 是单条绑定更新的渠道 ID。
ChannelID int64 `json:"channel_id"`
// Enabled 是单条绑定是否启用;省略时默认为启用。
Enabled *bool `json:"enabled"`
}
// storeNotificationChannelRepository 将通知数据库能力适配为通知应用端口。
type storeNotificationChannelRepository struct {
// store 保存数据库聚合入口,仅在 Server 基础设施适配器内使用。
store *db.Store
}
// ListChannels 查询渠道摘要并丢弃配置,避免敏感配置进入应用展示模型。
func (r storeNotificationChannelRepository) ListChannels(ctx context.Context, userID int64) ([]notificationsapp.ChannelSummary, error) {
// rows、err 保存数据库渠道读取结果;Config 仅在适配器内部被解密读取。
rows, err := r.store.Notifications.AllChannelsForUser(ctx, userID)
if err != nil {
return nil, err
}
// summaries 保存不含渠道配置的应用摘要。
summaries := make([]notificationsapp.ChannelSummary, 0, len(rows))
// row 表示当前待转换的数据库渠道行。
for _, row := range rows {
summaries = append(summaries, notificationsapp.ChannelSummary{ID: row.ID, Name: row.Name, Type: row.Type, EventTypes: row.EventTypes, Enabled: row.Enabled, UserID: row.UserID})
}
return summaries, nil
}
// GetChannelForUpdate 查询归属渠道的完整记录,仅供应用层合并部分更新。
func (r storeNotificationChannelRepository) GetChannelForUpdate(ctx context.Context, channelID, userID int64) (*notificationsapp.ChannelRecord, error) {
// row、err 保存带用户归属的数据库渠道记录。
row, err := r.store.Notifications.GetChannelRowForUser(ctx, channelID, userID)
if err != nil {
return nil, err
}
if row == nil {
return nil, nil
}
return &notificationsapp.ChannelRecord{ID: row.ID, Name: row.Name, Type: row.Type, Config: row.Config, EventTypes: row.EventTypes, Enabled: row.Enabled, UserID: row.UserID}, nil
}
// CreateChannel 将应用输入转换为数据库行并创建渠道。
func (r storeNotificationChannelRepository) CreateChannel(ctx context.Context, userID int64, input notificationsapp.ChannelInput) (int64, error) {
// row 保存待加密写入数据库的渠道行;Config 不向 HTTP 返回。
row := db.NotificationChannelRow{Name: input.Name, Type: input.Type, Config: input.Config, EventTypes: input.EventTypes, Enabled: input.Enabled, UserID: userID}
return r.store.Notifications.CreateChannel(ctx, &row)
}
// UpdateChannel 将应用层完整渠道记录转换为数据库更新。
func (r storeNotificationChannelRepository) UpdateChannel(ctx context.Context, userID int64, record notificationsapp.ChannelRecord) error {
// row 保存待加密写入数据库的渠道行;调用方已完成归属和字段校验。
row := db.NotificationChannelRow{ID: record.ID, Name: record.Name, Type: record.Type, Config: record.Config, EventTypes: record.EventTypes, Enabled: record.Enabled, UserID: userID}
return r.store.Notifications.UpdateChannelForUser(ctx, &row, userID)
}
// DeleteChannel 删除用户拥有的渠道并统一转换不存在错误。
func (r storeNotificationChannelRepository) DeleteChannel(ctx context.Context, channelID, userID int64) error {
return normalizeNotificationRepositoryError(r.store.Notifications.DeleteChannelForUser(ctx, channelID, userID))
}
// OwnsChannel 查询通知渠道归属,不读取配置内容。
func (r storeNotificationChannelRepository) OwnsChannel(ctx context.Context, channelID, userID int64) (bool, error) {
return r.store.Notifications.OwnsChannel(ctx, channelID, userID)
}
// OwnsAccount 查询账号归属,不读取或解密 Cookie。
func (r storeNotificationChannelRepository) OwnsAccount(ctx context.Context, userID int64, cookieID string) (bool, error) {
return r.store.Cookies.ExistsOwned(ctx, userID, cookieID)
}
// ListBindings 查询绑定摘要并转换为应用模型。
func (r storeNotificationChannelRepository) ListBindings(ctx context.Context, userID int64) ([]notificationsapp.BindingSummary, error) {
// rows、err 保存数据库绑定摘要及错误。
rows, err := r.store.Notifications.ListBindingsForUser(ctx, userID)
if err != nil {
return nil, err
}
// bindings 保存不含配置的应用绑定摘要。
bindings := make([]notificationsapp.BindingSummary, 0, len(rows))
// row 表示当前待转换的数据库绑定行。
for _, row := range rows {
bindings = append(bindings, notificationsapp.BindingSummary{ID: row.ID, CookieID: row.CookieID, ChannelID: row.ChannelID, ChannelName: row.ChannelName, Enabled: row.Enabled})
}
return bindings, nil
}
// GetBindingIDs 查询账号启用的通知渠道 ID。
func (r storeNotificationChannelRepository) GetBindingIDs(ctx context.Context, cookieID string) ([]int64, error) {
return r.store.Notifications.AccountBindings(ctx, cookieID)
}
// SetBindings 覆盖保存账号绑定,并保留数据库事务和跨归属校验。
func (r storeNotificationChannelRepository) SetBindings(ctx context.Context, cookieID string, channelIDs []int64) error {
return normalizeNotificationRepositoryError(r.store.Notifications.SetBindings(ctx, cookieID, channelIDs))
}
// SetSingleBinding 更新单个账号绑定状态。
func (r storeNotificationChannelRepository) SetSingleBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error {
return r.store.Notifications.SetSingleBinding(ctx, cookieID, channelID, enabled)
}
// DeleteBinding 删除用户的一条绑定。
func (r storeNotificationChannelRepository) DeleteBinding(ctx context.Context, userID, bindingID int64) error {
return r.store.Notifications.DeleteBinding(ctx, userID, bindingID)
}
// DeleteAccountBindings 删除用户账号的全部绑定。
func (r storeNotificationChannelRepository) DeleteAccountBindings(ctx context.Context, userID int64, cookieID string) error {
return r.store.Notifications.DeleteAccountBindings(ctx, userID, cookieID)
}
// normalizeNotificationRepositoryError 将数据库归属错误转换为应用错误,隐藏基础设施类型。
func normalizeNotificationRepositoryError(err error) error {
if errors.Is(err, db.ErrNotFound) {
return notificationsapp.ErrChannelNotFound
}
if errors.Is(err, db.ErrForbidden) {
return notificationsapp.ErrChannelForbidden
}
return err
}
// newStoreNotificationChannelRepository 构造通知渠道应用端口适配器。
func newStoreNotificationChannelRepository(store *db.Store) notificationsapp.ChannelRepository {
if store == nil || store.Notifications == nil || store.Cookies == nil {
return nil
}
return storeNotificationChannelRepository{store: store}
}
// notificationChannelsApplication 返回当前 Server 绑定的通知渠道应用服务。
func (s *Server) notificationChannelsApplication() *notificationsapp.ChannelService {
return s.applicationServiceSet().notificationChannels
}
// ensureStoreNotificationChannelRepository 保证通知渠道应用端口覆盖全部能力。
var _ notificationsapp.ChannelRepository = storeNotificationChannelRepository{}
// storeNotificationUncertainRepository 将数据库通知摘要查询适配为应用层端口。
type storeNotificationUncertainRepository struct {
// store 保存数据库聚合入口,仅在脱敏摘要适配器内使用。
@@ -124,10 +294,10 @@ func (s *Server) listAdminUncertainNotifications(w http.ResponseWriter, r *http.
// listChannels 负责list渠道列表相关处理。
func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
// chs、err 保存chs、err,供当前处理流程使用
chs, err := s.communicationApplication().ListNotificationChannels(r.Context(), sess.UserID)
// chs、err 保存通知渠道非敏感摘要及查询错误。
chs, err := s.notificationChannelsApplication().ListChannels(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
@@ -137,24 +307,18 @@ func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
// createChannel 负责create渠道相关处理。
func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
// req 保存req,供当前处理流程使用
var req struct {
Name string `json:"name"`
Type string `json:"type"`
Config string `json:"config"`
EventTypes string `json:"event_types"`
Enabled bool `json:"enabled"`
}
if // err 保存err,供当前处理流程使用
// req 保存具名通知渠道创建请求;Config 只写入应用端口。
var req notificationChannelCreateRequest
if // err 保存 JSON 解码错误。
err := decodeJSON(r, &req); err != nil || req.Name == "" || req.Type == "" {
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
return
}
// id、err 保存id、err,供当前处理流程使用
id, err := s.communicationApplication().CreateNotificationChannel(r.Context(), db.NotificationChannelRow{
Name: req.Name, Type: req.Type, Config: req.Config, EventTypes: req.EventTypes, Enabled: req.Enabled, UserID: sess.UserID,
// id、err 保存渠道创建结果及应用错误。
id, err := s.notificationChannelsApplication().CreateChannel(r.Context(), sess.UserID, notificationsapp.ChannelInput{
Name: req.Name, Type: req.Type, Config: req.Config, EventTypes: req.EventTypes, Enabled: req.Enabled,
})
if err != nil {
writeErr(w, http.StatusInternalServerError, "创建失败")
@@ -165,59 +329,30 @@ func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
// updateChannel 负责update渠道相关处理。
func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
// id、err 保存路径中的渠道 ID 及解析错误。
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效ID")
return
}
// req 保存req,供当前处理流程使用
var req struct {
Name *string `json:"name"`
Type *string `json:"type"`
Config *string `json:"config"`
EventTypes *string `json:"event_types"`
Enabled *bool `json:"enabled"`
}
if // err 保存err,供当前处理流程使用
// req 保存具名通知渠道部分更新请求;Config 不会进入响应。
var req notificationChannelPatchRequest
if // err 保存 JSON 解码错误。
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 保存sess,供当前处理流程使用
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
// row、err 保存row、err,供当前处理流程使用
row, err := s.communicationApplication().GetNotificationChannel(r.Context(), id, sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
if row == nil {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return
}
if req.Name != nil {
row.Name = *req.Name
}
if req.Type != nil {
row.Type = *req.Type
}
if req.Config != nil {
row.Config = *req.Config
}
if req.EventTypes != nil {
row.EventTypes = *req.EventTypes
}
if req.Enabled != nil {
row.Enabled = *req.Enabled
}
if row.Name == "" || row.Type == "" {
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
return
}
if // err 保存err,供当前处理流程使用
err := s.communicationApplication().UpdateNotificationChannel(r.Context(), *row, sess.UserID); err != nil {
if errors.Is(err, db.ErrNotFound) {
// err 保存应用层部分更新结果。
if err := s.notificationChannelsApplication().UpdateChannel(r.Context(), sess.UserID, id, notificationsapp.ChannelPatch{
Name: req.Name, Type: req.Type, Config: req.Config, EventTypes: req.EventTypes, Enabled: req.Enabled,
}); err != nil {
if errors.Is(err, notificationsapp.ErrChannelInvalidInput) {
writeErr(w, http.StatusBadRequest, "name 和 type 必填")
return
}
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) || errors.Is(err, db.ErrNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return
}
@@ -229,17 +364,17 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
// deleteChannel 负责delete渠道相关处理。
func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
// id、err 保存路径中的渠道 ID 及解析错误。
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效ID")
return
}
// sess 保存sess,供当前处理流程使用
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
if // err 保存err,供当前处理流程使用
err := s.communicationApplication().DeleteNotificationChannel(r.Context(), id, sess.UserID); err != nil {
if errors.Is(err, db.ErrNotFound) {
// err 保存应用层删除结果。
if err := s.notificationChannelsApplication().DeleteChannel(r.Context(), sess.UserID, id); err != nil {
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) || errors.Is(err, db.ErrNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return
}
@@ -251,28 +386,27 @@ func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
// testChannel 向指定渠道发送一条测试通知,便于用户验证配置是否正确。
func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
// id、err 保存id、err,供当前处理流程使用
// id、err 保存路径中的渠道 ID 及解析错误。
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效ID")
return
}
// notifier 表示当前 Server 是否装配了实际通知发送器;未装配时保持旧接口的 503 语义,避免先执行归属查询。
if s.notifier == nil {
writeErr(w, http.StatusServiceUnavailable, "通知器未启用")
return
}
if !s.requireChannelOwner(w, r, id) {
return
}
// body 保存请求体,供当前处理流程使用
body := "🧪 通知渠道测试\n\n这是一条来自Ydisks闲鱼助手的测试通知,收到说明渠道配置正常。\n时间: " +
time.Now().Format("2006-01-02 15:04:05")
if // err 保存err,供当前处理流程使用
err := s.communicationApplication().TestNotificationChannel(r.Context(), id, authSess(r).UserID, body); err != nil {
if errors.Is(err, errCommunicationUnavailable) {
// err 保存应用层测试发送结果。
if err := s.notificationChannelsApplication().TestChannel(r.Context(), authSess(r).UserID, id, time.Now()); err != nil {
if errors.Is(err, notificationsapp.ErrNotifierUnavailable) {
writeErr(w, http.StatusServiceUnavailable, "通知器未启用")
return
}
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return
}
writeErr(w, http.StatusInternalServerError, "发送失败: "+err.Error())
return
}
@@ -281,14 +415,17 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
// getAccountBindings 负责get账号Bindings相关处理。
func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 保存路径中的账号标识。
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// ids、err 保存ids、err,供当前处理流程使用
ids, err := s.communicationApplication().GetNotificationBindingIDs(r.Context(), cid)
// sess 保存当前认证用户,用于应用层账号归属校验。
sess := authSess(r)
// ids、err 保存账号启用渠道 ID 及查询错误。
ids, err := s.notificationChannelsApplication().GetBindingIDs(r.Context(), sess.UserID, cid)
if err != nil {
if errors.Is(err, notificationsapp.ErrAccountForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
@@ -297,10 +434,10 @@ func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
// listMessageNotifications 负责list消息通知列表相关处理。
func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
// rows、err 保存rows、err,供当前处理流程使用
rows, err := s.communicationApplication().ListNotificationBindings(r.Context(), sess.UserID)
// rows、err 保存通知绑定摘要及查询错误。
rows, err := s.notificationChannelsApplication().ListBindings(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
@@ -308,59 +445,57 @@ func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request
// out 保存out,供当前处理流程使用
out := make(notificationBindingListResponse, len(rows))
// cookieID、bindings 表示当前遍历过程中的登录凭证ID、bindings
for cookieID, bindings := range rows {
// binding 表示当前遍历过程中的binding
for _, binding := range bindings {
out[cookieID] = append(out[cookieID], notificationBindingResponse{ID: binding.ID, ChannelID: binding.ChannelID, ChannelName: binding.ChannelName, Enabled: binding.Enabled})
}
// binding 表示当前遍历到的通知绑定摘要。
for _, binding := range rows {
out[binding.CookieID] = append(out[binding.CookieID], notificationBindingResponse{ID: binding.ID, ChannelID: binding.ChannelID, ChannelName: binding.ChannelName, Enabled: binding.Enabled})
}
writeJSON(w, http.StatusOK, out)
}
// setAccountBindings 负责set账号Bindings相关处理。
func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 保存路径中的账号标识。
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存req,供当前处理流程使用
var req struct {
ChannelIDs []int64 `json:"channel_ids"`
ChannelID int64 `json:"channel_id"`
Enabled *bool `json:"enabled"`
}
// req 保存具名账号通知绑定请求。
var req notificationBindingRequest
if // err 保存err,供当前处理流程使用
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if req.ChannelID != 0 {
if !s.requireChannelOwner(w, r, req.ChannelID) {
return
}
// enabled 保存启用状态,供当前处理流程使用
enabled := true
if req.Enabled != nil {
enabled = *req.Enabled
}
// err 保存err,供当前处理流程使用
err := s.communicationApplication().SetSingleNotificationBinding(r.Context(), cid, req.ChannelID, enabled)
// err 保存单条绑定应用用例结果。
err := s.notificationChannelsApplication().SetSingleBinding(r.Context(), authSess(r).UserID, cid, req.ChannelID, enabled)
if err != nil {
if errors.Is(err, notificationsapp.ErrAccountForbidden) {
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return
}
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
return
}
// channelID 表示当前遍历过程中的渠道ID
for _, channelID := range req.ChannelIDs {
if !s.requireChannelOwner(w, r, channelID) {
// err 保存批量绑定应用用例结果。
if err := s.notificationChannelsApplication().SetBindings(r.Context(), authSess(r).UserID, cid, req.ChannelIDs); err != nil {
if errors.Is(err, notificationsapp.ErrAccountForbidden) {
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return
}
}
if // err 保存err,供当前处理流程使用
err := s.communicationApplication().SetNotificationBindings(r.Context(), cid, req.ChannelIDs); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
@@ -369,15 +504,16 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
// deleteMessageNotification 负责delete消息通知相关处理。
func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
// id、err 保存id、err,供当前处理流程使用
// id、err 保存路径中的绑定 ID 及解析错误。
id, err := strconv.ParseInt(chi.URLParam(r, "notification_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效ID")
return
}
err = s.communicationApplication().DeleteNotificationBinding(r.Context(), sess.UserID, id)
// err 保存应用层绑定删除结果。
err = s.notificationChannelsApplication().DeleteBinding(r.Context(), sess.UserID, id)
if err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
@@ -387,13 +523,17 @@ func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Reques
// deleteAccountNotifications 负责delete账号通知列表相关处理。
func (s *Server) deleteAccountNotifications(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
// cid 保存cid,供当前处理流程使用
// cid 保存路径中的账号标识。
cid := chi.URLParam(r, "cid")
// err 保存err,供当前处理流程使用
err := s.communicationApplication().DeleteAccountNotificationBindings(r.Context(), sess.UserID, cid)
// err 保存应用层账号绑定删除结果。
err := s.notificationChannelsApplication().DeleteAccountBindings(r.Context(), sess.UserID, cid)
if err != nil {
if errors.Is(err, notificationsapp.ErrAccountForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) {
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
+17 -5
View File
@@ -144,6 +144,20 @@ func newChatMessageDTOFromPointer(message *db.ChatMessage) chatMessageDTO {
return newChatMessageDTO(*message)
}
// newChatMessageDTOFromApplication 将聊天应用层发送结果转换为 HTTP DTO,避免响应引用数据库模型。
func newChatMessageDTOFromApplication(message *chatapp.Message) chatMessageDTO {
if message == nil {
return chatMessageDTO{}
}
return chatMessageDTO{
ID: message.ID, AccountID: message.AccountID, ChatID: message.ChatID,
MessageKey: message.MessageKey, Direction: message.Direction,
SenderID: message.SenderID, SenderName: message.SenderName,
MessageType: message.MessageType, Content: message.Content,
Status: message.Status, SentAt: message.SentAt,
}
}
// newChatMessageDTOs 批量转换聊天消息,保持接口响应与数据库模型解耦。
func newChatMessageDTOs(messages []db.ChatMessage) []chatMessageDTO {
// result 是转换后的聊天消息 DTO 列表。
@@ -738,8 +752,6 @@ type notificationChannelResponse struct {
Name string `json:"name"`
// Type 是通知渠道类型。
Type string `json:"type"`
// Config 是通知渠道配置 JSON。
Config string `json:"config"`
// EventTypes 是订阅事件类型 JSON 或兼容分隔文本。
EventTypes string `json:"event_types,omitempty"`
// Enabled 表示通知渠道是否启用。
@@ -749,15 +761,15 @@ type notificationChannelResponse struct {
}
// newNotificationChannelResponse 将数据库通知渠道转换为 HTTP DTO。
func newNotificationChannelResponse(channel db.NotificationChannelRow) notificationChannelResponse {
func newNotificationChannelResponse(channel notificationsapp.ChannelSummary) notificationChannelResponse {
return notificationChannelResponse{
ID: channel.ID, Name: channel.Name, Type: channel.Type, Config: channel.Config,
ID: channel.ID, Name: channel.Name, Type: channel.Type,
EventTypes: channel.EventTypes, Enabled: channel.Enabled, UserID: channel.UserID,
}
}
// newNotificationChannelResponses 批量转换通知渠道,保持数据库模型不穿透 HTTP 层。
func newNotificationChannelResponses(channels []db.NotificationChannelRow) []notificationChannelResponse {
func newNotificationChannelResponses(channels []notificationsapp.ChannelSummary) []notificationChannelResponse {
// result 是转换后的通知渠道 DTO 列表。
result := make([]notificationChannelResponse, 0, len(channels))
// channel 是当前待转换的通知渠道数据库模型。