推进P1扫码聊天与通知不确定态收口
This commit is contained in:
1 parent
0a756c408e
commit
3fdd0fe267
18 files changed
+1414
-155
No files matched your search
@@ -102,6 +102,53 @@ func (r storeAccountLoginRepository) UpdateFlatCookieOwned(ctx context.Context,
|
||||
return r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix())
|
||||
}
|
||||
|
||||
// FindAccount 只读取扫码登录所需的账号归属,不解密 Cookie、密码或 metadata。
|
||||
func (r storeAccountLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) {
|
||||
// ownerID 保存数据库返回的账号所属用户标识。
|
||||
ownerID, err := r.store.Cookies.GetOwnerID(ctx, accountID)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return accountapp.QRLoginAccount{}, accountapp.ErrNotFound
|
||||
}
|
||||
return accountapp.QRLoginAccount{}, err
|
||||
}
|
||||
return accountapp.QRLoginAccount{ID: accountID, UserID: ownerID}, nil
|
||||
}
|
||||
|
||||
// UpdateQRCookieFlatOwned 更新扫码登录账号的扁平 Cookie,并清除旧的完整快照。
|
||||
func (r storeAccountLoginRepository) UpdateQRCookieFlatOwned(ctx context.Context, accountID, cookies string) error {
|
||||
// detail 保存平台运行视图;该窄视图只在凭证适配器内部读取 metadata。
|
||||
detail, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// metadata 保存移除旧快照后的加密 metadata 文本。
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
|
||||
return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix())
|
||||
}
|
||||
|
||||
// UpdateQRCookieSnapshotOwned 更新扫码 Cookie,并把完整快照合并进加密 metadata。
|
||||
func (r storeAccountLoginRepository) UpdateQRCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error {
|
||||
// detail 保存平台运行视图;完整 metadata 不向应用服务层泄露。
|
||||
detail, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// browserSnapshot 保存转换后的浏览器 Cookie 快照,仅在数据库适配器内使用。
|
||||
browserSnapshot := make([]cookierefresh.BrowserCookie, 0, len(snapshot))
|
||||
// snapshotEntry 表示当前待转换的应用层 Cookie 快照。
|
||||
for _, snapshotEntry := range snapshot {
|
||||
browserSnapshot = append(browserSnapshot, cookierefresh.BrowserCookie{
|
||||
Name: snapshotEntry.Name, Value: snapshotEntry.Value, Domain: snapshotEntry.Domain,
|
||||
Path: snapshotEntry.Path, Expires: snapshotEntry.Expires, HTTPOnly: snapshotEntry.HTTPOnly,
|
||||
Secure: snapshotEntry.Secure, SameSite: snapshotEntry.SameSite, PartitionKey: snapshotEntry.PartitionKey,
|
||||
})
|
||||
}
|
||||
// metadata 保存快照合并后的加密 metadata 文本。
|
||||
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, browserSnapshot)
|
||||
return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix())
|
||||
}
|
||||
|
||||
// UpdateRenewalCookie 委托 Cookie 与 metadata 更新。
|
||||
func (r storeAccountLoginRepository) UpdateRenewalCookie(ctx context.Context, accountID, cookies, metadata string, at int64) error {
|
||||
return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, at)
|
||||
@@ -151,5 +198,53 @@ func newStoreAccountLoginRepository(store *db.Store) accountLoginRepository {
|
||||
return storeAccountLoginRepository{store: store}
|
||||
}
|
||||
|
||||
// newStoreQRLoginRepository 从完整 Store 构造扫码登录应用服务所需的窄凭证端口。
|
||||
func newStoreQRLoginRepository(store *db.Store) accountapp.QRLoginRepository {
|
||||
if store == nil || store.Cookies == nil {
|
||||
return nil
|
||||
}
|
||||
return storeQRLoginRepository{store: store}
|
||||
}
|
||||
|
||||
// storeQRLoginRepository 将 Store 的扫码凭证能力限制在应用服务定义的窄端口内。
|
||||
type storeQRLoginRepository struct {
|
||||
// store 提供数据库凭证读写能力,仅在本适配器内部访问。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// LockCredentials 串行化扫码登录对同一账号的凭证变更。
|
||||
func (r storeQRLoginRepository) LockCredentials(accountID string) func() {
|
||||
return r.store.LockAccountCredentials(accountID)
|
||||
}
|
||||
|
||||
// FindAccount 只返回账号存在性和归属,不读取 Cookie、密码或 metadata。
|
||||
func (r storeQRLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) {
|
||||
return storeAccountLoginRepository(r).FindAccount(ctx, accountID)
|
||||
}
|
||||
|
||||
// CreateCookieOwned 创建扫码登录得到的新账号 Cookie。
|
||||
func (r storeQRLoginRepository) CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error {
|
||||
return r.store.Cookies.CreateOwned(ctx, accountID, cookies, userID)
|
||||
}
|
||||
|
||||
// UpdateFlatCookieOwned 更新已有账号的扁平 Cookie,并清除完整快照。
|
||||
func (r storeQRLoginRepository) UpdateFlatCookieOwned(ctx context.Context, accountID, cookies string) error {
|
||||
return storeAccountLoginRepository(r).UpdateQRCookieFlatOwned(ctx, accountID, cookies)
|
||||
}
|
||||
|
||||
// UpdateCookieSnapshotOwned 更新 Cookie 并合并完整浏览器快照。
|
||||
func (r storeQRLoginRepository) UpdateCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error {
|
||||
return storeAccountLoginRepository(r).UpdateQRCookieSnapshotOwned(ctx, accountID, cookies, snapshot)
|
||||
}
|
||||
|
||||
// ClearTokens 清理扫码登录前遗留的旧连接 Token。
|
||||
func (r storeQRLoginRepository) ClearTokens(ctx context.Context, accountID string) error {
|
||||
// clearErr 保存旧连接 Token 清理结果;凭证已成功写入时该错误不阻断扫码登录。
|
||||
return storeAccountLoginRepository(r).ClearTokens(ctx, accountID)
|
||||
}
|
||||
|
||||
// 确保 Store 适配器始终覆盖账号登录服务所需的全部能力。
|
||||
var _ accountLoginRepository = storeAccountLoginRepository{}
|
||||
|
||||
// 确保扫码凭证适配器始终覆盖应用服务定义的最小端口。
|
||||
var _ accountapp.QRLoginRepository = storeQRLoginRepository{}
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
@@ -22,6 +21,8 @@ type accountLoginService struct {
|
||||
repository accountLoginRepository
|
||||
// createApplication 提供已迁移的手动 Cookie 登录应用用例。
|
||||
createApplication *accountapp.LoginService
|
||||
// qrApplication 提供扫码成功凭证持久化应用用例;会话幂等状态仍由 Server 适配器拥有。
|
||||
qrApplication *accountapp.QRLoginService
|
||||
}
|
||||
|
||||
// serverLoginLifecyclePort 将登录成功后的审计、资料刷新和运行时重启适配到应用层端口。
|
||||
@@ -75,6 +76,11 @@ func newAccountLoginCreateApplication(server *Server) (*accountapp.LoginService,
|
||||
return accountapp.NewLoginService(serverLoginLifecyclePort{server: server})
|
||||
}
|
||||
|
||||
// newAccountQRLoginApplication 构造扫码登录应用服务及其凭证、生命周期适配器。
|
||||
func newAccountQRLoginApplication(server *Server) (*accountapp.QRLoginService, error) {
|
||||
return accountapp.NewQRLoginService(newStoreQRLoginRepository(server.Store), serverQRLoginLifecycle{server: server})
|
||||
}
|
||||
|
||||
// serverAccountProfilePort 将平台资料刷新适配为账号应用层 Port。
|
||||
type serverAccountProfilePort struct {
|
||||
// server 提供平台会话、凭证锁、资料保存和运行时同步能力。
|
||||
@@ -185,13 +191,34 @@ func (svc *accountLoginService) UpdateCookie(ctx context.Context, input accountC
|
||||
return nil
|
||||
}
|
||||
|
||||
// PersistQRLoginSuccess 持久化扫码登录结果,复用会话级幂等锁和账号重启流程。
|
||||
func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) {
|
||||
return svc.persistQRLoginSuccessCore(ctx, userID, sessionID, result, targetAccountID)
|
||||
// serverQRLoginLifecycle 将扫码登录成功后的审计、资料刷新和运行时同步适配到应用端口。
|
||||
type serverQRLoginLifecycle struct {
|
||||
// server 提供审计、资料刷新、自动化唤醒和账号运行时管理能力。
|
||||
server *Server
|
||||
}
|
||||
|
||||
// persistQRLoginSuccessCore 执行扫码结果校验、凭证合并、登录审计和账号重启。
|
||||
func (svc *accountLoginService) persistQRLoginSuccessCore(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) {
|
||||
// AfterSuccessfulQRLogin 在凭证锁释放后执行扫码登录成功的后续编排。
|
||||
func (p serverQRLoginLifecycle) AfterSuccessfulQRLogin(ctx context.Context, userID int64, accountID string) {
|
||||
if p.server == nil {
|
||||
return
|
||||
}
|
||||
p.server.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功")
|
||||
p.server.accountLoginApplication().refreshAndRestartAccount(ctx, userID, accountID)
|
||||
p.server.wakeCredentialBlockedAutomation(ctx, accountID)
|
||||
}
|
||||
|
||||
// ReportQRLoginCleanupFailure 记录扫码登录后旧 Token 清理失败,不暴露 Cookie 内容且不回滚已写入凭证。
|
||||
func (p serverQRLoginLifecycle) ReportQRLoginCleanupFailure(_ context.Context, accountID string, err error) {
|
||||
if p.server != nil && p.server.Logger != nil {
|
||||
p.server.Logger.Warn("扫码登录后清理旧连接凭证失败", "cookie_id", accountID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// PersistQRLoginSuccess 将 HTTP/平台 map 适配为纯应用 DTO,并复用会话级幂等锁。
|
||||
func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) {
|
||||
if svc == nil || svc.server == nil || svc.qrApplication == nil {
|
||||
return qrLoginPersistence{}, errors.New("扫码登录应用服务未初始化")
|
||||
}
|
||||
// s 是当前账号登录应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// lockValue 和 persistMu 保证同一扫码会话只执行一次持久化。
|
||||
@@ -214,103 +241,44 @@ func (svc *accountLoginService) persistQRLoginSuccessCore(ctx context.Context, u
|
||||
return persisted, nil
|
||||
}
|
||||
s.qrMu.Unlock()
|
||||
// cookies、cookieSnapshot 和 snapshotComplete 保存平台登录凭证及其完整 Cookie Jar。
|
||||
// cookies 保存平台返回的登录 Cookie 明文,仅在 Server 到应用端口的调用边界短暂存在。
|
||||
cookies := qrString(result, "cookies")
|
||||
// cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie Jar。
|
||||
// cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie 快照及其完整性。
|
||||
cookieSnapshot, snapshotComplete := qrCookieSnapshot(result)
|
||||
// scannedAccountID 是扫码结果中的平台账号标识。
|
||||
// scannedAccountID 保存从结果字段或 Cookie 解析出的平台账号标识。
|
||||
scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"]))
|
||||
if cookies == "" || scannedAccountID == "" {
|
||||
return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
|
||||
}
|
||||
// accountID 是最终写入的账号标识。
|
||||
accountID := strings.TrimSpace(targetAccountID)
|
||||
if accountID == "" {
|
||||
accountID = scannedAccountID
|
||||
} else if accountID != scannedAccountID {
|
||||
return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖")
|
||||
}
|
||||
|
||||
// isNew 标记本次扫码是否创建了新账号。
|
||||
isNew := false
|
||||
// credentialUnlock 保护账号凭证写入和登录审计。
|
||||
credentialUnlock := svc.repository.LockCredentials(accountID)
|
||||
// saveErr 保存账号凭证、Cookie Jar 和登录审计的事务错误。
|
||||
saveErr := func() error {
|
||||
defer credentialUnlock()
|
||||
// detail 和 err 保存待更新账号的凭证详情。
|
||||
detail, err := s.loadCookiePlatformDetail(ctx, accountID)
|
||||
switch {
|
||||
case errors.Is(err, db.ErrNotFound):
|
||||
if targetAccountID != "" {
|
||||
return errors.New("待重新授权账号不存在")
|
||||
}
|
||||
isNew = true
|
||||
// err 表示创建扫码账号的错误。
|
||||
if err := svc.repository.CreateCookieOwned(ctx, accountID, cookies, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
if snapshotComplete {
|
||||
// metadata 是新账号的完整 Cookie Jar 元数据。
|
||||
metadata := cookierefresh.MetadataWithSnapshot("", cookieSnapshot)
|
||||
// err 表示保存新账号 Cookie Jar 的错误。
|
||||
if err := svc.repository.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case err != nil:
|
||||
return err
|
||||
case detail == nil:
|
||||
return db.ErrNotFound
|
||||
case detail.UserID != userID:
|
||||
if targetAccountID != "" {
|
||||
return errors.New("待重新授权账号不属于当前用户")
|
||||
}
|
||||
return db.ErrForbidden
|
||||
default:
|
||||
if snapshotComplete {
|
||||
// metadata 是已有账号合并后的 Cookie Jar 元数据。
|
||||
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, cookieSnapshot)
|
||||
// err 表示保存已有账号 Cookie Jar 的错误。
|
||||
if err := svc.repository.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 表示合并扁平 Cookie 的错误。
|
||||
} else if err := svc.repository.UpdateFlatCookieOwned(ctx, detail, cookies); err != nil {
|
||||
return err
|
||||
}
|
||||
// input 保存转换后的纯应用扫码登录输入;Cookie 只交给凭证端口消费。
|
||||
input := accountapp.QRLoginInput{UserID: userID, ScannedAccountID: scannedAccountID, TargetAccountID: targetAccountID, Cookies: cookies}
|
||||
if snapshotComplete {
|
||||
input.Snapshot = make([]accountapp.CookieSnapshot, 0, len(cookieSnapshot))
|
||||
// cookie 保存当前浏览器 Cookie 快照,转换后不再依赖平台 DTO。
|
||||
for _, cookie := range cookieSnapshot {
|
||||
input.Snapshot = append(input.Snapshot, accountapp.CookieSnapshot{
|
||||
Name: cookie.Name, Value: cookie.Value, Domain: cookie.Domain, Path: cookie.Path,
|
||||
Expires: cookie.Expires, HTTPOnly: cookie.HTTPOnly, Secure: cookie.Secure,
|
||||
SameSite: cookie.SameSite, PartitionKey: cookie.PartitionKey,
|
||||
})
|
||||
}
|
||||
s.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功")
|
||||
{
|
||||
// err 表示清理旧连接凭证的错误,仅记录不阻断扫码登录。
|
||||
if err := svc.repository.ClearTokens(ctx, accountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("扫码登录保存后清理旧连接凭证失败", "cookie_id", accountID, "err", err)
|
||||
}
|
||||
}
|
||||
// resultValue 保存应用服务返回的非敏感持久化结果。
|
||||
resultValue, persistErr := svc.qrApplication.PersistSuccess(ctx, input)
|
||||
if persistErr != nil {
|
||||
if errors.Is(persistErr, accountapp.ErrQRLoginIncomplete) {
|
||||
return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
if saveErr != nil {
|
||||
if errors.Is(saveErr, db.ErrForbidden) {
|
||||
if errors.Is(persistErr, accountapp.ErrQRLoginAccountMismatch) {
|
||||
return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖")
|
||||
}
|
||||
if errors.Is(persistErr, accountapp.ErrForbidden) {
|
||||
return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户")
|
||||
}
|
||||
if errors.Is(saveErr, db.ErrAlreadyExists) {
|
||||
if errors.Is(persistErr, db.ErrAlreadyExists) {
|
||||
return qrLoginPersistence{}, errors.New("该账号ID已被并发创建,请重新获取账号状态")
|
||||
}
|
||||
return qrLoginPersistence{}, saveErr
|
||||
}
|
||||
// detail 和 err 保存登录成功后的资料摘要查询结果。
|
||||
if detail, err := s.loadCookieSummaryDetail(ctx, userID, accountID); err == nil {
|
||||
s.refreshAccountProfile(ctx, detail)
|
||||
}
|
||||
s.wakeCredentialBlockedAutomation(ctx, accountID)
|
||||
if s.Manager != nil && svc.repository.GetStatus(ctx, accountID) {
|
||||
// err 表示扫码登录后的账号运行时重启错误。
|
||||
if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("扫码登录后重启账号失败", "cookie_id", accountID, "err", err)
|
||||
}
|
||||
return qrLoginPersistence{}, persistErr
|
||||
}
|
||||
// persisted 是扫码会话幂等返回值。
|
||||
persisted := qrLoginPersistence{AccountID: accountID, IsNew: isNew, UserID: userID, CreatedAt: time.Now().UTC()}
|
||||
persisted := qrLoginPersistence{AccountID: resultValue.AccountID, IsNew: resultValue.IsNew, UserID: userID, CreatedAt: time.Now().UTC()}
|
||||
s.qrMu.Lock()
|
||||
s.qrPersisted[sessionID] = persisted
|
||||
s.qrMu.Unlock()
|
||||
|
||||
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
accountapp "xianyu-go/internal/application/account"
|
||||
chatapp "xianyu-go/internal/application/chat"
|
||||
itemapp "xianyu-go/internal/application/items"
|
||||
orderapp "xianyu-go/internal/application/orders"
|
||||
)
|
||||
@@ -22,6 +23,8 @@ type applicationServices struct {
|
||||
accountProfile *accountapp.ProfileService
|
||||
// communication 是聊天、通知和账号任务应用服务。
|
||||
communication *communicationService
|
||||
// chat 是聊天历史查询应用服务,负责用户归属和分页编排。
|
||||
chat *chatapp.Service
|
||||
// analytics 是订单分析应用服务。
|
||||
analytics *analyticsService
|
||||
}
|
||||
@@ -49,14 +52,25 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
if accountLoginCreateErr != nil {
|
||||
panic(accountLoginCreateErr)
|
||||
}
|
||||
// accountQRLogin 是扫码成功凭证持久化应用服务的构造结果;零值测试 Server 暂不装配数据库端口。
|
||||
var accountQRLogin *accountapp.QRLoginService
|
||||
if server.Store != nil {
|
||||
// accountQRLoginErr 保存扫码应用服务装配失败原因。
|
||||
var accountQRLoginErr error
|
||||
accountQRLogin, accountQRLoginErr = newAccountQRLoginApplication(server)
|
||||
if accountQRLoginErr != nil {
|
||||
panic(accountQRLoginErr)
|
||||
}
|
||||
}
|
||||
return &applicationServices{
|
||||
orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository},
|
||||
itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)},
|
||||
itemSinglePublish: newItemPublishApplication(server),
|
||||
itemBatchRunner: itemBatchRunner,
|
||||
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store), createApplication: accountLoginCreate},
|
||||
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)),
|
||||
analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
chatapp "xianyu-go/internal/application/chat"
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
@@ -29,6 +30,79 @@ func (s *Server) mountChat(r chi.Router) {
|
||||
r.Get("/api/chat/ws", s.chatWebSocket)
|
||||
}
|
||||
|
||||
// storeChatApplicationRepository 将数据库聊天查询适配为应用层聊天端口。
|
||||
type storeChatApplicationRepository struct {
|
||||
// store 保存数据库聚合入口,仅在适配器内执行窄聊天查询。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// ListMessages 查询带用户归属条件的聊天消息,并转换为应用层模型。
|
||||
func (r storeChatApplicationRepository) ListMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]chatapp.Message, error) {
|
||||
// rows 保存数据库返回的消息记录。
|
||||
rows, err := r.store.Chats.ListMessages(ctx, userID, accountID, chatID, beforeID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// messages 保存脱离数据库模型的应用层消息。
|
||||
messages := make([]chatapp.Message, 0, len(rows))
|
||||
// row 表示当前待转换的数据库聊天消息。
|
||||
for _, row := range rows {
|
||||
messages = append(messages, chatapp.Message{
|
||||
ID: row.ID, AccountID: row.CookieID, ChatID: row.ChatID, MessageKey: row.MessageKey,
|
||||
Direction: row.Direction, SenderID: row.SenderID, SenderName: row.SenderName,
|
||||
MessageType: row.MessageType, Content: row.Content, Status: row.Status, SentAt: row.SentAt,
|
||||
})
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// ListSessions 查询带用户归属条件的聊天会话,并转换为应用层模型。
|
||||
func (r storeChatApplicationRepository) ListSessions(ctx context.Context, userID int64, accountID string, limit int) ([]chatapp.Session, error) {
|
||||
// rows 保存数据库返回的会话记录。
|
||||
rows, err := r.store.Chats.ListSessions(ctx, userID, accountID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// sessions 保存脱离数据库模型的应用层会话摘要。
|
||||
sessions := make([]chatapp.Session, 0, len(rows))
|
||||
// row 表示当前待转换的数据库聊天会话。
|
||||
for _, row := range rows {
|
||||
sessions = append(sessions, chatapp.Session{
|
||||
AccountID: row.CookieID, ChatID: row.ChatID, BuyerID: row.BuyerID,
|
||||
BuyerName: row.BuyerName, BuyerAvatar: row.BuyerAvatar, ItemID: row.ItemID,
|
||||
ItemTitle: row.ItemTitle, LastMessage: row.LastMessage, LastMessageAt: row.LastMessageAt,
|
||||
UnreadCount: row.UnreadCount,
|
||||
})
|
||||
}
|
||||
return sessions, nil
|
||||
}
|
||||
|
||||
// newStoreChatApplicationRepository 创建聊天历史应用服务使用的数据库适配器。
|
||||
func newStoreChatApplicationRepository(store *db.Store) chatapp.Repository {
|
||||
if store == nil || store.Chats == nil {
|
||||
return nil
|
||||
}
|
||||
return storeChatApplicationRepository{store: store}
|
||||
}
|
||||
|
||||
// dbChatSessionFromApplication 将非敏感应用会话转换为平台身份适配器可消费的数据库形状。
|
||||
func dbChatSessionFromApplication(session chatapp.Session) db.ChatSession {
|
||||
return db.ChatSession{
|
||||
CookieID: session.AccountID, ChatID: session.ChatID, BuyerID: session.BuyerID,
|
||||
BuyerName: session.BuyerName, BuyerAvatar: session.BuyerAvatar, ItemID: session.ItemID,
|
||||
ItemTitle: session.ItemTitle, LastMessage: session.LastMessage, LastMessageAt: session.LastMessageAt,
|
||||
UnreadCount: session.UnreadCount,
|
||||
}
|
||||
}
|
||||
|
||||
// 确保数据库适配器覆盖聊天历史应用端口的全部能力。
|
||||
var _ chatapp.Repository = storeChatApplicationRepository{}
|
||||
|
||||
// chatApplication 返回当前 Server 绑定的聊天历史应用服务。
|
||||
func (s *Server) chatApplication() *chatapp.Service {
|
||||
return s.applicationServiceSet().chat
|
||||
}
|
||||
|
||||
// listChatSessions 负责list聊天Sessions相关处理。
|
||||
func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
@@ -290,12 +364,17 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
// page、err 保存page、err,供当前处理流程使用
|
||||
page, err := s.communicationApplication().ListStoredChatMessages(r.Context(), sess.UserID, accountID, chatID, beforeID, limit)
|
||||
page, err := s.chatApplication().ListStoredMessages(r.Context(), sess.UserID, accountID, chatID, beforeID, limit)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取聊天消息失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOs(page.Messages), HasMore: page.HasMore, Session: newChatSessionDTO(page.Session)})
|
||||
// session 是应用层返回的非敏感会话摘要,供平台身份适配器补齐展示名称。
|
||||
session := dbChatSessionFromApplication(page.Session)
|
||||
if session.ChatID != "" {
|
||||
session = s.resolveSelectedChatIdentity(r.Context(), accountID, session)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOsFromApplication(page.Messages), HasMore: page.HasMore, Session: newChatSessionDTO(session)})
|
||||
}
|
||||
|
||||
// resolveSelectedChatIdentity 负责resolveSelected聊天Identity相关处理。
|
||||
|
||||
@@ -44,10 +44,6 @@ type communicationRepository interface {
|
||||
UpdateCookieValue(ctx context.Context, cookieID, value string) error
|
||||
// MarkChatRead 将聊天会话标记为已读。
|
||||
MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error
|
||||
// ListChatMessages 查询聊天历史消息。
|
||||
ListChatMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]db.ChatMessage, error)
|
||||
// ListChatSessions 查询账号聊天会话列表。
|
||||
ListChatSessions(ctx context.Context, userID int64, accountID string, limit int) ([]db.ChatSession, error)
|
||||
}
|
||||
|
||||
// storeCommunicationRepository 将完整 Store 适配为通信应用服务窄 repository。
|
||||
@@ -146,16 +142,6 @@ func (r storeCommunicationRepository) MarkChatRead(ctx context.Context, userID i
|
||||
return r.store.Chats.MarkRead(ctx, userID, accountID, chatID)
|
||||
}
|
||||
|
||||
// ListChatMessages 委托聊天消息查询。
|
||||
func (r storeCommunicationRepository) ListChatMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]db.ChatMessage, error) {
|
||||
return r.store.Chats.ListMessages(ctx, userID, accountID, chatID, beforeID, limit)
|
||||
}
|
||||
|
||||
// ListChatSessions 委托聊天会话查询。
|
||||
func (r storeCommunicationRepository) ListChatSessions(ctx context.Context, userID int64, accountID string, limit int) ([]db.ChatSession, error) {
|
||||
return r.store.Chats.ListSessions(ctx, userID, accountID, limit)
|
||||
}
|
||||
|
||||
// newStoreCommunicationRepository 从完整 Store 构造通信应用服务窄 repository。
|
||||
func newStoreCommunicationRepository(store *db.Store) communicationRepository {
|
||||
if store == nil || store.AccountTasks == nil || store.Notifications == nil || store.Cookies == nil || store.Chats == nil {
|
||||
|
||||
@@ -59,18 +59,6 @@ type chatImageInput struct {
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// chatMessagePageResult 是聊天历史查询结果,不依赖 HTTP DTO。
|
||||
type chatMessagePageResult struct {
|
||||
// Messages 是本地或远端保存的聊天消息。
|
||||
Messages []db.ChatMessage
|
||||
// Session 是当前聊天会话摘要。
|
||||
Session db.ChatSession
|
||||
// HasMore 表示是否还有更早消息。
|
||||
HasMore bool
|
||||
// NextCursor 是远端历史分页游标。
|
||||
NextCursor int64
|
||||
}
|
||||
|
||||
// notificationBindingRow 是通知绑定列表的一行业务数据。
|
||||
type notificationBindingRow struct {
|
||||
// ID 是绑定记录标识。
|
||||
@@ -313,25 +301,3 @@ func (svc *communicationService) SendChatImage(ctx context.Context, input chatIm
|
||||
func (svc *communicationService) MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error {
|
||||
return svc.repository.MarkChatRead(ctx, userID, accountID, chatID)
|
||||
}
|
||||
|
||||
// ListStoredChatMessages 查询本地聊天历史并返回会话摘要。
|
||||
func (svc *communicationService) ListStoredChatMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) (chatMessagePageResult, error) {
|
||||
// messages 和 err 保存本地聊天历史查询结果。
|
||||
messages, err := svc.repository.ListChatMessages(ctx, userID, accountID, chatID, beforeID, limit)
|
||||
if err != nil {
|
||||
return chatMessagePageResult{}, err
|
||||
}
|
||||
// session 保存当前聊天会话摘要。
|
||||
var session db.ChatSession
|
||||
// sessions 和 sessionErr 保存当前用户的聊天会话列表及查询错误。
|
||||
if sessions, sessionErr := svc.repository.ListChatSessions(ctx, userID, accountID, 500); sessionErr == nil {
|
||||
// candidate 是当前遍历到的会话摘要。
|
||||
for _, candidate := range sessions {
|
||||
if candidate.ChatID == chatID {
|
||||
session = svc.server.resolveSelectedChatIdentity(ctx, accountID, candidate)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return chatMessagePageResult{Messages: messages, Session: session, HasMore: len(messages) == limit}, nil
|
||||
}
|
||||
@@ -39,15 +39,15 @@ func TestCommunicationServiceRejectsInvalidAccountTask(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommunicationServiceListsStoredChatMessages 验证聊天历史查询服务返回稳定分页结果。
|
||||
func TestCommunicationServiceListsStoredChatMessages(t *testing.T) {
|
||||
// TestChatApplicationListsStoredMessages 验证聊天历史应用服务返回稳定分页结果。
|
||||
func TestChatApplicationListsStoredMessages(t *testing.T) {
|
||||
// srv、store 和 cleanup 构造并释放测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// page 和 err 保存聊天历史查询结果。
|
||||
page, err := srv.communicationApplication().ListStoredChatMessages(context.Background(), 1, "acc1", "chat-missing", 0, 20)
|
||||
page, err := srv.chatApplication().ListStoredMessages(context.Background(), 1, "acc1", "chat-missing", 0, 20)
|
||||
if err != nil {
|
||||
t.Fatalf("ListStoredChatMessages error: %v", err)
|
||||
t.Fatalf("ListStoredMessages error: %v", err)
|
||||
}
|
||||
if len(page.Messages) != 0 || page.Session.ChatID != "" {
|
||||
t.Fatalf("unexpected empty chat page: %+v", page)
|
||||
|
||||
@@ -25,6 +25,46 @@ func (s *Server) mountNotificationsReal(r chi.Router) {
|
||||
r.Post("/message-notifications/{cid}", s.setAccountBindings)
|
||||
}
|
||||
|
||||
// listUncertainNotifications 返回当前用户渠道对应的不确定通知摘要,不暴露正文或凭证。
|
||||
func (s *Server) listUncertainNotifications(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存当前已认证用户,用于限制通知渠道归属范围。
|
||||
sess := authSess(r)
|
||||
// limit 保存运维列表页请求的最大条数,超出范围时使用数据库默认上限。
|
||||
limit := parsePositiveInt(r.URL.Query().Get("limit"), 20)
|
||||
// items 保存当前用户可见的不确定通知摘要。
|
||||
items, err := s.Store.Notifications.ListUncertainOutboxForUser(r.Context(), sess.UserID, limit)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询通知状态失败")
|
||||
return
|
||||
}
|
||||
// total 保存当前用户渠道的不确定通知总数。
|
||||
total, err := s.Store.Notifications.CountUncertainOutboxForUser(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计通知状态失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, newNotificationUncertainOutboxResponse(items, total, false))
|
||||
}
|
||||
|
||||
// listAdminUncertainNotifications 返回全局不确定通知摘要,仅管理员路由可访问。
|
||||
func (s *Server) listAdminUncertainNotifications(w http.ResponseWriter, r *http.Request) {
|
||||
// limit 保存管理员运维查询的最大条数,超出范围时使用数据库默认上限。
|
||||
limit := parsePositiveInt(r.URL.Query().Get("limit"), 50)
|
||||
// items 保存所有用户渠道的不确定通知摘要,但不包含正文和错误原文。
|
||||
items, err := s.Store.Notifications.ListUncertainOutboxForAdmin(r.Context(), limit)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询通知状态失败")
|
||||
return
|
||||
}
|
||||
// total 保存全局不确定通知总数。
|
||||
total, err := s.Store.Notifications.CountUncertainOutboxForAdmin(r.Context())
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计通知状态失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, newNotificationUncertainOutboxResponse(items, total, true))
|
||||
}
|
||||
|
||||
// listChannels 负责list渠道列表相关处理。
|
||||
func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestUncertainNotificationEndpointsEnforceScope 验证用户与管理员 uncertain 查询的隔离和脱敏边界。
|
||||
func TestUncertainNotificationEndpointsEnforceScope(t *testing.T) {
|
||||
// srv、store、cleanup 保存 HTTP 测试服务、数据库和资源释放函数。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// ctx 保存数据库夹具使用的根上下文。
|
||||
ctx := context.Background()
|
||||
// userCreated、err 保存普通用户创建结果和数据库错误。
|
||||
userCreated, err := store.Users.Create(ctx, "uncertain-http-user", "[email protected]", "pw")
|
||||
if err != nil || !userCreated {
|
||||
t.Fatalf("create user: created=%v err=%v", userCreated, err)
|
||||
}
|
||||
// user、err 保存普通用户实体和读取错误。
|
||||
user, err := store.Users.GetByUsername(ctx, "uncertain-http-user")
|
||||
if err != nil {
|
||||
t.Fatalf("get user: %v", err)
|
||||
}
|
||||
// createChannel 创建指定用户拥有的通知渠道并返回渠道标识。
|
||||
createChannel := func(userID int64) int64 {
|
||||
// result、err 保存渠道插入结果和数据库错误。
|
||||
result, err := store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES (?,?,?,?,?)`, "ops", "webhook", `{}`, 1, userID)
|
||||
if err != nil {
|
||||
t.Fatalf("create channel: %v", err)
|
||||
}
|
||||
// channelID、err 保存渠道主键和读取主键错误。
|
||||
channelID, err := result.LastInsertId()
|
||||
if err != nil {
|
||||
t.Fatalf("channel id: %v", err)
|
||||
}
|
||||
return channelID
|
||||
}
|
||||
// adminChannelID、userChannelID 保存管理员与普通用户各自拥有的渠道。
|
||||
adminChannelID := createChannel(1)
|
||||
// userChannelID 保存普通用户拥有的通知渠道标识。
|
||||
userChannelID := createChannel(user.ID)
|
||||
// enqueueUncertain 写入包含敏感正文的通知并推进到 uncertain 状态。
|
||||
enqueueUncertain := func(channelID int64, eventType string) {
|
||||
// body 保存仅供 worker 的测试正文,验证 HTTP 响应不会返回它。
|
||||
body := "绝不能从接口泄露的通知正文 token=super-secret"
|
||||
// err 保存 outbox 写入错误。
|
||||
if err := store.Notifications.EnqueueOutbox(ctx, []db.NotificationOutboxInput{{ChannelID: channelID, EventType: eventType, Body: body}}); err != nil {
|
||||
t.Fatalf("enqueue outbox: %v", err)
|
||||
}
|
||||
// workerToken 保存当前测试 worker 的租约标识。
|
||||
workerToken := "http-" + eventType
|
||||
// claimed、err 保存 worker 抢占结果和数据库错误。
|
||||
claimed, err := store.Notifications.ClaimOutbox(ctx, workerToken, time.Unix(100, 0), 10)
|
||||
if err != nil || len(claimed) != 1 {
|
||||
t.Fatalf("claim outbox: messages=%+v err=%v", claimed, err)
|
||||
}
|
||||
// marked、err 保存 uncertain 状态转移结果和数据库错误。
|
||||
marked, err := store.Notifications.MarkOutboxUncertain(ctx, claimed[0].ID, workerToken, "credential=should-not-leak")
|
||||
if err != nil || !marked {
|
||||
t.Fatalf("mark uncertain: marked=%v err=%v", marked, err)
|
||||
}
|
||||
}
|
||||
enqueueUncertain(adminChannelID, "admin-event")
|
||||
enqueueUncertain(userChannelID, "user-event")
|
||||
|
||||
// handler 保存当前服务的 HTTP 路由处理器。
|
||||
handler := srv.Router()
|
||||
// userCookie 保存普通用户登录后的会话 Cookie。
|
||||
userCookie := loginAsHelper(t, handler, "uncertain-http-user", "pw")
|
||||
// userReq、userRec 保存普通用户查询请求及响应。
|
||||
userReq := httptest.NewRequest(http.MethodGet, "/api/v1/notifications/outbox/uncertain?limit=10", nil)
|
||||
userReq.AddCookie(userCookie)
|
||||
// userRec 保存普通用户查询响应。
|
||||
userRec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(userRec, userReq)
|
||||
if userRec.Code != http.StatusOK {
|
||||
t.Fatalf("user uncertain status=%d body=%s", userRec.Code, userRec.Body.String())
|
||||
}
|
||||
// userResponse 保存普通用户可见的非敏感通知摘要。
|
||||
var userResponse notificationUncertainOutboxResponse
|
||||
// decodeErr 保存解析普通用户响应时的 JSON 错误。
|
||||
if decodeErr := json.Unmarshal(userRec.Body.Bytes(), &userResponse); decodeErr != nil {
|
||||
t.Fatalf("decode user response: %v", decodeErr)
|
||||
}
|
||||
if userResponse.Total != 1 || len(userResponse.Items) != 1 || userResponse.Items[0].EventType != "user-event" || userResponse.Items[0].OwnerUserID != 0 {
|
||||
t.Fatalf("user response violates scope: %+v", userResponse)
|
||||
}
|
||||
if strings.Contains(userRec.Body.String(), "super-secret") || strings.Contains(userRec.Body.String(), "should-not-leak") {
|
||||
t.Fatal("user uncertain response leaked notification body or error")
|
||||
}
|
||||
|
||||
// adminCookie 保存管理员登录后的会话 Cookie。
|
||||
adminCookie := loginHelper(t, handler)
|
||||
// adminReq、adminRec 保存管理员查询请求及响应。
|
||||
adminReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/notifications/outbox/uncertain?limit=10", nil)
|
||||
adminReq.AddCookie(adminCookie)
|
||||
// adminRec 保存管理员查询响应。
|
||||
adminRec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(adminRec, adminReq)
|
||||
if adminRec.Code != http.StatusOK {
|
||||
t.Fatalf("admin uncertain status=%d body=%s", adminRec.Code, adminRec.Body.String())
|
||||
}
|
||||
// adminResponse 保存管理员可见的全局摘要。
|
||||
var adminResponse notificationUncertainOutboxResponse
|
||||
// decodeErr 保存解析管理员响应时的 JSON 错误。
|
||||
if decodeErr := json.Unmarshal(adminRec.Body.Bytes(), &adminResponse); decodeErr != nil {
|
||||
t.Fatalf("decode admin response: %v", decodeErr)
|
||||
}
|
||||
if adminResponse.Total != 2 || len(adminResponse.Items) != 2 {
|
||||
t.Fatalf("admin response missing global items: %+v", adminResponse)
|
||||
}
|
||||
// item 表示当前遍历到的管理员通知摘要。
|
||||
for _, item := range adminResponse.Items {
|
||||
if item.OwnerUserID == 0 || !item.HasError {
|
||||
t.Fatalf("admin response missing safe metadata: %+v", item)
|
||||
}
|
||||
}
|
||||
if strings.Contains(adminRec.Body.String(), "super-secret") || strings.Contains(adminRec.Body.String(), "should-not-leak") {
|
||||
t.Fatal("admin uncertain response leaked notification body or error")
|
||||
}
|
||||
|
||||
// forbiddenReq、forbiddenRec 保存普通用户访问管理员接口的请求及响应。
|
||||
forbiddenReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/notifications/outbox/uncertain", nil)
|
||||
forbiddenReq.AddCookie(userCookie)
|
||||
// forbiddenRec 保存普通用户访问管理员接口的响应。
|
||||
forbiddenRec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(forbiddenRec, forbiddenReq)
|
||||
if forbiddenRec.Code != http.StatusForbidden {
|
||||
t.Fatalf("non-admin admin uncertain status=%d body=%s", forbiddenRec.Code, forbiddenRec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
chatapp "xianyu-go/internal/application/chat"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
@@ -153,6 +154,22 @@ func newChatMessageDTOs(messages []db.ChatMessage) []chatMessageDTO {
|
||||
return result
|
||||
}
|
||||
|
||||
// newChatMessageDTOsFromApplication 将聊天应用层消息转换为 HTTP DTO,避免响应暴露数据库模型。
|
||||
func newChatMessageDTOsFromApplication(messages []chatapp.Message) []chatMessageDTO {
|
||||
// result 是转换后的聊天消息 DTO 列表。
|
||||
result := make([]chatMessageDTO, 0, len(messages))
|
||||
// message 保存当前待转换的应用层消息。
|
||||
for _, message := range messages {
|
||||
result = append(result, 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,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// chatSessionPageResponse 是聊天会话分页接口的具名响应 DTO。
|
||||
type chatSessionPageResponse struct {
|
||||
// Sessions 是当前页聊天会话。
|
||||
@@ -772,6 +789,53 @@ type accountBindingsResponse struct {
|
||||
ChannelIDs []int64 `json:"channel_ids"`
|
||||
}
|
||||
|
||||
// notificationUncertainOutboxItem 是不确定通知的非敏感运维摘要。
|
||||
// 该 DTO 不包含通知正文、渠道配置、凭证或最后错误原文。
|
||||
type notificationUncertainOutboxItem struct {
|
||||
// ID 是通知 outbox 记录的稳定标识。
|
||||
ID int64 `json:"id"`
|
||||
// ChannelID 是关联通知渠道标识。
|
||||
ChannelID int64 `json:"channel_id"`
|
||||
// OwnerUserID 是渠道所属用户标识,仅管理员查询时返回。
|
||||
OwnerUserID int64 `json:"owner_user_id,omitempty"`
|
||||
// EventType 是通知事件分类。
|
||||
EventType string `json:"event_type"`
|
||||
// AttemptCount 是进入不确定状态前的发送尝试次数。
|
||||
AttemptCount int `json:"attempt_count"`
|
||||
// UncertainAt 是进入不确定状态的 Unix 秒时间戳。
|
||||
UncertainAt int64 `json:"uncertain_at"`
|
||||
// HasError 表示是否存在本地确认错误,但不暴露错误原文。
|
||||
HasError bool `json:"has_error"`
|
||||
}
|
||||
|
||||
// notificationUncertainOutboxResponse 是用户或管理员查询不确定通知的具名响应。
|
||||
type notificationUncertainOutboxResponse struct {
|
||||
// Total 是当前权限范围内的不确定通知总数。
|
||||
Total int `json:"total"`
|
||||
// Items 是按最近进入不确定状态排序的非敏感摘要列表。
|
||||
Items []notificationUncertainOutboxItem `json:"items"`
|
||||
}
|
||||
|
||||
// newNotificationUncertainOutboxResponse 将数据库不确定状态摘要转换为非敏感 HTTP DTO。
|
||||
// includeOwner 仅管理员列表使用,用于展示渠道所属用户但不改变正文脱敏边界。
|
||||
func newNotificationUncertainOutboxResponse(items []db.NotificationUncertainSummary, total int, includeOwner bool) notificationUncertainOutboxResponse {
|
||||
// result 保存不确定通知查询的具名响应。
|
||||
result := notificationUncertainOutboxResponse{Total: total, Items: make([]notificationUncertainOutboxItem, 0, len(items))}
|
||||
// item 保存当前待转换的数据库摘要。
|
||||
for _, item := range items {
|
||||
// responseItem 保存当前摘要对应的非敏感 API 行。
|
||||
responseItem := notificationUncertainOutboxItem{
|
||||
ID: item.ID, ChannelID: item.ChannelID, EventType: item.EventType,
|
||||
AttemptCount: item.AttemptCount, UncertainAt: item.UncertainAt, HasError: item.HasError,
|
||||
}
|
||||
if includeOwner {
|
||||
responseItem.OwnerUserID = item.OwnerUserID
|
||||
}
|
||||
result.Items = append(result.Items, responseItem)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// categoryRecommendationResponse 是商品类目推荐接口的具名响应 DTO。
|
||||
type categoryRecommendationResponse struct {
|
||||
// Success 表示类目推荐是否成功。
|
||||
|
||||
@@ -20,6 +20,7 @@ func (s *Server) mountVersionedSettingsCardNotificationRoutes(r chi.Router) {
|
||||
r.Put("/api/v1/settings/system", s.setSettings)
|
||||
r.Put("/api/v1/settings/system/{key}", s.setSetting)
|
||||
r.Post("/api/v1/settings/ai-models", s.listAIModels)
|
||||
r.Get("/api/v1/admin/notifications/outbox/uncertain", s.listAdminUncertainNotifications)
|
||||
})
|
||||
|
||||
// 普通登录用户可访问账号 AI 设置、用户设置、卡券和通知资源。
|
||||
@@ -49,6 +50,7 @@ func (s *Server) mountVersionedSettingsCardNotificationRoutes(r chi.Router) {
|
||||
r.Delete("/api/v1/notifications/channels/{channel_id}", s.deleteChannel)
|
||||
r.Post("/api/v1/notifications/channels/{channel_id}/test", s.testChannel)
|
||||
r.Get("/api/v1/notifications/messages", s.listMessageNotifications)
|
||||
r.Get("/api/v1/notifications/outbox/uncertain", s.listUncertainNotifications)
|
||||
r.Delete("/api/v1/notifications/messages/account/{cid}", s.deleteAccountNotifications)
|
||||
r.Delete("/api/v1/notifications/messages/{notification_id}", s.deleteMessageNotification)
|
||||
r.Get("/api/v1/notifications/accounts/{cid}/bindings", s.getAccountBindings)
|
||||
|
||||
Reference in new issue
Block a user