阶段十:完成 Go Chat 注释基线清零
This commit is contained in:
1 parent
c9ac336547
commit
a45a82a149
5 files changed
+300
-1851
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -636,3 +636,4 @@ npm --prefix frontend run build
|
|||||||
| 2026-08-15 | 完成阶段 10 第十个 PR 切片“Go internal/adapter 注释基线按领域清零” | 为 adapter 装配、平台运行视图、远端 Token CAPTCHA 流程及其测试补齐函数、变量、字段和常量中文注释;`internal/adapter` 注释基线清零;Adapter 定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/renewal、internal/notify、internal/chat 等领域注释基线 |
|
| 2026-08-15 | 完成阶段 10 第十个 PR 切片“Go internal/adapter 注释基线按领域清零” | 为 adapter 装配、平台运行视图、远端 Token CAPTCHA 流程及其测试补齐函数、变量、字段和常量中文注释;`internal/adapter` 注释基线清零;Adapter 定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/renewal、internal/notify、internal/chat 等领域注释基线 |
|
||||||
| 2026-08-15 | 完成阶段 10 第十一个 PR 切片“Go internal/renewal 注释基线按领域清零” | 为续期冷却、调度器、平台运行凭证范围和相关测试补齐函数、变量、字段及常量中文注释;`internal/renewal` 注释基线清零;Renewal 定向测试、`go test -race ./internal/renewal`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/notify、internal/chat 等领域注释基线 |
|
| 2026-08-15 | 完成阶段 10 第十一个 PR 切片“Go internal/renewal 注释基线按领域清零” | 为续期冷却、调度器、平台运行凭证范围和相关测试补齐函数、变量、字段及常量中文注释;`internal/renewal` 注释基线清零;Renewal 定向测试、`go test -race ./internal/renewal`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/notify、internal/chat 等领域注释基线 |
|
||||||
| 2026-08-15 | 完成阶段 10 第十二个 PR 切片“Go internal/notify 注释基线按领域清零” | 为通知器、渠道与账号绑定、通知 outbox、SMTP 守卫及其测试补齐函数、变量、字段和常量中文注释;`internal/notify` 注释基线清零;Notify 定向测试、`go test -race ./internal/notify`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/chat 领域注释基线 |
|
| 2026-08-15 | 完成阶段 10 第十二个 PR 切片“Go internal/notify 注释基线按领域清零” | 为通知器、渠道与账号绑定、通知 outbox、SMTP 守卫及其测试补齐函数、变量、字段和常量中文注释;`internal/notify` 注释基线清零;Notify 定向测试、`go test -race ./internal/notify`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/chat 领域注释基线 |
|
||||||
|
| 2026-08-15 | 完成阶段 10 第十三个 PR 切片“Go internal/chat 注释基线按领域清零” | 为聊天 repository、消息服务、账号订阅、已读状态、事件广播及其测试补齐函数、变量、字段和常量中文注释;`internal/chat` 注释基线清零;Chat 定向测试、`go test -race ./internal/chat`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:进入非冻结 browser、cmd 与 tools 注释基线清理 |
|
||||||
@@ -46,7 +46,9 @@ func (*fakeRepository) UpdateMessageStatus(_ context.Context, _ string, _ string
|
|||||||
func TestServiceUsesNarrowRepository(t *testing.T) {
|
func TestServiceUsesNarrowRepository(t *testing.T) {
|
||||||
// repository 是只实现聊天所需方法的内存替身。
|
// repository 是只实现聊天所需方法的内存替身。
|
||||||
repository := &fakeRepository{accountIDs: []string{"account-1", "account-2"}}
|
repository := &fakeRepository{accountIDs: []string{"account-1", "account-2"}}
|
||||||
|
// service 保存service,供当前处理流程使用
|
||||||
service := NewWithRepository(repository)
|
service := NewWithRepository(repository)
|
||||||
|
// cancel、err 保存cancel、err,供当前处理流程使用
|
||||||
_, cancel, err := service.Subscribe(context.Background(), 42)
|
_, cancel, err := service.Subscribe(context.Background(), 42)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Subscribe() error = %v", err)
|
t.Fatalf("Subscribe() error = %v", err)
|
||||||
|
|||||||
+187
-37
@@ -16,43 +16,60 @@ import (
|
|||||||
"xianyu-go/internal/db"
|
"xianyu-go/internal/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// HistoryPage 保存History页码,供当前处理流程使用
|
||||||
type HistoryPage struct {
|
type HistoryPage struct {
|
||||||
Messages []db.ChatMessage
|
Messages []db.ChatMessage
|
||||||
HasMore bool
|
HasMore bool
|
||||||
NextCursor int64
|
NextCursor int64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ConversationPage 保存Conversation页码,供当前处理流程使用
|
||||||
type ConversationPage struct {
|
type ConversationPage struct {
|
||||||
HasMore bool
|
HasMore bool
|
||||||
NextCursor int64
|
NextCursor int64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// xianxiaomiAvatar 保存xianxiaomiAvatar,供当前处理流程使用
|
||||||
const xianxiaomiAvatar = "https://img.alicdn.com/imgextra/i2/O1CN01rxBFRr1II3BU0as29_!!6000000000869-2-tps-144-144.png_110x10000.jpg_.webp"
|
const xianxiaomiAvatar = "https://img.alicdn.com/imgextra/i2/O1CN01rxBFRr1II3BU0as29_!!6000000000869-2-tps-144-144.png_110x10000.jpg_.webp"
|
||||||
|
|
||||||
|
// RecordConversationPage 负责RecordConversation页码相关处理。
|
||||||
func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID string, body map[string]any) (ConversationPage, error) {
|
func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID string, body map[string]any) (ConversationPage, error) {
|
||||||
|
// page 保存页码,供当前处理流程使用
|
||||||
page := ConversationPage{HasMore: boolValue(body["hasMore"]), NextCursor: int64Value(body["nextCursor"])}
|
page := ConversationPage{HasMore: boolValue(body["hasMore"]), NextCursor: int64Value(body["nextCursor"])}
|
||||||
|
// items 保存商品列表,供当前处理流程使用
|
||||||
items, _ := body["userConvs"].([]any)
|
items, _ := body["userConvs"].([]any)
|
||||||
|
// item 表示当前遍历过程中的商品
|
||||||
for _, item := range items {
|
for _, item := range items {
|
||||||
|
// wrapper 保存wrapper,供当前处理流程使用
|
||||||
wrapper, _ := item.(map[string]any)
|
wrapper, _ := item.(map[string]any)
|
||||||
|
// conv 保存conv,供当前处理流程使用
|
||||||
conv := wrapper
|
conv := wrapper
|
||||||
if nested, ok := wrapper["singleChatUserConversation"].(map[string]any); ok {
|
if // nested、ok 保存nested、ok,供当前处理流程使用
|
||||||
|
nested, ok := wrapper["singleChatUserConversation"].(map[string]any); ok {
|
||||||
conv = nested
|
conv = nested
|
||||||
}
|
}
|
||||||
|
// single 保存single,供当前处理流程使用
|
||||||
single, _ := conv["singleChatConversation"].(map[string]any)
|
single, _ := conv["singleChatConversation"].(map[string]any)
|
||||||
|
// cid 保存cid,供当前处理流程使用
|
||||||
cid := strings.Split(strings.TrimSpace(fmt.Sprint(single["cid"])), "@")[0]
|
cid := strings.Split(strings.TrimSpace(fmt.Sprint(single["cid"])), "@")[0]
|
||||||
if visible, exists := conv["visible"]; exists && int64Value(visible) == 0 {
|
if // visible、exists 保存visible、exists,供当前处理流程使用
|
||||||
|
visible, exists := conv["visible"]; exists && int64Value(visible) == 0 {
|
||||||
if cid != "" && cid != "<nil>" {
|
if cid != "" && cid != "<nil>" {
|
||||||
_ = s.repository.DeleteSession(ctx, accountID, cid)
|
_ = s.repository.DeleteSession(ctx, accountID, cid)
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
// first 保存first,供当前处理流程使用
|
||||||
first := strings.Split(strings.TrimSpace(fmt.Sprint(single["pairFirst"])), "@")[0]
|
first := strings.Split(strings.TrimSpace(fmt.Sprint(single["pairFirst"])), "@")[0]
|
||||||
|
// second 保存second,供当前处理流程使用
|
||||||
second := strings.Split(strings.TrimSpace(fmt.Sprint(single["pairSecond"])), "@")[0]
|
second := strings.Split(strings.TrimSpace(fmt.Sprint(single["pairSecond"])), "@")[0]
|
||||||
|
// ext 保存ext,供当前处理流程使用
|
||||||
ext := mapValue(single["extension"])
|
ext := mapValue(single["extension"])
|
||||||
if second == "0" && cleanNilString(ext["extUserId"]) != "1400" {
|
if second == "0" && cleanNilString(ext["extUserId"]) != "1400" {
|
||||||
_ = s.repository.DeleteSession(ctx, accountID, cid)
|
_ = s.repository.DeleteSession(ctx, accountID, cid)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
// peerID 保存peerID,供当前处理流程使用
|
||||||
peerID := first
|
peerID := first
|
||||||
if first == myID {
|
if first == myID {
|
||||||
peerID = second
|
peerID = second
|
||||||
@@ -63,7 +80,9 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
|||||||
if cid == "" || cid == "<nil>" || peerID == "" || peerID == "0" || peerID == "<nil>" {
|
if cid == "" || cid == "<nil>" || peerID == "" || peerID == "0" || peerID == "<nil>" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
// lastWrap 保存lastWrap,供当前处理流程使用
|
||||||
lastWrap, _ := conv["lastMessage"].(map[string]any)
|
lastWrap, _ := conv["lastMessage"].(map[string]any)
|
||||||
|
// last 保存last,供当前处理流程使用
|
||||||
last, _ := lastWrap["message"].(map[string]any)
|
last, _ := lastWrap["message"].(map[string]any)
|
||||||
// The conversation endpoint can return empty shells for notification
|
// The conversation endpoint can return empty shells for notification
|
||||||
// recipients. The official web client does not render these as contacts;
|
// recipients. The official web client does not render these as contacts;
|
||||||
@@ -76,12 +95,17 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
|||||||
// another card title. The official web client resolves conversation
|
// another card title. The official web client resolves conversation
|
||||||
// identity separately through pc.user.query, so never persist this field
|
// identity separately through pc.user.query, so never persist this field
|
||||||
// as the session nickname.
|
// as the session nickname.
|
||||||
|
// peerName 保存peer名称,供当前处理流程使用
|
||||||
peerName := ""
|
peerName := ""
|
||||||
|
// custom 保存custom,供当前处理流程使用
|
||||||
custom := map[string]any{}
|
custom := map[string]any{}
|
||||||
|
// extension 保存extension,供当前处理流程使用
|
||||||
extension := mapValue(last["extension"])
|
extension := mapValue(last["extension"])
|
||||||
if content, ok := last["content"].(map[string]any); ok {
|
if // content、ok 保存content、ok,供当前处理流程使用
|
||||||
|
content, ok := last["content"].(map[string]any); ok {
|
||||||
custom, _ = content["custom"].(map[string]any)
|
custom, _ = content["custom"].(map[string]any)
|
||||||
}
|
}
|
||||||
|
// summary 保存summary,供当前处理流程使用
|
||||||
summary := cleanNilString(custom["summary"])
|
summary := cleanNilString(custom["summary"])
|
||||||
if summary == "" {
|
if summary == "" {
|
||||||
summary = cleanNilString(extension["reminderContent"])
|
summary = cleanNilString(extension["reminderContent"])
|
||||||
@@ -90,11 +114,16 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
|||||||
summary = cleanNilString(extension["detailNotice"])
|
summary = cleanNilString(extension["detailNotice"])
|
||||||
}
|
}
|
||||||
if summary == "" {
|
if summary == "" {
|
||||||
if encoded := cleanNilString(custom["data"]); encoded != "" {
|
if // encoded 保存encoded,供当前处理流程使用
|
||||||
|
encoded := cleanNilString(custom["data"]); encoded != "" {
|
||||||
|
// decoded 保存decoded,供当前处理流程使用
|
||||||
var decoded map[string]any
|
var decoded map[string]any
|
||||||
if raw, err := base64.StdEncoding.DecodeString(encoded); err == nil && json.Unmarshal(raw, &decoded) == nil {
|
if // raw、err 保存raw、err,供当前处理流程使用
|
||||||
|
raw, err := base64.StdEncoding.DecodeString(encoded); err == nil && json.Unmarshal(raw, &decoded) == nil {
|
||||||
|
// fallback 保存fallback,供当前处理流程使用
|
||||||
fallback := ""
|
fallback := ""
|
||||||
if textBlock, ok := decoded["text"].(map[string]any); ok {
|
if // textBlock、ok 保存文本Block、ok,供当前处理流程使用
|
||||||
|
textBlock, ok := decoded["text"].(map[string]any); ok {
|
||||||
fallback = cleanNilString(textBlock["text"])
|
fallback = cleanNilString(textBlock["text"])
|
||||||
}
|
}
|
||||||
_, summary = extractMessageContent(decoded, fallback)
|
_, summary = extractMessageContent(decoded, fallback)
|
||||||
@@ -104,34 +133,42 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
|||||||
if summary == "" {
|
if summary == "" {
|
||||||
summary = "暂无消息"
|
summary = "暂无消息"
|
||||||
}
|
}
|
||||||
|
// avatar 保存avatar,供当前处理流程使用
|
||||||
avatar := ""
|
avatar := ""
|
||||||
if peerID == "1400" {
|
if peerID == "1400" {
|
||||||
peerName, avatar = "闲小蜜", xianxiaomiAvatar
|
peerName, avatar = "闲小蜜", xianxiaomiAvatar
|
||||||
}
|
}
|
||||||
|
// modifyTime 保存modify时间,供当前处理流程使用
|
||||||
modifyTime := int64Value(conv["modifyTime"])
|
modifyTime := int64Value(conv["modifyTime"])
|
||||||
|
// lastMessageAt 保存last消息At,供当前处理流程使用
|
||||||
lastMessageAt := int64Value(last["createAt"])
|
lastMessageAt := int64Value(last["createAt"])
|
||||||
if lastMessageAt <= 0 {
|
if lastMessageAt <= 0 {
|
||||||
lastMessageAt = modifyTime
|
lastMessageAt = modifyTime
|
||||||
}
|
}
|
||||||
|
// session 保存会话,供当前处理流程使用
|
||||||
session := db.ChatSession{CookieID: accountID, ChatID: cid, BuyerID: peerID, BuyerName: peerName, BuyerAvatar: avatar,
|
session := db.ChatSession{CookieID: accountID, ChatID: cid, BuyerID: peerID, BuyerName: peerName, BuyerAvatar: avatar,
|
||||||
ItemID: cleanNilString(ext["itemId"]), ItemTitle: cleanNilString(ext["itemTitle"]), LastMessage: summary,
|
ItemID: cleanNilString(ext["itemId"]), ItemTitle: cleanNilString(ext["itemTitle"]), LastMessage: summary,
|
||||||
LastMessageAt: lastMessageAt, UnreadCount: int(int64Value(conv["redPoint"]))}
|
LastMessageAt: lastMessageAt, UnreadCount: int(int64Value(conv["redPoint"]))}
|
||||||
if err := s.repository.UpsertSession(ctx, session); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
err := s.repository.UpsertSession(ctx, session); err != nil {
|
||||||
return page, err
|
return page, err
|
||||||
}
|
}
|
||||||
if err := s.repository.SyncSessionSummary(ctx, accountID, cid, summary, lastMessageAt, modifyTime, session.UnreadCount); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
err := s.repository.SyncSessionSummary(ctx, accountID, cid, summary, lastMessageAt, modifyTime, session.UnreadCount); err != nil {
|
||||||
return page, err
|
return page, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return page, nil
|
return page, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// invalidNicknames 保存invalidNicknames,供当前处理流程使用
|
||||||
var invalidNicknames = map[string]struct{}{
|
var invalidNicknames = map[string]struct{}{
|
||||||
"交易消息": {}, "系统消息": {}, "卡片消息": {}, "我完成了评价": {}, "对方完成了评价": {},
|
"交易消息": {}, "系统消息": {}, "卡片消息": {}, "我完成了评价": {}, "对方完成了评价": {},
|
||||||
"快给ta一个评价吧~": {}, "卖家已发货": {}, "买家已付款": {}, "买家已确认收货": {},
|
"快给ta一个评价吧~": {}, "卖家已发货": {}, "买家已付款": {}, "买家已确认收货": {},
|
||||||
"等待您发货": {}, "超时未付款,系统关闭了订单": {}, "邀您填写售后问卷": {},
|
"等待您发货": {}, "超时未付款,系统关闭了订单": {}, "邀您填写售后问卷": {},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ValidNickname 负责有效Nickname相关处理。
|
||||||
func ValidNickname(value string) bool {
|
func ValidNickname(value string) bool {
|
||||||
value = strings.TrimSpace(value)
|
value = strings.TrimSpace(value)
|
||||||
if value == "" {
|
if value == "" {
|
||||||
@@ -140,17 +177,22 @@ func ValidNickname(value string) bool {
|
|||||||
if strings.Contains(value, "***") {
|
if strings.Contains(value, "***") {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if _, err := strconv.ParseUint(value, 10, 64); err == nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
_, err := strconv.ParseUint(value, 10, 64); err == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
// trimmed 保存trimmed,供当前处理流程使用
|
||||||
trimmed := strings.TrimSuffix(strings.TrimPrefix(value, "["), "]")
|
trimmed := strings.TrimSuffix(strings.TrimPrefix(value, "["), "]")
|
||||||
if _, invalid := invalidNicknames[trimmed]; invalid {
|
if // invalid 保存invalid,供当前处理流程使用
|
||||||
|
_, invalid := invalidNicknames[trimmed]; invalid {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return !strings.Contains(value, "发来一条新消息")
|
return !strings.Contains(value, "发来一条新消息")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cleanNilString 负责cleanNilString相关处理。
|
||||||
func cleanNilString(value any) string {
|
func cleanNilString(value any) string {
|
||||||
|
// text 保存文本,供当前处理流程使用
|
||||||
text := strings.TrimSpace(fmt.Sprint(value))
|
text := strings.TrimSpace(fmt.Sprint(value))
|
||||||
if text == "<nil>" {
|
if text == "<nil>" {
|
||||||
return ""
|
return ""
|
||||||
@@ -158,6 +200,7 @@ func cleanNilString(value any) string {
|
|||||||
return text
|
return text
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Incoming 保存Incoming,供当前处理流程使用
|
||||||
type Incoming struct {
|
type Incoming struct {
|
||||||
AccountID string
|
AccountID string
|
||||||
ChatID string
|
ChatID string
|
||||||
@@ -168,17 +211,20 @@ type Incoming struct {
|
|||||||
Raw map[string]any
|
Raw map[string]any
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Event 保存Event,供当前处理流程使用
|
||||||
type Event struct {
|
type Event struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Message *db.ChatMessage `json:"message,omitempty"`
|
Message *db.ChatMessage `json:"message,omitempty"`
|
||||||
Session *db.ChatSession `json:"session,omitempty"`
|
Session *db.ChatSession `json:"session,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// subscriber 保存subscriber,供当前处理流程使用
|
||||||
type subscriber struct {
|
type subscriber struct {
|
||||||
accounts map[string]struct{}
|
accounts map[string]struct{}
|
||||||
ch chan Event
|
ch chan Event
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Service 保存Service,供当前处理流程使用
|
||||||
type Service struct {
|
type Service struct {
|
||||||
// repository 提供聊天服务所需的最小持久化能力。
|
// repository 提供聊天服务所需的最小持久化能力。
|
||||||
repository Repository
|
repository Repository
|
||||||
@@ -187,6 +233,7 @@ type Service struct {
|
|||||||
subs map[uint64]subscriber
|
subs map[uint64]subscriber
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// New 负责New相关处理。
|
||||||
func New(store *db.Store) *Service {
|
func New(store *db.Store) *Service {
|
||||||
return NewWithRepository(newStoreRepository(store))
|
return NewWithRepository(newStoreRepository(store))
|
||||||
}
|
}
|
||||||
@@ -196,26 +243,33 @@ func NewWithRepository(repository Repository) *Service {
|
|||||||
return &Service{repository: repository, subs: make(map[uint64]subscriber)}
|
return &Service{repository: repository, subs: make(map[uint64]subscriber)}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Subscribe 负责Subscribe相关处理。
|
||||||
func (s *Service) Subscribe(ctx context.Context, userID int64) (<-chan Event, func(), error) {
|
func (s *Service) Subscribe(ctx context.Context, userID int64) (<-chan Event, func(), error) {
|
||||||
accountIDs, err := s.repository.ListOwnedIDs(ctx, userID) // accountIDs 和 err 是用户账号 ID 列表及查询错误。
|
accountIDs, err := s.repository.ListOwnedIDs(ctx, userID) // accountIDs 和 err 是用户账号 ID 列表及查询错误。
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
// allowed 保存allowed,供当前处理流程使用
|
||||||
allowed := make(map[string]struct{}, len(accountIDs))
|
allowed := make(map[string]struct{}, len(accountIDs))
|
||||||
for _, accountID := range accountIDs { // accountID 是当前订阅允许接收事件的账号。
|
for _, accountID := range accountIDs { // accountID 是当前订阅允许接收事件的账号。
|
||||||
allowed[accountID] = struct{}{}
|
allowed[accountID] = struct{}{}
|
||||||
}
|
}
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
s.next++
|
s.next++
|
||||||
|
// id 保存标识,供当前处理流程使用
|
||||||
id := s.next
|
id := s.next
|
||||||
|
// ch 保存ch,供当前处理流程使用
|
||||||
ch := make(chan Event, 128)
|
ch := make(chan Event, 128)
|
||||||
s.subs[id] = subscriber{accounts: allowed, ch: ch}
|
s.subs[id] = subscriber{accounts: allowed, ch: ch}
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
|
// once 保存once,供当前处理流程使用
|
||||||
var once sync.Once
|
var once sync.Once
|
||||||
|
// cancel 保存取消,供当前处理流程使用
|
||||||
cancel := func() {
|
cancel := func() {
|
||||||
once.Do(func() {
|
once.Do(func() {
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
if sub, ok := s.subs[id]; ok {
|
if // sub、ok 保存sub、ok,供当前处理流程使用
|
||||||
|
sub, ok := s.subs[id]; ok {
|
||||||
delete(s.subs, id)
|
delete(s.subs, id)
|
||||||
close(sub.ch)
|
close(sub.ch)
|
||||||
}
|
}
|
||||||
@@ -225,11 +279,14 @@ func (s *Service) Subscribe(ctx context.Context, userID int64) (<-chan Event, fu
|
|||||||
return ch, cancel, nil
|
return ch, cancel, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Publish 负责发布相关处理。
|
||||||
func (s *Service) Publish(accountID string, event Event) {
|
func (s *Service) Publish(accountID string, event Event) {
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
defer s.mu.RUnlock()
|
defer s.mu.RUnlock()
|
||||||
|
// sub 表示当前遍历过程中的sub
|
||||||
for _, sub := range s.subs {
|
for _, sub := range s.subs {
|
||||||
if _, ok := sub.accounts[accountID]; !ok {
|
if // ok 保存ok,供当前处理流程使用
|
||||||
|
_, ok := sub.accounts[accountID]; !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
@@ -241,23 +298,30 @@ func (s *Service) Publish(accountID string, event Event) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RecordIncoming 负责RecordIncoming相关处理。
|
||||||
func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMessage, bool, error) {
|
func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMessage, bool, error) {
|
||||||
if s == nil || s.repository == nil {
|
if s == nil || s.repository == nil {
|
||||||
return nil, false, fmt.Errorf("聊天服务未初始化")
|
return nil, false, fmt.Errorf("聊天服务未初始化")
|
||||||
}
|
}
|
||||||
|
// sentAt 保存sentAt,供当前处理流程使用
|
||||||
sentAt := extractUnixMilli(in.Raw)
|
sentAt := extractUnixMilli(in.Raw)
|
||||||
if sentAt == 0 {
|
if sentAt == 0 {
|
||||||
sentAt = time.Now().UTC().UnixMilli()
|
sentAt = time.Now().UTC().UnixMilli()
|
||||||
}
|
}
|
||||||
|
// key 保存key,供当前处理流程使用
|
||||||
key := extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid")
|
key := extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid")
|
||||||
if key == "" {
|
if key == "" {
|
||||||
|
// raw 保存原始,供当前处理流程使用
|
||||||
raw, _ := json.Marshal(in.Raw)
|
raw, _ := json.Marshal(in.Raw)
|
||||||
|
// digest 保存digest,供当前处理流程使用
|
||||||
digest := sha256.Sum256([]byte(in.AccountID + "\x00" + in.ChatID + "\x00" + in.BuyerID + "\x00" + in.Text + "\x00" + string(raw)))
|
digest := sha256.Sum256([]byte(in.AccountID + "\x00" + in.ChatID + "\x00" + in.BuyerID + "\x00" + in.Text + "\x00" + string(raw)))
|
||||||
key = "in-" + hex.EncodeToString(digest[:16])
|
key = "in-" + hex.EncodeToString(digest[:16])
|
||||||
}
|
}
|
||||||
|
// session 保存会话,供当前处理流程使用
|
||||||
session := db.ChatSession{CookieID: in.AccountID, ChatID: in.ChatID, BuyerID: in.BuyerID,
|
session := db.ChatSession{CookieID: in.AccountID, ChatID: in.ChatID, BuyerID: in.BuyerID,
|
||||||
BuyerName: in.BuyerName, BuyerAvatar: extractString(in.Raw, "avatar", "avatarUrl", "senderAvatar"),
|
BuyerName: in.BuyerName, BuyerAvatar: extractString(in.Raw, "avatar", "avatarUrl", "senderAvatar"),
|
||||||
ItemID: in.ItemID, ItemTitle: extractString(in.Raw, "itemTitle", "title")}
|
ItemID: in.ItemID, ItemTitle: extractString(in.Raw, "itemTitle", "title")}
|
||||||
|
// messageType、content 保存消息Type、content,供当前处理流程使用
|
||||||
messageType, content := extractMessageContent(in.Raw, in.Text)
|
messageType, content := extractMessageContent(in.Raw, in.Text)
|
||||||
if isOfficialSystemMessage(in.Raw, in.BuyerID, in.Text) {
|
if isOfficialSystemMessage(in.Raw, in.BuyerID, in.Text) {
|
||||||
messageType = "system"
|
messageType = "system"
|
||||||
@@ -267,8 +331,10 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess
|
|||||||
session.BuyerAvatar = xianxiaomiAvatar
|
session.BuyerAvatar = xianxiaomiAvatar
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// message 保存消息,供当前处理流程使用
|
||||||
message := db.ChatMessage{MessageKey: key, Direction: "incoming", SenderID: in.BuyerID,
|
message := db.ChatMessage{MessageKey: key, Direction: "incoming", SenderID: in.BuyerID,
|
||||||
SenderName: in.BuyerName, MessageType: messageType, Content: content, Status: "received", SentAt: sentAt}
|
SenderName: in.BuyerName, MessageType: messageType, Content: content, Status: "received", SentAt: sentAt}
|
||||||
|
// stored、inserted、err 保存stored、inserted、err,供当前处理流程使用
|
||||||
stored, inserted, err := s.repository.SaveMessage(ctx, session, message, true)
|
stored, inserted, err := s.repository.SaveMessage(ctx, session, message, true)
|
||||||
if err == nil && inserted {
|
if err == nil && inserted {
|
||||||
s.Publish(in.AccountID, Event{Type: "message.created", Message: stored, Session: &session})
|
s.Publish(in.AccountID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||||
@@ -277,11 +343,17 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess
|
|||||||
}
|
}
|
||||||
|
|
||||||
// RecordHistoryPage normalizes official IM history and stores it idempotently.
|
// RecordHistoryPage normalizes official IM history and stores it idempotently.
|
||||||
|
// RecordHistoryPage 负责RecordHistory页码相关处理。
|
||||||
func (s *Service) RecordHistoryPage(ctx context.Context, accountID, chatID, myID string, session db.ChatSession, body map[string]any) (HistoryPage, error) {
|
func (s *Service) RecordHistoryPage(ctx context.Context, accountID, chatID, myID string, session db.ChatSession, body map[string]any) (HistoryPage, error) {
|
||||||
|
// page 保存页码,供当前处理流程使用
|
||||||
page := HistoryPage{HasMore: boolValue(body["hasMore"]), NextCursor: int64Value(body["nextCursor"])}
|
page := HistoryPage{HasMore: boolValue(body["hasMore"]), NextCursor: int64Value(body["nextCursor"])}
|
||||||
|
// models 保存模型列表,供当前处理流程使用
|
||||||
models, _ := body["userMessageModels"].([]any)
|
models, _ := body["userMessageModels"].([]any)
|
||||||
for i := len(models) - 1; i >= 0; i-- { // official API returns newest first
|
for // i 保存i,供当前处理流程使用
|
||||||
|
i := len(models) - 1; i >= 0; i-- { // official API returns newest first
|
||||||
|
// model 保存模型,供当前处理流程使用
|
||||||
model, _ := models[i].(map[string]any)
|
model, _ := models[i].(map[string]any)
|
||||||
|
// message、ok 保存message、ok,供当前处理流程使用
|
||||||
message, ok := parseHistoryMessage(accountID, chatID, myID, model)
|
message, ok := parseHistoryMessage(accountID, chatID, myID, model)
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
@@ -292,12 +364,14 @@ func (s *Service) RecordHistoryPage(ctx context.Context, accountID, chatID, myID
|
|||||||
session.BuyerID = message.SenderID
|
session.BuyerID = message.SenderID
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// stored、err 保存stored、err,供当前处理流程使用
|
||||||
stored, _, err := s.repository.SaveMessage(ctx, session, message, false)
|
stored, _, err := s.repository.SaveMessage(ctx, session, message, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return page, err
|
return page, err
|
||||||
}
|
}
|
||||||
if message.MessageType == "system" {
|
if message.MessageType == "system" {
|
||||||
if err := s.repository.UpdateMessageType(ctx, accountID, message.MessageKey, "system"); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
err := s.repository.UpdateMessageType(ctx, accountID, message.MessageKey, "system"); err != nil {
|
||||||
return page, err
|
return page, err
|
||||||
}
|
}
|
||||||
stored.MessageType = "system"
|
stored.MessageType = "system"
|
||||||
@@ -307,38 +381,53 @@ func (s *Service) RecordHistoryPage(ctx context.Context, accountID, chatID, myID
|
|||||||
return page, nil
|
return page, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// parseHistoryMessage 负责parseHistory消息相关处理。
|
||||||
func parseHistoryMessage(accountID, chatID, myID string, model map[string]any) (db.ChatMessage, bool) {
|
func parseHistoryMessage(accountID, chatID, myID string, model map[string]any) (db.ChatMessage, bool) {
|
||||||
|
// message 保存消息,供当前处理流程使用
|
||||||
message, _ := model["message"].(map[string]any)
|
message, _ := model["message"].(map[string]any)
|
||||||
if message == nil {
|
if message == nil {
|
||||||
return db.ChatMessage{}, false
|
return db.ChatMessage{}, false
|
||||||
}
|
}
|
||||||
|
// extension 保存extension,供当前处理流程使用
|
||||||
extension := mapValue(message["extension"])
|
extension := mapValue(message["extension"])
|
||||||
|
// senderID 保存senderID,供当前处理流程使用
|
||||||
senderID := strings.Split(strings.TrimSpace(fmt.Sprint(extension["senderUserId"])), "@")[0]
|
senderID := strings.Split(strings.TrimSpace(fmt.Sprint(extension["senderUserId"])), "@")[0]
|
||||||
|
// senderName 保存sender名称,供当前处理流程使用
|
||||||
senderName := strings.TrimSpace(fmt.Sprint(extension["reminderTitle"]))
|
senderName := strings.TrimSpace(fmt.Sprint(extension["reminderTitle"]))
|
||||||
if senderName == "<nil>" {
|
if senderName == "<nil>" {
|
||||||
senderName = ""
|
senderName = ""
|
||||||
}
|
}
|
||||||
|
// key 保存key,供当前处理流程使用
|
||||||
key := strings.TrimSpace(fmt.Sprint(message["messageId"]))
|
key := strings.TrimSpace(fmt.Sprint(message["messageId"]))
|
||||||
if key == "" || key == "<nil>" {
|
if key == "" || key == "<nil>" {
|
||||||
return db.ChatMessage{}, false
|
return db.ChatMessage{}, false
|
||||||
}
|
}
|
||||||
|
// contentMap 保存内容Map,供当前处理流程使用
|
||||||
contentMap, _ := message["content"].(map[string]any)
|
contentMap, _ := message["content"].(map[string]any)
|
||||||
|
// custom 保存custom,供当前处理流程使用
|
||||||
custom, _ := contentMap["custom"].(map[string]any)
|
custom, _ := contentMap["custom"].(map[string]any)
|
||||||
|
// rawContent 保存原始内容,供当前处理流程使用
|
||||||
rawContent := map[string]any{}
|
rawContent := map[string]any{}
|
||||||
if encoded := strings.TrimSpace(fmt.Sprint(custom["data"])); encoded != "" && encoded != "<nil>" {
|
if // encoded 保存encoded,供当前处理流程使用
|
||||||
if decoded, err := base64.StdEncoding.DecodeString(encoded); err == nil {
|
encoded := strings.TrimSpace(fmt.Sprint(custom["data"])); encoded != "" && encoded != "<nil>" {
|
||||||
|
if // decoded、err 保存decoded、err,供当前处理流程使用
|
||||||
|
decoded, err := base64.StdEncoding.DecodeString(encoded); err == nil {
|
||||||
_ = json.Unmarshal(decoded, &rawContent)
|
_ = json.Unmarshal(decoded, &rawContent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// fallback 保存fallback,供当前处理流程使用
|
||||||
fallback := strings.TrimSpace(fmt.Sprint(custom["summary"]))
|
fallback := strings.TrimSpace(fmt.Sprint(custom["summary"]))
|
||||||
if fallback == "<nil>" {
|
if fallback == "<nil>" {
|
||||||
fallback = ""
|
fallback = ""
|
||||||
}
|
}
|
||||||
if textBlock, ok := rawContent["text"].(map[string]any); ok {
|
if // textBlock、ok 保存文本Block、ok,供当前处理流程使用
|
||||||
if text := strings.TrimSpace(fmt.Sprint(textBlock["text"])); text != "" && text != "<nil>" {
|
textBlock, ok := rawContent["text"].(map[string]any); ok {
|
||||||
|
if // text 保存文本,供当前处理流程使用
|
||||||
|
text := strings.TrimSpace(fmt.Sprint(textBlock["text"])); text != "" && text != "<nil>" {
|
||||||
fallback = text
|
fallback = text
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// messageType、content 保存消息Type、content,供当前处理流程使用
|
||||||
messageType, content := extractMessageContent(rawContent, fallback)
|
messageType, content := extractMessageContent(rawContent, fallback)
|
||||||
if isOfficialSystemMessage(rawContent, senderID, fallback) {
|
if isOfficialSystemMessage(rawContent, senderID, fallback) {
|
||||||
messageType = "system"
|
messageType = "system"
|
||||||
@@ -349,6 +438,7 @@ func parseHistoryMessage(accountID, chatID, myID string, model map[string]any) (
|
|||||||
if content == "" {
|
if content == "" {
|
||||||
content = "[系统消息]"
|
content = "[系统消息]"
|
||||||
}
|
}
|
||||||
|
// direction、status 保存direction、status,供当前处理流程使用
|
||||||
direction, status := "incoming", "received"
|
direction, status := "incoming", "received"
|
||||||
if senderID != "" && senderID == strings.TrimSpace(myID) {
|
if senderID != "" && senderID == strings.TrimSpace(myID) {
|
||||||
direction, status = "outgoing", "sent"
|
direction, status = "outgoing", "sent"
|
||||||
@@ -358,11 +448,15 @@ func parseHistoryMessage(accountID, chatID, myID string, model map[string]any) (
|
|||||||
Status: status, SentAt: int64Value(message["createAt"])}, true
|
Status: status, SentAt: int64Value(message["createAt"])}, true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// mapValue 负责map值相关处理。
|
||||||
func mapValue(value any) map[string]any {
|
func mapValue(value any) map[string]any {
|
||||||
if result, ok := value.(map[string]any); ok {
|
if // result、ok 保存result、ok,供当前处理流程使用
|
||||||
|
result, ok := value.(map[string]any); ok {
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
if text, ok := value.(string); ok {
|
if // text、ok 保存text、ok,供当前处理流程使用
|
||||||
|
text, ok := value.(string); ok {
|
||||||
|
// result 保存结果,供当前处理流程使用
|
||||||
var result map[string]any
|
var result map[string]any
|
||||||
if json.Unmarshal([]byte(text), &result) == nil {
|
if json.Unmarshal([]byte(text), &result) == nil {
|
||||||
return result
|
return result
|
||||||
@@ -371,8 +465,10 @@ func mapValue(value any) map[string]any {
|
|||||||
return map[string]any{}
|
return map[string]any{}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// int64Value 负责int64值相关处理。
|
||||||
func int64Value(value any) int64 {
|
func int64Value(value any) int64 {
|
||||||
switch typed := value.(type) {
|
switch // typed 保存typed,供当前处理流程使用
|
||||||
|
typed := value.(type) {
|
||||||
case float64:
|
case float64:
|
||||||
return int64(typed)
|
return int64(typed)
|
||||||
case int64:
|
case int64:
|
||||||
@@ -380,9 +476,11 @@ func int64Value(value any) int64 {
|
|||||||
case int:
|
case int:
|
||||||
return int64(typed)
|
return int64(typed)
|
||||||
case json.Number:
|
case json.Number:
|
||||||
|
// result 保存结果,供当前处理流程使用
|
||||||
result, _ := typed.Int64()
|
result, _ := typed.Int64()
|
||||||
return result
|
return result
|
||||||
case string:
|
case string:
|
||||||
|
// result 保存结果,供当前处理流程使用
|
||||||
var result int64
|
var result int64
|
||||||
_, _ = fmt.Sscan(strings.TrimSpace(typed), &result)
|
_, _ = fmt.Sscan(strings.TrimSpace(typed), &result)
|
||||||
return result
|
return result
|
||||||
@@ -390,8 +488,10 @@ func int64Value(value any) int64 {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// boolValue 负责bool值相关处理。
|
||||||
func boolValue(value any) bool {
|
func boolValue(value any) bool {
|
||||||
switch typed := value.(type) {
|
switch // typed 保存typed,供当前处理流程使用
|
||||||
|
typed := value.(type) {
|
||||||
case bool:
|
case bool:
|
||||||
return typed
|
return typed
|
||||||
case float64:
|
case float64:
|
||||||
@@ -404,42 +504,54 @@ func boolValue(value any) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// extractMessageContent 负责extract消息内容相关处理。
|
||||||
func extractMessageContent(raw map[string]any, fallback string) (string, string) {
|
func extractMessageContent(raw map[string]any, fallback string) (string, string) {
|
||||||
|
// inspect 保存inspect,供当前处理流程使用
|
||||||
var inspect func(any) (string, string)
|
var inspect func(any) (string, string)
|
||||||
inspect = func(value any) (string, string) {
|
inspect = func(value any) (string, string) {
|
||||||
switch typed := value.(type) {
|
switch // typed 保存typed,供当前处理流程使用
|
||||||
|
typed := value.(type) {
|
||||||
case string:
|
case string:
|
||||||
|
// nested 保存nested,供当前处理流程使用
|
||||||
var nested any
|
var nested any
|
||||||
if json.Unmarshal([]byte(typed), &nested) == nil {
|
if json.Unmarshal([]byte(typed), &nested) == nil {
|
||||||
return inspect(nested)
|
return inspect(nested)
|
||||||
}
|
}
|
||||||
case map[string]any:
|
case map[string]any:
|
||||||
|
// contentType 保存内容类型,供当前处理流程使用
|
||||||
contentType := strings.TrimSpace(fmt.Sprint(typed["contentType"]))
|
contentType := strings.TrimSpace(fmt.Sprint(typed["contentType"]))
|
||||||
if contentType == "2" {
|
if contentType == "2" {
|
||||||
if mediaURL := extractString(typed["image"], "url"); mediaURL != "" {
|
if // mediaURL 保存mediaURL,供当前处理流程使用
|
||||||
|
mediaURL := extractString(typed["image"], "url"); mediaURL != "" {
|
||||||
return "image", mediaURL
|
return "image", mediaURL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if contentType == "4" || typed["video"] != nil {
|
if contentType == "4" || typed["video"] != nil {
|
||||||
if mediaURL := extractString(typed["video"], "url", "videoUrl", "playUrl"); mediaURL != "" {
|
if // mediaURL 保存mediaURL,供当前处理流程使用
|
||||||
|
mediaURL := extractString(typed["video"], "url", "videoUrl", "playUrl"); mediaURL != "" {
|
||||||
return "video", mediaURL
|
return "video", mediaURL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// child 表示当前遍历过程中的child
|
||||||
for _, child := range typed {
|
for _, child := range typed {
|
||||||
if kind, mediaURL := inspect(child); mediaURL != "" {
|
if // kind、mediaURL 保存kind、mediaURL,供当前处理流程使用
|
||||||
|
kind, mediaURL := inspect(child); mediaURL != "" {
|
||||||
return kind, mediaURL
|
return kind, mediaURL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case []any:
|
case []any:
|
||||||
|
// child 表示当前遍历过程中的child
|
||||||
for _, child := range typed {
|
for _, child := range typed {
|
||||||
if kind, mediaURL := inspect(child); mediaURL != "" {
|
if // kind、mediaURL 保存kind、mediaURL,供当前处理流程使用
|
||||||
|
kind, mediaURL := inspect(child); mediaURL != "" {
|
||||||
return kind, mediaURL
|
return kind, mediaURL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return "", ""
|
return "", ""
|
||||||
}
|
}
|
||||||
if kind, mediaURL := inspect(raw); mediaURL != "" {
|
if // kind、mediaURL 保存kind、mediaURL,供当前处理流程使用
|
||||||
|
kind, mediaURL := inspect(raw); mediaURL != "" {
|
||||||
return kind, mediaURL
|
return kind, mediaURL
|
||||||
}
|
}
|
||||||
return "text", strings.TrimSpace(fallback)
|
return "text", strings.TrimSpace(fallback)
|
||||||
@@ -449,11 +561,13 @@ func extractMessageContent(raw map[string]any, fallback string) (string, string)
|
|||||||
// protocol metadata, rather than matching a growing list of Chinese prompts.
|
// protocol metadata, rather than matching a growing list of Chinese prompts.
|
||||||
// contentType=14 is a platform notice and contentType=26 is an official trade
|
// contentType=14 is a platform notice and contentType=26 is an official trade
|
||||||
// card. User 1400 is 闲小蜜, whose messages are also not peer chat.
|
// card. User 1400 is 闲小蜜, whose messages are also not peer chat.
|
||||||
|
// isOfficialSystemMessage 负责isOfficial系统消息相关处理。
|
||||||
func isOfficialSystemMessage(raw map[string]any, senderID, fallback string) bool {
|
func isOfficialSystemMessage(raw map[string]any, senderID, fallback string) bool {
|
||||||
if strings.TrimSuffix(strings.TrimSpace(senderID), "@goofish") == "1400" {
|
if strings.TrimSuffix(strings.TrimSpace(senderID), "@goofish") == "1400" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if contentType := findOfficialContentType(raw); contentType == "14" || contentType == "26" {
|
if // contentType 保存内容类型,供当前处理流程使用
|
||||||
|
contentType := findOfficialContentType(raw); contentType == "14" || contentType == "26" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return strings.TrimSpace(fallback) == "发来一条新消息"
|
return strings.TrimSpace(fallback) == "发来一条新消息"
|
||||||
@@ -462,28 +576,36 @@ func isOfficialSystemMessage(raw map[string]any, senderID, fallback string) bool
|
|||||||
// findOfficialContentType walks decoded history content as well as live WS
|
// findOfficialContentType walks decoded history content as well as live WS
|
||||||
// envelopes. History stores the inner content JSON under custom.data, while
|
// envelopes. History stores the inner content JSON under custom.data, while
|
||||||
// live messages expose it under 1.6.3 or 1.10.extJson.
|
// live messages expose it under 1.6.3 or 1.10.extJson.
|
||||||
|
// findOfficialContentType 负责findOfficial内容类型相关处理。
|
||||||
func findOfficialContentType(value any) string {
|
func findOfficialContentType(value any) string {
|
||||||
|
// found 保存found,供当前处理流程使用
|
||||||
var found string
|
var found string
|
||||||
|
// walk 保存walk,供当前处理流程使用
|
||||||
var walk func(any)
|
var walk func(any)
|
||||||
walk = func(current any) {
|
walk = func(current any) {
|
||||||
if found != "" {
|
if found != "" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
switch typed := current.(type) {
|
switch // typed 保存typed,供当前处理流程使用
|
||||||
|
typed := current.(type) {
|
||||||
case string:
|
case string:
|
||||||
|
// nested 保存nested,供当前处理流程使用
|
||||||
var nested any
|
var nested any
|
||||||
if json.Unmarshal([]byte(typed), &nested) == nil {
|
if json.Unmarshal([]byte(typed), &nested) == nil {
|
||||||
walk(nested)
|
walk(nested)
|
||||||
}
|
}
|
||||||
case map[string]any:
|
case map[string]any:
|
||||||
if candidate := strings.TrimSpace(fmt.Sprint(typed["contentType"])); candidate == "14" || candidate == "26" {
|
if // candidate 保存candidate,供当前处理流程使用
|
||||||
|
candidate := strings.TrimSpace(fmt.Sprint(typed["contentType"])); candidate == "14" || candidate == "26" {
|
||||||
found = candidate
|
found = candidate
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// child 表示当前遍历过程中的child
|
||||||
for _, child := range typed {
|
for _, child := range typed {
|
||||||
walk(child)
|
walk(child)
|
||||||
}
|
}
|
||||||
case []any:
|
case []any:
|
||||||
|
// child 表示当前遍历过程中的child
|
||||||
for _, child := range typed {
|
for _, child := range typed {
|
||||||
walk(child)
|
walk(child)
|
||||||
}
|
}
|
||||||
@@ -493,15 +615,20 @@ func findOfficialContentType(value any) string {
|
|||||||
return found
|
return found
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateOutgoing 创建Outgoing。
|
||||||
func (s *Service) CreateOutgoing(ctx context.Context, session db.ChatSession, text string) (*db.ChatMessage, error) {
|
func (s *Service) CreateOutgoing(ctx context.Context, session db.ChatSession, text string) (*db.ChatMessage, error) {
|
||||||
return s.CreateOutgoingMedia(ctx, session, "text", strings.TrimSpace(text))
|
return s.CreateOutgoingMedia(ctx, session, "text", strings.TrimSpace(text))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateOutgoingMedia 创建OutgoingMedia。
|
||||||
func (s *Service) CreateOutgoingMedia(ctx context.Context, session db.ChatSession, messageType, content string) (*db.ChatMessage, error) {
|
func (s *Service) CreateOutgoingMedia(ctx context.Context, session db.ChatSession, messageType, content string) (*db.ChatMessage, error) {
|
||||||
|
// key 保存key,供当前处理流程使用
|
||||||
key := "local-" + randomID()
|
key := "local-" + randomID()
|
||||||
|
// message 保存消息,供当前处理流程使用
|
||||||
message := db.ChatMessage{MessageKey: key, Direction: "outgoing", SenderID: session.CookieID,
|
message := db.ChatMessage{MessageKey: key, Direction: "outgoing", SenderID: session.CookieID,
|
||||||
SenderName: "我", MessageType: messageType, Content: strings.TrimSpace(content), Status: "sending",
|
SenderName: "我", MessageType: messageType, Content: strings.TrimSpace(content), Status: "sending",
|
||||||
SentAt: time.Now().UTC().UnixMilli()}
|
SentAt: time.Now().UTC().UnixMilli()}
|
||||||
|
// stored、err 保存stored、err,供当前处理流程使用
|
||||||
stored, _, err := s.repository.SaveMessage(ctx, session, message, false)
|
stored, _, err := s.repository.SaveMessage(ctx, session, message, false)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
s.Publish(session.CookieID, Event{Type: "message.created", Message: stored, Session: &session})
|
s.Publish(session.CookieID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||||
@@ -511,13 +638,16 @@ func (s *Service) CreateOutgoingMedia(ctx context.Context, session db.ChatSessio
|
|||||||
|
|
||||||
// RecordOutgoingSent captures automatic replies and automation messages. A
|
// RecordOutgoingSent captures automatic replies and automation messages. A
|
||||||
// supplied key correlates a UI pending message and only updates its status.
|
// supplied key correlates a UI pending message and only updates its status.
|
||||||
|
// RecordOutgoingSent 负责RecordOutgoingSent相关处理。
|
||||||
func (s *Service) RecordOutgoingSent(ctx context.Context, session db.ChatSession, key, text string) (*db.ChatMessage, error) {
|
func (s *Service) RecordOutgoingSent(ctx context.Context, session db.ChatSession, key, text string) (*db.ChatMessage, error) {
|
||||||
if strings.TrimSpace(key) != "" {
|
if strings.TrimSpace(key) != "" {
|
||||||
return s.SetOutgoingStatus(ctx, session.CookieID, key, "sent")
|
return s.SetOutgoingStatus(ctx, session.CookieID, key, "sent")
|
||||||
}
|
}
|
||||||
|
// message 保存消息,供当前处理流程使用
|
||||||
message := db.ChatMessage{MessageKey: "sent-" + randomID(), Direction: "outgoing", SenderID: session.CookieID,
|
message := db.ChatMessage{MessageKey: "sent-" + randomID(), Direction: "outgoing", SenderID: session.CookieID,
|
||||||
SenderName: "我", MessageType: "text", Content: strings.TrimSpace(text), Status: "sent",
|
SenderName: "我", MessageType: "text", Content: strings.TrimSpace(text), Status: "sent",
|
||||||
SentAt: time.Now().UTC().UnixMilli()}
|
SentAt: time.Now().UTC().UnixMilli()}
|
||||||
|
// stored、err 保存stored、err,供当前处理流程使用
|
||||||
stored, _, err := s.repository.SaveMessage(ctx, session, message, false)
|
stored, _, err := s.repository.SaveMessage(ctx, session, message, false)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
s.Publish(session.CookieID, Event{Type: "message.created", Message: stored, Session: &session})
|
s.Publish(session.CookieID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||||
@@ -525,7 +655,9 @@ func (s *Service) RecordOutgoingSent(ctx context.Context, session db.ChatSession
|
|||||||
return stored, err
|
return stored, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetOutgoingStatus 设置Outgoing状态。
|
||||||
func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status string) (*db.ChatMessage, error) {
|
func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status string) (*db.ChatMessage, error) {
|
||||||
|
// message、err 保存message、err,供当前处理流程使用
|
||||||
message, err := s.repository.UpdateMessageStatus(ctx, accountID, key, status)
|
message, err := s.repository.UpdateMessageStatus(ctx, accountID, key, status)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
s.Publish(accountID, Event{Type: "message.updated", Message: message})
|
s.Publish(accountID, Event{Type: "message.updated", Message: message})
|
||||||
@@ -533,38 +665,53 @@ func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status
|
|||||||
return message, err
|
return message, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// randomID 负责randomID相关处理。
|
||||||
func randomID() string {
|
func randomID() string {
|
||||||
|
// value 保存值,供当前处理流程使用
|
||||||
var value [16]byte
|
var value [16]byte
|
||||||
if _, err := rand.Read(value[:]); err == nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
_, err := rand.Read(value[:]); err == nil {
|
||||||
return hex.EncodeToString(value[:])
|
return hex.EncodeToString(value[:])
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("%d", time.Now().UTC().UnixNano())
|
return fmt.Sprintf("%d", time.Now().UTC().UnixNano())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// extractString 负责extractString相关处理。
|
||||||
func extractString(value any, keys ...string) string {
|
func extractString(value any, keys ...string) string {
|
||||||
|
// wanted 保存wanted,供当前处理流程使用
|
||||||
wanted := make(map[string]struct{}, len(keys))
|
wanted := make(map[string]struct{}, len(keys))
|
||||||
|
// key 表示当前遍历过程中的key
|
||||||
for _, key := range keys {
|
for _, key := range keys {
|
||||||
wanted[strings.ToLower(key)] = struct{}{}
|
wanted[strings.ToLower(key)] = struct{}{}
|
||||||
}
|
}
|
||||||
|
// walk 保存walk,供当前处理流程使用
|
||||||
var walk func(any) string
|
var walk func(any) string
|
||||||
walk = func(v any) string {
|
walk = func(v any) string {
|
||||||
switch x := v.(type) {
|
switch // x 保存x,供当前处理流程使用
|
||||||
|
x := v.(type) {
|
||||||
case map[string]any:
|
case map[string]any:
|
||||||
|
// key、child 表示当前遍历过程中的key、child
|
||||||
for key, child := range x {
|
for key, child := range x {
|
||||||
if _, ok := wanted[strings.ToLower(key)]; ok {
|
if // ok 保存ok,供当前处理流程使用
|
||||||
if text := strings.TrimSpace(fmt.Sprint(child)); text != "" && text != "<nil>" {
|
_, ok := wanted[strings.ToLower(key)]; ok {
|
||||||
|
if // text 保存文本,供当前处理流程使用
|
||||||
|
text := strings.TrimSpace(fmt.Sprint(child)); text != "" && text != "<nil>" {
|
||||||
return text
|
return text
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// child 表示当前遍历过程中的child
|
||||||
for _, child := range x {
|
for _, child := range x {
|
||||||
if text := walk(child); text != "" {
|
if // text 保存文本,供当前处理流程使用
|
||||||
|
text := walk(child); text != "" {
|
||||||
return text
|
return text
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case []any:
|
case []any:
|
||||||
|
// child 表示当前遍历过程中的child
|
||||||
for _, child := range x {
|
for _, child := range x {
|
||||||
if text := walk(child); text != "" {
|
if // text 保存文本,供当前处理流程使用
|
||||||
|
text := walk(child); text != "" {
|
||||||
return text
|
return text
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -574,8 +721,11 @@ func extractString(value any, keys ...string) string {
|
|||||||
return walk(value)
|
return walk(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// extractUnixMilli 负责extractUnixMilli相关处理。
|
||||||
func extractUnixMilli(raw map[string]any) int64 {
|
func extractUnixMilli(raw map[string]any) int64 {
|
||||||
|
// text 保存文本,供当前处理流程使用
|
||||||
text := extractString(raw, "sendTime", "timestamp", "time", "createdAt")
|
text := extractString(raw, "sendTime", "timestamp", "time", "createdAt")
|
||||||
|
// value 保存值,供当前处理流程使用
|
||||||
var value int64
|
var value int64
|
||||||
_, _ = fmt.Sscan(text, &value)
|
_, _ = fmt.Sscan(text, &value)
|
||||||
if value > 0 && value < 10_000_000_000 {
|
if value > 0 && value < 10_000_000_000 {
|
||||||
|
|||||||
+110
-20
@@ -10,12 +10,18 @@ import (
|
|||||||
"xianyu-go/internal/db"
|
"xianyu-go/internal/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TestRecordHistoryPageParsesDirectionMediaAndDeduplicates 负责TestRecordHistory页码ParsesDirectionMediaAndDeduplicates相关处理。
|
||||||
func TestRecordHistoryPageParsesDirectionMediaAndDeduplicates(t *testing.T) {
|
func TestRecordHistoryPageParsesDirectionMediaAndDeduplicates(t *testing.T) {
|
||||||
|
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||||
store, cleanup := chatTestStore(t)
|
store, cleanup := chatTestStore(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
// service 保存service,供当前处理流程使用
|
||||||
service := New(store)
|
service := New(store)
|
||||||
|
// ctx 保存ctx,供当前处理流程使用
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
// encoded 保存encoded,供当前处理流程使用
|
||||||
encoded := func(value string) string { return base64.StdEncoding.EncodeToString([]byte(value)) }
|
encoded := func(value string) string { return base64.StdEncoding.EncodeToString([]byte(value)) }
|
||||||
|
// body 保存请求体,供当前处理流程使用
|
||||||
body := map[string]any{
|
body := map[string]any{
|
||||||
"hasMore": float64(1), "nextCursor": float64(12345),
|
"hasMore": float64(1), "nextCursor": float64(12345),
|
||||||
"userMessageModels": []any{
|
"userMessageModels": []any{
|
||||||
@@ -23,7 +29,9 @@ func TestRecordHistoryPageParsesDirectionMediaAndDeduplicates(t *testing.T) {
|
|||||||
map[string]any{"message": map[string]any{"messageId": "m1", "createAt": float64(1000), "extension": map[string]any{"senderUserId": "peer@goofish", "reminderTitle": "对方"}, "content": map[string]any{"custom": map[string]any{"data": encoded(`{"contentType":1,"text":{"text":"较早的消息"}}`)}}}},
|
map[string]any{"message": map[string]any{"messageId": "m1", "createAt": float64(1000), "extension": map[string]any{"senderUserId": "peer@goofish", "reminderTitle": "对方"}, "content": map[string]any{"custom": map[string]any{"data": encoded(`{"contentType":1,"text":{"text":"较早的消息"}}`)}}}},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
// session 保存会话,供当前处理流程使用
|
||||||
session := db.ChatSession{CookieID: "account-1", ChatID: "cid", BuyerID: "peer", BuyerName: "对方"}
|
session := db.ChatSession{CookieID: "account-1", ChatID: "cid", BuyerID: "peer", BuyerName: "对方"}
|
||||||
|
// page、err 保存page、err,供当前处理流程使用
|
||||||
page, err := service.RecordHistoryPage(ctx, "account-1", "cid", "self", session, body)
|
page, err := service.RecordHistoryPage(ctx, "account-1", "cid", "self", session, body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -37,10 +45,13 @@ func TestRecordHistoryPageParsesDirectionMediaAndDeduplicates(t *testing.T) {
|
|||||||
if page.Messages[1].Direction != "outgoing" || page.Messages[1].MessageType != "image" || page.Messages[1].Content != "https://img.example/2.jpg" {
|
if page.Messages[1].Direction != "outgoing" || page.Messages[1].MessageType != "image" || page.Messages[1].Content != "https://img.example/2.jpg" {
|
||||||
t.Fatalf("unexpected outgoing image: %+v", page.Messages[1])
|
t.Fatalf("unexpected outgoing image: %+v", page.Messages[1])
|
||||||
}
|
}
|
||||||
if _, err := service.RecordHistoryPage(ctx, "account-1", "cid", "self", session, body); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
_, err := service.RecordHistoryPage(ctx, "account-1", "cid", "self", session, body); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// owner 保存所有者,供当前处理流程使用
|
||||||
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
||||||
|
// rows、err 保存rows、err,供当前处理流程使用
|
||||||
rows, err := store.Chats.ListMessages(ctx, owner.ID, "account-1", "cid", 0, 20)
|
rows, err := store.Chats.ListMessages(ctx, owner.ID, "account-1", "cid", 0, 20)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -52,17 +63,23 @@ func TestRecordHistoryPageParsesDirectionMediaAndDeduplicates(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// name、err 保存name、err,供当前处理流程使用
|
||||||
name, err := store.Chats.LatestUnmaskedPeerName(ctx, "account-1", "cid")
|
name, err := store.Chats.LatestUnmaskedPeerName(ctx, "account-1", "cid")
|
||||||
if err != nil || name != "对方" {
|
if err != nil || name != "对方" {
|
||||||
t.Fatalf("historical nickname=%q err=%v", name, err)
|
t.Fatalf("historical nickname=%q err=%v", name, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRecordHistoryPageClassifiesOfficialCardsAsSystem 负责TestRecordHistory页码ClassifiesOfficial卡密列表As系统相关处理。
|
||||||
func TestRecordHistoryPageClassifiesOfficialCardsAsSystem(t *testing.T) {
|
func TestRecordHistoryPageClassifiesOfficialCardsAsSystem(t *testing.T) {
|
||||||
|
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||||
store, cleanup := chatTestStore(t)
|
store, cleanup := chatTestStore(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
// service 保存service,供当前处理流程使用
|
||||||
service := New(store)
|
service := New(store)
|
||||||
|
// encoded 保存encoded,供当前处理流程使用
|
||||||
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26,"dxCard":{"item":{"main":{"exContent":{"title":"我已拍下,待付款"}}}}}`))
|
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26,"dxCard":{"item":{"main":{"exContent":{"title":"我已拍下,待付款"}}}}}`))
|
||||||
|
// body 保存请求体,供当前处理流程使用
|
||||||
body := map[string]any{"userMessageModels": []any{
|
body := map[string]any{"userMessageModels": []any{
|
||||||
map[string]any{"message": map[string]any{
|
map[string]any{"message": map[string]any{
|
||||||
"messageId": "official-card", "createAt": float64(3000),
|
"messageId": "official-card", "createAt": float64(3000),
|
||||||
@@ -70,13 +87,16 @@ func TestRecordHistoryPageClassifiesOfficialCardsAsSystem(t *testing.T) {
|
|||||||
"content": map[string]any{"custom": map[string]any{"data": encoded, "summary": "[我已拍下,待付款]"}},
|
"content": map[string]any{"custom": map[string]any{"data": encoded, "summary": "[我已拍下,待付款]"}},
|
||||||
}},
|
}},
|
||||||
}}
|
}}
|
||||||
|
// session 保存会话,供当前处理流程使用
|
||||||
session := db.ChatSession{CookieID: "account-1", ChatID: "official", BuyerID: "peer", BuyerName: "真实昵称"}
|
session := db.ChatSession{CookieID: "account-1", ChatID: "official", BuyerID: "peer", BuyerName: "真实昵称"}
|
||||||
if _, _, err := store.Chats.SaveMessage(context.Background(), session, db.ChatMessage{
|
if // err 保存err,供当前处理流程使用
|
||||||
|
_, _, err := store.Chats.SaveMessage(context.Background(), session, db.ChatMessage{
|
||||||
MessageKey: "official-card", Direction: "incoming", SenderID: "peer", SenderName: "真实昵称",
|
MessageKey: "official-card", Direction: "incoming", SenderID: "peer", SenderName: "真实昵称",
|
||||||
MessageType: "text", Content: "[我已拍下,待付款]", Status: "received", SentAt: 3000,
|
MessageType: "text", Content: "[我已拍下,待付款]", Status: "received", SentAt: 3000,
|
||||||
}, false); err != nil {
|
}, false); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// page、err 保存page、err,供当前处理流程使用
|
||||||
page, err := service.RecordHistoryPage(context.Background(), "account-1", "official", "self", session, body)
|
page, err := service.RecordHistoryPage(context.Background(), "account-1", "official", "self", session, body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -89,10 +109,14 @@ func TestRecordHistoryPageClassifiesOfficialCardsAsSystem(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRecordIncomingClassifiesXianxiaomiAndPlaceholder 负责TestRecordIncomingClassifiesXianxiaomiAndPlaceholder相关处理。
|
||||||
func TestRecordIncomingClassifiesXianxiaomiAndPlaceholder(t *testing.T) {
|
func TestRecordIncomingClassifiesXianxiaomiAndPlaceholder(t *testing.T) {
|
||||||
|
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||||
store, cleanup := chatTestStore(t)
|
store, cleanup := chatTestStore(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
// service 保存service,供当前处理流程使用
|
||||||
service := New(store)
|
service := New(store)
|
||||||
|
// message、inserted、err 保存message、inserted、err,供当前处理流程使用
|
||||||
message, inserted, err := service.RecordIncoming(context.Background(), Incoming{
|
message, inserted, err := service.RecordIncoming(context.Background(), Incoming{
|
||||||
AccountID: "account-1", ChatID: "xiaomi", BuyerID: "1400@goofish",
|
AccountID: "account-1", ChatID: "xiaomi", BuyerID: "1400@goofish",
|
||||||
BuyerName: "闲小蜜发来一条新消息", Text: "邀您填写售后问卷",
|
BuyerName: "闲小蜜发来一条新消息", Text: "邀您填写售后问卷",
|
||||||
@@ -106,14 +130,20 @@ func TestRecordIncomingClassifiesXianxiaomiAndPlaceholder(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRecordConversationPageImportsHistoricalContacts 负责TestRecordConversation页码ImportsHistoricalContacts相关处理。
|
||||||
func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
|
func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
|
||||||
|
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||||
store, cleanup := chatTestStore(t)
|
store, cleanup := chatTestStore(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
// service 保存service,供当前处理流程使用
|
||||||
service := New(store)
|
service := New(store)
|
||||||
|
// encoded 保存encoded,供当前处理流程使用
|
||||||
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":1,"text":{"text":"历史消息"}}`))
|
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":1,"text":{"text":"历史消息"}}`))
|
||||||
if err := store.Chats.UpsertSession(context.Background(), db.ChatSession{CookieID: "account-1", ChatID: "history-cid", BuyerID: "peer-9", LastMessage: "错误的新摘要", LastMessageAt: 987654}); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
err := store.Chats.UpsertSession(context.Background(), db.ChatSession{CookieID: "account-1", ChatID: "history-cid", BuyerID: "peer-9", LastMessage: "错误的新摘要", LastMessageAt: 987654}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// body 保存请求体,供当前处理流程使用
|
||||||
body := map[string]any{"hasMore": true, "nextCursor": float64(888), "userConvs": []any{
|
body := map[string]any{"hasMore": true, "nextCursor": float64(888), "userConvs": []any{
|
||||||
map[string]any{"singleChatUserConversation": map[string]any{
|
map[string]any{"singleChatUserConversation": map[string]any{
|
||||||
"singleChatConversation": map[string]any{"cid": "history-cid@goofish", "pairFirst": "self@goofish", "pairSecond": "peer-9@goofish", "extension": `{"itemTitle":"旧商品"}`},
|
"singleChatConversation": map[string]any{"cid": "history-cid@goofish", "pairFirst": "self@goofish", "pairSecond": "peer-9@goofish", "extension": `{"itemTitle":"旧商品"}`},
|
||||||
@@ -121,6 +151,7 @@ func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
|
|||||||
"modifyTime": float64(987654), "redPoint": float64(2),
|
"modifyTime": float64(987654), "redPoint": float64(2),
|
||||||
}},
|
}},
|
||||||
}}
|
}}
|
||||||
|
// page、err 保存page、err,供当前处理流程使用
|
||||||
page, err := service.RecordConversationPage(context.Background(), "account-1", "self", body)
|
page, err := service.RecordConversationPage(context.Background(), "account-1", "self", body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -128,7 +159,9 @@ func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
|
|||||||
if !page.HasMore || page.NextCursor != 888 {
|
if !page.HasMore || page.NextCursor != 888 {
|
||||||
t.Fatalf("unexpected page: %+v", page)
|
t.Fatalf("unexpected page: %+v", page)
|
||||||
}
|
}
|
||||||
|
// owner 保存所有者,供当前处理流程使用
|
||||||
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
|
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
|
||||||
|
// rows、err 保存rows、err,供当前处理流程使用
|
||||||
rows, err := store.Chats.ListSessions(context.Background(), owner.ID, "account-1", 20)
|
rows, err := store.Chats.ListSessions(context.Background(), owner.ID, "account-1", 20)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -141,17 +174,24 @@ func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions 负责TestRecordConversation页码HandlesXianxiaomiAndRemovesInvisibleSessions相关处理。
|
||||||
func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *testing.T) {
|
func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *testing.T) {
|
||||||
|
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||||
store, cleanup := chatTestStore(t)
|
store, cleanup := chatTestStore(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
// ctx 保存ctx,供当前处理流程使用
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
// service 保存service,供当前处理流程使用
|
||||||
service := New(store)
|
service := New(store)
|
||||||
if err := store.Chats.UpsertSession(ctx, db.ChatSession{CookieID: "account-1", ChatID: "hidden", BuyerID: "peer", LastMessage: "暂无消息"}); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
err := store.Chats.UpsertSession(ctx, db.ChatSession{CookieID: "account-1", ChatID: "hidden", BuyerID: "peer", LastMessage: "暂无消息"}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := store.Chats.UpsertSession(ctx, db.ChatSession{CookieID: "account-1", ChatID: "platform", BuyerID: "900", LastMessage: "暂无消息"}); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
err := store.Chats.UpsertSession(ctx, db.ChatSession{CookieID: "account-1", ChatID: "platform", BuyerID: "900", LastMessage: "暂无消息"}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// body 保存请求体,供当前处理流程使用
|
||||||
body := map[string]any{"userConvs": []any{
|
body := map[string]any{"userConvs": []any{
|
||||||
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(0), "singleChatConversation": map[string]any{"cid": "hidden@goofish"}}},
|
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(0), "singleChatConversation": map[string]any{"cid": "hidden@goofish"}}},
|
||||||
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "singleChatConversation": map[string]any{"cid": "platform@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "900"}}}},
|
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "singleChatConversation": map[string]any{"cid": "platform@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "900"}}}},
|
||||||
@@ -159,10 +199,13 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t
|
|||||||
"singleChatConversation": map[string]any{"cid": "xiaomi@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "1400"}},
|
"singleChatConversation": map[string]any{"cid": "xiaomi@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "1400"}},
|
||||||
"lastMessage": map[string]any{"message": map[string]any{"extension": map[string]any{"senderUserId": "1400@goofish", "reminderTitle": "闲小蜜发来一条新消息"}, "content": map[string]any{"custom": map[string]any{"summary": "邀您填写售后问卷"}}}}}},
|
"lastMessage": map[string]any{"message": map[string]any{"extension": map[string]any{"senderUserId": "1400@goofish", "reminderTitle": "闲小蜜发来一条新消息"}, "content": map[string]any{"custom": map[string]any{"summary": "邀您填写售后问卷"}}}}}},
|
||||||
}}
|
}}
|
||||||
if _, err := service.RecordConversationPage(ctx, "account-1", "self", body); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
_, err := service.RecordConversationPage(ctx, "account-1", "self", body); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// owner 保存所有者,供当前处理流程使用
|
||||||
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
||||||
|
// rows、err 保存rows、err,供当前处理流程使用
|
||||||
rows, err := store.Chats.ListSessions(ctx, owner.ID, "account-1", 20)
|
rows, err := store.Chats.ListSessions(ctx, owner.ID, "account-1", 20)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -172,10 +215,14 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRecordConversationPageSkipsEmptyConversationShells 负责TestRecordConversation页码SkipsEmptyConversationShells相关处理。
|
||||||
func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) {
|
func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) {
|
||||||
|
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||||
store, cleanup := chatTestStore(t)
|
store, cleanup := chatTestStore(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
// service 保存service,供当前处理流程使用
|
||||||
service := New(store)
|
service := New(store)
|
||||||
|
// body 保存请求体,供当前处理流程使用
|
||||||
body := map[string]any{"userConvs": []any{
|
body := map[string]any{"userConvs": []any{
|
||||||
map[string]any{"singleChatUserConversation": map[string]any{
|
map[string]any{"singleChatUserConversation": map[string]any{
|
||||||
"singleChatConversation": map[string]any{"cid": "empty@goofish", "pairFirst": "self@goofish", "pairSecond": "69@goofish"},
|
"singleChatConversation": map[string]any{"cid": "empty@goofish", "pairFirst": "self@goofish", "pairSecond": "69@goofish"},
|
||||||
@@ -187,10 +234,13 @@ func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) {
|
|||||||
}},
|
}},
|
||||||
}},
|
}},
|
||||||
}}
|
}}
|
||||||
if _, err := service.RecordConversationPage(context.Background(), "account-1", "self", body); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
_, err := service.RecordConversationPage(context.Background(), "account-1", "self", body); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// owner 保存所有者,供当前处理流程使用
|
||||||
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
|
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
|
||||||
|
// rows、err 保存rows、err,供当前处理流程使用
|
||||||
rows, err := store.Chats.ListSessions(context.Background(), owner.ID, "account-1", 20)
|
rows, err := store.Chats.ListSessions(context.Background(), owner.ID, "account-1", 20)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -200,22 +250,32 @@ func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestDeleteEmptySessionsRemovesGhostsButKeepsRealConversation 负责TestDeleteEmptySessionsRemovesGhostsButKeepsRealConversation相关处理。
|
||||||
func TestDeleteEmptySessionsRemovesGhostsButKeepsRealConversation(t *testing.T) {
|
func TestDeleteEmptySessionsRemovesGhostsButKeepsRealConversation(t *testing.T) {
|
||||||
|
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||||
store, cleanup := chatTestStore(t)
|
store, cleanup := chatTestStore(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
// ctx 保存ctx,供当前处理流程使用
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
// ghost 保存ghost,供当前处理流程使用
|
||||||
ghost := db.ChatSession{CookieID: "account-1", ChatID: "ghost", BuyerID: "peer-ghost", LastMessage: "暂无消息", LastMessageAt: 100}
|
ghost := db.ChatSession{CookieID: "account-1", ChatID: "ghost", BuyerID: "peer-ghost", LastMessage: "暂无消息", LastMessageAt: 100}
|
||||||
if err := store.Chats.UpsertSession(ctx, ghost); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
err := store.Chats.UpsertSession(ctx, ghost); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// real 保存real,供当前处理流程使用
|
||||||
real := db.ChatSession{CookieID: "account-1", ChatID: "real", BuyerID: "peer-real", LastMessage: "暂无消息", LastMessageAt: 200}
|
real := db.ChatSession{CookieID: "account-1", ChatID: "real", BuyerID: "peer-real", LastMessage: "暂无消息", LastMessageAt: 200}
|
||||||
if _, _, err := store.Chats.SaveMessage(ctx, real, db.ChatMessage{MessageKey: "real-1", Direction: "incoming", SenderID: "peer-real", SenderName: "真实用户", MessageType: "text", Content: "真实消息", Status: "received", SentAt: 200}, false); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
_, _, err := store.Chats.SaveMessage(ctx, real, db.ChatMessage{MessageKey: "real-1", Direction: "incoming", SenderID: "peer-real", SenderName: "真实用户", MessageType: "text", Content: "真实消息", Status: "received", SentAt: 200}, false); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := store.Chats.DeleteEmptySessions(ctx, "account-1"); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
err := store.Chats.DeleteEmptySessions(ctx, "account-1"); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// owner 保存所有者,供当前处理流程使用
|
||||||
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
||||||
|
// rows、err 保存rows、err,供当前处理流程使用
|
||||||
rows, err := store.Chats.ListSessions(ctx, owner.ID, "account-1", 20)
|
rows, err := store.Chats.ListSessions(ctx, owner.ID, "account-1", 20)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -225,7 +285,9 @@ func TestDeleteEmptySessionsRemovesGhostsButKeepsRealConversation(t *testing.T)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestValidNicknameRejectsSystemReminderTitles 负责Test有效NicknameRejects系统ReminderTitles相关处理。
|
||||||
func TestValidNicknameRejectsSystemReminderTitles(t *testing.T) {
|
func TestValidNicknameRejectsSystemReminderTitles(t *testing.T) {
|
||||||
|
// value 表示当前遍历过程中的值
|
||||||
for _, value := range []string{"", "203591535", "x***3", "快给ta一个评价吧~", "[卖家已发货]", "闲小蜜发来一条新消息"} {
|
for _, value := range []string{"", "203591535", "x***3", "快给ta一个评价吧~", "[卖家已发货]", "闲小蜜发来一条新消息"} {
|
||||||
if ValidNickname(value) {
|
if ValidNickname(value) {
|
||||||
t.Fatalf("system reminder accepted as nickname: %q", value)
|
t.Fatalf("system reminder accepted as nickname: %q", value)
|
||||||
@@ -236,35 +298,47 @@ func TestValidNicknameRejectsSystemReminderTitles(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestIncomingMessagePersistsDeduplicatesAndPublishesByOwner 负责TestIncoming消息PersistsDeduplicatesAndPublishesBy所有者相关处理。
|
||||||
func TestIncomingMessagePersistsDeduplicatesAndPublishesByOwner(t *testing.T) {
|
func TestIncomingMessagePersistsDeduplicatesAndPublishesByOwner(t *testing.T) {
|
||||||
|
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||||
store, cleanup := chatTestStore(t)
|
store, cleanup := chatTestStore(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
// ctx 保存ctx,供当前处理流程使用
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
// owner 保存所有者,供当前处理流程使用
|
||||||
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
||||||
|
// other 保存other,供当前处理流程使用
|
||||||
other, _ := store.Users.GetByUsername(ctx, "other")
|
other, _ := store.Users.GetByUsername(ctx, "other")
|
||||||
|
// service 保存service,供当前处理流程使用
|
||||||
service := New(store)
|
service := New(store)
|
||||||
|
// ownerEvents、cancelOwner、err 保存所有者Events、cancelOwner、err,供当前处理流程使用
|
||||||
ownerEvents, cancelOwner, err := service.Subscribe(ctx, owner.ID)
|
ownerEvents, cancelOwner, err := service.Subscribe(ctx, owner.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer cancelOwner()
|
defer cancelOwner()
|
||||||
|
// otherEvents、cancelOther、err 保存otherEvents、cancelOther、err,供当前处理流程使用
|
||||||
otherEvents, cancelOther, err := service.Subscribe(ctx, other.ID)
|
otherEvents, cancelOther, err := service.Subscribe(ctx, other.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer cancelOther()
|
defer cancelOther()
|
||||||
|
|
||||||
|
// incoming 保存incoming,供当前处理流程使用
|
||||||
incoming := Incoming{AccountID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家甲",
|
incoming := Incoming{AccountID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家甲",
|
||||||
Text: "你好", ItemID: "item-1", Raw: map[string]any{"messageId": "platform-1", "sendTime": int64(1234567890000)}}
|
Text: "你好", ItemID: "item-1", Raw: map[string]any{"messageId": "platform-1", "sendTime": int64(1234567890000)}}
|
||||||
|
// message、inserted、err 保存message、inserted、err,供当前处理流程使用
|
||||||
message, inserted, err := service.RecordIncoming(ctx, incoming)
|
message, inserted, err := service.RecordIncoming(ctx, incoming)
|
||||||
if err != nil || !inserted || message.MessageKey != "platform-1" {
|
if err != nil || !inserted || message.MessageKey != "platform-1" {
|
||||||
t.Fatalf("message=%+v inserted=%v err=%v", message, inserted, err)
|
t.Fatalf("message=%+v inserted=%v err=%v", message, inserted, err)
|
||||||
}
|
}
|
||||||
if _, inserted, err := service.RecordIncoming(ctx, incoming); err != nil || inserted {
|
if // inserted、err 保存inserted、err,供当前处理流程使用
|
||||||
|
_, inserted, err := service.RecordIncoming(ctx, incoming); err != nil || inserted {
|
||||||
t.Fatalf("duplicate inserted=%v err=%v", inserted, err)
|
t.Fatalf("duplicate inserted=%v err=%v", inserted, err)
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case event := <-ownerEvents:
|
case // event 保存event,供当前处理流程使用
|
||||||
|
event := <-ownerEvents:
|
||||||
if event.Type != "message.created" || event.Message.MessageKey != "platform-1" {
|
if event.Type != "message.created" || event.Message.MessageKey != "platform-1" {
|
||||||
t.Fatalf("event=%+v", event)
|
t.Fatalf("event=%+v", event)
|
||||||
}
|
}
|
||||||
@@ -272,45 +346,61 @@ func TestIncomingMessagePersistsDeduplicatesAndPublishesByOwner(t *testing.T) {
|
|||||||
t.Fatal("owner did not receive event")
|
t.Fatal("owner did not receive event")
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case event := <-otherEvents:
|
case // event 保存event,供当前处理流程使用
|
||||||
|
event := <-otherEvents:
|
||||||
t.Fatalf("other owner leaked event: %+v", event)
|
t.Fatalf("other owner leaked event: %+v", event)
|
||||||
case <-time.After(30 * time.Millisecond):
|
case <-time.After(30 * time.Millisecond):
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestExtractMessageContentSupportsImageAndVideo 负责TestExtract消息内容Supports图片AndVideo相关处理。
|
||||||
func TestExtractMessageContentSupportsImageAndVideo(t *testing.T) {
|
func TestExtractMessageContentSupportsImageAndVideo(t *testing.T) {
|
||||||
|
// imageRaw 保存图片原始,供当前处理流程使用
|
||||||
imageRaw := map[string]any{"payload": `{"contentType":2,"image":{"pics":[{"url":"https://cdn/image.jpg"}]}}`}
|
imageRaw := map[string]any{"payload": `{"contentType":2,"image":{"pics":[{"url":"https://cdn/image.jpg"}]}}`}
|
||||||
if kind, content := extractMessageContent(imageRaw, "[图片]"); kind != "image" || content != "https://cdn/image.jpg" {
|
if // kind、content 保存kind、content,供当前处理流程使用
|
||||||
|
kind, content := extractMessageContent(imageRaw, "[图片]"); kind != "image" || content != "https://cdn/image.jpg" {
|
||||||
t.Fatalf("image kind=%q content=%q", kind, content)
|
t.Fatalf("image kind=%q content=%q", kind, content)
|
||||||
}
|
}
|
||||||
|
// videoRaw 保存video原始,供当前处理流程使用
|
||||||
videoRaw := map[string]any{"content": map[string]any{"video": map[string]any{"playUrl": "https://cdn/video.mp4"}}}
|
videoRaw := map[string]any{"content": map[string]any{"video": map[string]any{"playUrl": "https://cdn/video.mp4"}}}
|
||||||
if kind, content := extractMessageContent(videoRaw, "[视频]"); kind != "video" || content != "https://cdn/video.mp4" {
|
if // kind、content 保存kind、content,供当前处理流程使用
|
||||||
|
kind, content := extractMessageContent(videoRaw, "[视频]"); kind != "video" || content != "https://cdn/video.mp4" {
|
||||||
t.Fatalf("video kind=%q content=%q", kind, content)
|
t.Fatalf("video kind=%q content=%q", kind, content)
|
||||||
}
|
}
|
||||||
if kind, content := extractMessageContent(nil, " 你好 "); kind != "text" || content != "你好" {
|
if // kind、content 保存kind、content,供当前处理流程使用
|
||||||
|
kind, content := extractMessageContent(nil, " 你好 "); kind != "text" || content != "你好" {
|
||||||
t.Fatalf("text kind=%q content=%q", kind, content)
|
t.Fatalf("text kind=%q content=%q", kind, content)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// chatTestStore 负责聊天TestStore相关处理。
|
||||||
func chatTestStore(t *testing.T) (*db.Store, func()) {
|
func chatTestStore(t *testing.T) (*db.Store, func()) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
// database、dialect、err 保存database、dialect、err,供当前处理流程使用
|
||||||
database, dialect, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "chat.db"))
|
database, dialect, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "chat.db"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// store 保存store,供当前处理流程使用
|
||||||
store := db.NewStore(database, dialect)
|
store := db.NewStore(database, dialect)
|
||||||
if ok, err := store.Users.Create(context.Background(), "owner", "[email protected]", "pw"); err != nil || !ok {
|
if // ok、err 保存ok、err,供当前处理流程使用
|
||||||
|
ok, err := store.Users.Create(context.Background(), "owner", "[email protected]", "pw"); err != nil || !ok {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if ok, err := store.Users.Create(context.Background(), "other", "[email protected]", "pw"); err != nil || !ok {
|
if // ok、err 保存ok、err,供当前处理流程使用
|
||||||
|
ok, err := store.Users.Create(context.Background(), "other", "[email protected]", "pw"); err != nil || !ok {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// owner 保存所有者,供当前处理流程使用
|
||||||
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
|
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
|
||||||
|
// other 保存other,供当前处理流程使用
|
||||||
other, _ := store.Users.GetByUsername(context.Background(), "other")
|
other, _ := store.Users.GetByUsername(context.Background(), "other")
|
||||||
if err := store.Cookies.Save(context.Background(), "account-1", "unb=1", owner.ID); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
err := store.Cookies.Save(context.Background(), "account-1", "unb=1", owner.ID); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := store.Cookies.Save(context.Background(), "account-2", "unb=2", other.ID); err != nil {
|
if // err 保存err,供当前处理流程使用
|
||||||
|
err := store.Cookies.Save(context.Background(), "account-2", "unb=2", other.ID); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return store, func() { _ = database.Close() }
|
return store, func() { _ = database.Close() }
|
||||||
|
|||||||
Reference in new issue
Block a user