修复聊天状态并完善风控浏览器诊断
修复内容: - 持久化聊天消息已读状态与未读边界,过滤系统通知红点,修正实时消息 ID、已读回执和前端徽标显示 - 完善账号级任务、商品接口和消息调度联动,补充相关服务端与引擎测试 - 新增 token 风控诊断包,保存页面、截图、Frame、选择器、网络事件和完整指纹信息 - 规范化无头 Chromium 的 User-Agent 与 Client Hints,覆盖 Playwright 主引擎和直接 CDP 备用引擎 - 增加可选证书错误兼容开关、真实 Chromium 指纹集成测试,并同步冻结规范 - 新增 SQLite、MySQL、Postgres 聊天状态迁移并重新构建嵌入式前端
This commit is contained in:
1 parent
1185551018
commit
ecfe43b5a4
43 files changed
+2244
-113
No files matched your search
@@ -207,6 +207,17 @@ Playwright 主引擎
|
||||
- `CAPTCHA_REAL_MOUSE=true` 在当前 Go/Docker 实现中只记录物理鼠标不可用,并继续备用逻辑;不得假装已启用物理鼠标。
|
||||
- `CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED` 默认为启用。
|
||||
- 备用引擎成功返回的引擎标识保持为 `drissionpage`,虽然底层实现是直接 Chromium + CDP。
|
||||
- `CAPTCHA_IGNORE_CERT_ERRORS` 默认关闭。仅当运行环境存在 TLS 检查代理、且诊断明确记录
|
||||
Alibaba 风控资源出现 `ERR_CERT_AUTHORITY_INVALID` 时,才允许显式设为 `true`;此时主引擎和
|
||||
备用 Chromium 都追加 `--ignore-certificate-errors`,HTTP 客户端仍保持正常证书校验。该开关
|
||||
必须记录在部署配置中,不能默认开启或静默改变。
|
||||
- 初始化时必须从随包 Chromium 实测 UA 和 Client Hints。无头上下文只允许把 legacy UA 中的
|
||||
`HeadlessChrome/<实际版本>` 规范化为 `Chrome/<相同实际版本>`;不得伪造版本、操作系统或移动端
|
||||
状态。有头上下文不覆盖 Chromium 原生 UA。Playwright 主引擎必须同时使用 context `userAgent`
|
||||
和导航前保持连接的页面级 `Emulation.setUserAgentOverride`,后者携带从实际 Chromium 读取并去除
|
||||
无头品牌、去重后的 `userAgentMetadata`;只设置 context `userAgent` 不合格,因为其默认
|
||||
`Sec-CH-UA` 和 `navigator.userAgentData` 仍可能包含 `HeadlessChrome`。非浏览器 HTTP 请求使用同一份
|
||||
规范化运行时指纹。
|
||||
|
||||
## 7. 备用引擎行为
|
||||
|
||||
@@ -217,6 +228,8 @@ Playwright 主引擎
|
||||
- 启动前清理现有 singleton 文件和 `DevToolsActivePort`,退出后再次清理 singleton 文件。
|
||||
- 保留 `--remote-debugging-port=0`、`--window-size=1920,1080`、`--lang=zh-CN`、`--disable-blink-features=AutomationControlled` 等现有启动参数。
|
||||
- headless 时使用 `--headless=new`。
|
||||
- headless 时必须在导航前通过 `--user-agent` 应用同版本、已去除 `HeadlessChrome` 标记的运行时 UA;
|
||||
有头模式不得追加该覆盖。Chromium 原生 Client Hints 必须继续保留,且不得出现 `HeadlessChrome`。
|
||||
- 默认总超时为 `25s`,可由现有环境变量控制;导航超时为 `15s`。
|
||||
|
||||
备用距离规则固定如下:
|
||||
@@ -246,6 +259,8 @@ Playwright 主引擎
|
||||
- 最终 `left`、最终 class 或最终 X 偏移。
|
||||
- 失败时的按钮 style/class、轨道 class、可见重试选择器和重试文本。
|
||||
- 恢复方式是 `click` 还是 `reload`、所用选择器以及是否重新归位。
|
||||
- 诊断包的 `page_state` 必须保留页面实际看到的 `navigator.userAgent`、`navigator.webdriver`、
|
||||
`navigator.userAgentData` 基础字段及可读取的 high-entropy values,用于识别 UA/Client Hints 矛盾。
|
||||
- 自动滑块最终失败时,错误文本和 `token 风控滑块处理失败` 日志的 `verification_url` 字段必须包含最后实际使用的完整验证地址(包括 query),供用户复制到本机浏览器手动验证。此字段是仅在最终失败时提供的人工接管信息;常规页面/frame 诊断日志仍必须去掉 query 与 fragment。
|
||||
|
||||
页面可能被浏览器扩展注入大量无关 DOM。当前仅把下列注入作为诊断信息记录,不允许它们改变滑块定位、距离或成功判定:
|
||||
@@ -276,6 +291,9 @@ go vet ./internal/browser ./internal/engine ./internal/account ./internal/server
|
||||
- 没有可见滑块、只显示直接错误提示的真实 Chromium 页面必须被识别,并且不得进入滑动或备用引擎。
|
||||
- 标准 `300px` 轨道与 `42px` 按钮得到精确 `258px`。
|
||||
- 旧 `x5sec` 不得判成功,新 `x5sec` 才能判成功。
|
||||
- 主 Playwright 无头上下文和直接 Chromium/CDP 无头上下文的 HTTP `User-Agent`、`Sec-CH-UA`、
|
||||
`navigator.userAgent`、`navigator.userAgentData` 都不得出现 `HeadlessChrome`/`headless` 标记,UA 中
|
||||
的 Chrome 完整版本必须与随包 Chromium 一致。
|
||||
|
||||
不得删除、跳过、弱化或改写断言来让行为变化通过测试。
|
||||
|
||||
@@ -285,6 +303,13 @@ go vet ./internal/browser ./internal/engine ./internal/account ./internal/server
|
||||
|
||||
用户明确要求改变“未找到滑块时仍执行失败恢复/备用引擎”和“最终失败日志只保留脱敏页面地址”的既有契约。原因是风控页有时只显示平台错误信息而没有可操作滑块,继续 reload、拖动或切换引擎没有验证意义且会增加风控;而真实滑块自动处理失败时,用户需要完整地址在本机浏览器中接管验证。本规范第 3.1、6、8、9 节已同步纳入新的页面分类、编排、日志和集成验证要求。
|
||||
|
||||
### 2026-08-17 当前授权变更
|
||||
|
||||
用户明确要求解决无头 Chromium 指纹暴露 `HeadlessChrome` 的问题。此前随包 Chromium 在服务端
|
||||
风控页中实测返回 `HeadlessChrome/149.0.7827.55`,会让 HTTP UA 与正常桌面 Chromium 身份不同。
|
||||
本规范第 6 至 9 节同步加入了只移除无头产品标记、保留实际版本与 Client Hints、覆盖主/备用引擎、
|
||||
并在诊断包及真实 Chromium 集成测试中核验页面实际指纹的契约。
|
||||
|
||||
只有用户在当前任务中明确点名要求修改滑块认证时,才允许触碰冻结范围。获得授权后也必须在同一个变更中:
|
||||
|
||||
1. 说明要改变本文哪一条冻结契约及原因。
|
||||
|
||||
@@ -14,6 +14,20 @@ type SessionsByAccount = Record<string, ChatSession[]>;
|
||||
|
||||
const accountStorageKey = 'ydisks.chat.account.v1';
|
||||
|
||||
const unreadLabel = (count: number): string => {
|
||||
const normalized = Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0;
|
||||
return normalized > 99 ? '99+' : String(normalized);
|
||||
};
|
||||
|
||||
const UnreadBadge: React.FC<{ count: number; className?: string }> = ({ count, className = '' }) => {
|
||||
if (!Number.isFinite(count) || count <= 0) return null;
|
||||
return (
|
||||
<span aria-label={`未读消息 ${unreadLabel(count)} 条`} className={`inline-flex h-5 min-w-5 shrink-0 items-center justify-center whitespace-nowrap rounded-full bg-red-500 px-1.5 text-[10px] font-bold leading-none text-white ${className}`}>
|
||||
{unreadLabel(count)}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const formatClock = (value: number): string => {
|
||||
if (!value) return '';
|
||||
const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
|
||||
@@ -64,10 +78,17 @@ const Chat: React.FC = () => {
|
||||
|
||||
const reloadSessions = async (accountID: string) => {
|
||||
const page = await getChatSessionPage(accountID, undefined, undefined, true);
|
||||
setSessionsByAccount(current => ({ ...current, [accountID]: page.sessions }));
|
||||
// The session list request can finish after markChatRead during a refresh.
|
||||
// Keep the currently open conversation locally read so a stale response
|
||||
// cannot resurrect its red badge.
|
||||
const sessions = page.sessions.map(session =>
|
||||
accountID === activeAccountRef.current && session.chat_id === activeChatRef.current
|
||||
? { ...session, unread_count: 0 }
|
||||
: session);
|
||||
setSessionsByAccount(current => ({ ...current, [accountID]: sessions }));
|
||||
setContactCursors(current => ({ ...current, [accountID]: page.next_cursor }));
|
||||
setHasMoreContacts(current => ({ ...current, [accountID]: page.has_more }));
|
||||
return page.sessions;
|
||||
return sessions;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -152,11 +173,18 @@ const Chat: React.FC = () => {
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
setSessionsByAccount(current => ({
|
||||
...current,
|
||||
[activeAccountID]: (current[activeAccountID] || []).map(session =>
|
||||
session.chat_id === activeChatID ? { ...session, unread_count: 0 } : session),
|
||||
}));
|
||||
setMessagesLoading(true);
|
||||
void Promise.all([
|
||||
getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }),
|
||||
markChatRead(activeAccountID, activeChatID),
|
||||
]).then(([page]) => {
|
||||
void getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }).then(page => {
|
||||
const readMessages = page.messages
|
||||
.filter(message => message.direction === 'incoming' && message.message_type !== 'system' && !message.message_key.startsWith('in-'))
|
||||
.map(message => ({ messageId: message.message_key, sessionId: activeChatID, cid: `${activeChatID}@goofish`, conversationType: 1 } as any));
|
||||
console.info('[聊天已读] 打开会话上报', { accountID: activeAccountID, chatID: activeChatID, messageCount: readMessages.length, messageIds: readMessages.map(item => item.messageId) });
|
||||
void markChatRead(activeAccountID, activeChatID, readMessages);
|
||||
setMessages(page.messages);
|
||||
setHasOlder(page.has_more);
|
||||
setHistoryCursor(page.next_cursor);
|
||||
@@ -233,7 +261,7 @@ const Chat: React.FC = () => {
|
||||
...row,
|
||||
last_message: message.content,
|
||||
last_message_at: message.sent_at,
|
||||
unread_count: message.direction === 'incoming' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id)
|
||||
unread_count: message.direction === 'incoming' && message.message_type !== 'system' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id)
|
||||
? row.unread_count + 1 : row.unread_count,
|
||||
} : row).sort((a, b) => b.last_message_at - a.last_message_at),
|
||||
};
|
||||
@@ -244,7 +272,11 @@ const Chat: React.FC = () => {
|
||||
if (index >= 0) return current.map((item, i) => i === index ? message : item);
|
||||
return [...current, message];
|
||||
});
|
||||
if (message.direction === 'incoming') void markChatRead(accountID, message.chat_id);
|
||||
if (message.direction === 'incoming' && message.message_type !== 'system') {
|
||||
const readMessage = [{ messageId: message.message_key, sessionId: message.chat_id, cid: `${message.chat_id}@goofish`, conversationType: 1 } as any];
|
||||
console.info('[聊天已读] 收到实时消息上报', { accountID, chatID: message.chat_id, messageKey: message.message_key, messageType: message.message_type });
|
||||
void markChatRead(accountID, message.chat_id, readMessage);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed non-chat frames and recover from authoritative REST state.
|
||||
@@ -388,7 +420,7 @@ const Chat: React.FC = () => {
|
||||
className={`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${active ? 'border-sky-500 text-sky-700' : 'border-transparent text-slate-500 hover:text-slate-900'}`}>
|
||||
<span className={`h-2 w-2 rounded-full ${online ? 'bg-emerald-500' : 'bg-slate-300'}`} />
|
||||
<span className="max-w-36 truncate">{account.nickname || account.remark || account.id}</span>
|
||||
{unread > 0 && <span className="min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white">{unread > 99 ? '99+' : unread}</span>}
|
||||
<UnreadBadge count={unread} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
@@ -434,7 +466,7 @@ const Chat: React.FC = () => {
|
||||
</div>
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<span className="truncate text-xs text-slate-500">{session.last_message || '暂无消息'}</span>
|
||||
{session.unread_count > 0 && <span className="ml-auto min-w-5 shrink-0 rounded-full bg-red-500 px-1.5 py-0.5 text-center text-[10px] font-bold text-white">{session.unread_count}</span>}
|
||||
<UnreadBadge count={session.unread_count} className="ml-auto" />
|
||||
</div>
|
||||
{session.item_title && <div className="mt-1.5 truncate text-[10px] font-medium text-sky-700">商品 · {session.item_title}</div>}
|
||||
</div>
|
||||
@@ -501,7 +533,7 @@ const Chat: React.FC = () => {
|
||||
)}
|
||||
<div className="mt-1 flex items-center gap-1 text-[10px] text-slate-400">
|
||||
{messageTime(message.sent_at)}
|
||||
{outgoing && (message.status === 'failed' ? <AlertCircle className="h-3 w-3 text-red-500" /> : message.status === 'sent' ? <CheckCheck className="h-3 w-3 text-sky-500" /> : <Check className="h-3 w-3" />)}
|
||||
{outgoing && (message.status === 'failed' ? <AlertCircle className="h-3 w-3 text-red-500" /> : message.read_status === 2 ? <CheckCheck className="h-3 w-3 text-sky-500" /> : message.status === 'sent' ? <Check className="h-3 w-3 text-sky-500" /> : <Check className="h-3 w-3" />)}
|
||||
</div>
|
||||
</div>
|
||||
{outgoing && <div className="h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white">
|
||||
|
||||
@@ -70,7 +70,7 @@ test('chat APIs preserve account and conversation scope', async () => {
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/chat/sessions?account_id=a1');
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/chat/messages?account_id=a1&chat_id=c1&before_id=9');
|
||||
expect(JSON.parse(fetchMock.mock.calls[2][1].body)).toMatchObject({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1' });
|
||||
expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1' });
|
||||
expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1', message_ids: [] });
|
||||
});
|
||||
|
||||
test('account task APIs keep rating and polish account-scoped', async () => {
|
||||
|
||||
@@ -148,8 +148,8 @@ export const sendChatImage = async (input: {
|
||||
return postForm('/api/chat/images', form, { timeoutMs: 120_000 });
|
||||
};
|
||||
|
||||
export const markChatRead = async (accountId: string, chatId: string): Promise<ApiResponse> =>
|
||||
post('/api/chat/read', { account_id: accountId, chat_id: chatId });
|
||||
export const markChatRead = async (accountId: string, chatId: string, messageIds: Array<{messageId: string; sessionId?: string; cid?: string; conversationType?: number}> = []): Promise<ApiResponse> =>
|
||||
post('/api/chat/read', { account_id: accountId, chat_id: chatId, message_ids: messageIds });
|
||||
|
||||
export interface AccountRuntimeStatus {
|
||||
state: NonNullable<AccountDetail['runtime_state']>;
|
||||
|
||||
@@ -111,6 +111,8 @@ export interface ChatMessage {
|
||||
message_type: 'text' | 'image' | 'video' | 'system';
|
||||
content: string;
|
||||
status: 'received' | 'sending' | 'sent' | 'failed';
|
||||
read_status?: number;
|
||||
read_at?: number;
|
||||
sent_at: number;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
@@ -73,6 +74,17 @@ type Adapter struct {
|
||||
|
||||
passwordMu sync.Mutex
|
||||
passwordProcessing map[string]struct{}
|
||||
passwordInFlight map[string]*passwordRenewal
|
||||
}
|
||||
|
||||
// passwordRenewal represents the result shared by callers that observe the
|
||||
// same account while its protocol-level credential renewal is running. A
|
||||
// caller must wait for this result instead of treating the in-flight request
|
||||
// as an immediate renewal failure; otherwise concurrent API requests turn one
|
||||
// recoverable expiry into a burst of 502 responses.
|
||||
type passwordRenewal struct {
|
||||
done chan struct{}
|
||||
success bool
|
||||
}
|
||||
|
||||
// notifyNotifier 是 *notify.Notifier 的最小接口,避免 adapter 直接依赖 notify 包
|
||||
@@ -99,6 +111,7 @@ func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter {
|
||||
captchaReq: mtop.NewClient(),
|
||||
orderMTop: mtop.NewClient(),
|
||||
passwordProcessing: make(map[string]struct{}),
|
||||
passwordInFlight: make(map[string]*passwordRenewal),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,13 +153,19 @@ func (a *Adapter) HandleChatMessage(ctx context.Context, message engine.ChatMess
|
||||
// Xianyu echoes messages sent by this account back over the same WS. Those
|
||||
// sends are already captured by HandleOutgoingChatMessage; recording the
|
||||
// echo as incoming would put our own bubble on the buyer side and duplicate it.
|
||||
if strings.TrimSuffix(message.SenderUserID, "@goofish") == strings.TrimSuffix(message.AccountID, "@goofish") {
|
||||
if selfID := protocol.TransCookies(message.CookieStr)["unb"]; selfID != "" &&
|
||||
strings.TrimSuffix(strings.TrimSpace(message.SenderUserID), "@goofish") == strings.TrimSuffix(strings.TrimSpace(selfID), "@goofish") {
|
||||
a.logger.Info("忽略账号自身发送的聊天回显", "account", message.AccountID, "chat_id", message.ChatID, "sender_id", message.SenderUserID)
|
||||
return nil
|
||||
}
|
||||
_, _, err := a.chat.RecordIncoming(ctx, chat.Incoming{
|
||||
stored, inserted, err := a.chat.RecordIncoming(ctx, chat.Incoming{
|
||||
AccountID: message.AccountID, ChatID: message.ChatID, BuyerID: message.SenderUserID,
|
||||
BuyerName: message.SenderName, Text: message.Text, ItemID: message.ItemID, Raw: message.Raw,
|
||||
BuyerName: message.SenderName, Text: message.Text, MessageID: message.MessageID, ItemID: message.ItemID, Raw: message.Raw,
|
||||
})
|
||||
if stored != nil {
|
||||
a.logger.Info("实时聊天消息已入库", "account", message.AccountID, "chat_id", message.ChatID,
|
||||
"message_key", stored.MessageKey, "message_type", stored.MessageType, "inserted", inserted)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -161,6 +180,21 @@ func (a *Adapter) HandleOutgoingChatMessage(ctx context.Context, message engine.
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *Adapter) HandleMessageRead(ctx context.Context, event engine.MessageReadEvent) error {
|
||||
if a.chat == nil {
|
||||
return nil
|
||||
}
|
||||
message, err := a.chat.MarkOutgoingRead(ctx, event.AccountID, event.MessageID, event.ReadAt)
|
||||
if errors.Is(err, db.ErrNotFound) && event.ChatID != "" {
|
||||
message, err = a.chat.MarkLatestOutgoingRead(ctx, event.AccountID, event.ChatID, event.ReadAt)
|
||||
}
|
||||
if err == nil && message != nil {
|
||||
a.logger.Info("聊天出站消息已标记已读", "account", event.AccountID, "chat_id", event.ChatID,
|
||||
"message_id", event.MessageID, "message_key", message.MessageKey, "read_status", message.ReadStatus)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// OnAccountAlert 把账号告警(token 失效/自动恢复失败/风控验证等)转发给通知器,
|
||||
// 推送到该账号已绑定的通知渠道。
|
||||
func (a *Adapter) OnAccountAlert(ctx context.Context, cookieID, level, title, body string) {
|
||||
@@ -498,10 +532,11 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
|
||||
return false
|
||||
}
|
||||
if !a.beginPasswordLogin(cookieID) {
|
||||
a.logger.Warn("协议续期已在处理中", "account", cookieID)
|
||||
return false
|
||||
a.logger.Warn("协议续期已在处理中,等待当前结果", "account", cookieID)
|
||||
return a.waitPasswordLogin(ctx, cookieID)
|
||||
}
|
||||
defer a.finishPasswordLogin(cookieID)
|
||||
renewed := false
|
||||
defer func() { a.finishPasswordLoginResult(cookieID, renewed) }()
|
||||
|
||||
d, err := a.store.Cookies.GetDetails(ctx, cookieID)
|
||||
if err != nil {
|
||||
@@ -551,13 +586,41 @@ func (a *Adapter) beginPasswordLogin(cookieID string) bool {
|
||||
return false
|
||||
}
|
||||
a.passwordProcessing[cookieID] = struct{}{}
|
||||
if a.passwordInFlight == nil {
|
||||
a.passwordInFlight = make(map[string]*passwordRenewal)
|
||||
}
|
||||
a.passwordInFlight[cookieID] = &passwordRenewal{done: make(chan struct{})}
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *Adapter) finishPasswordLogin(cookieID string) {
|
||||
a.finishPasswordLoginResult(cookieID, false)
|
||||
}
|
||||
|
||||
func (a *Adapter) finishPasswordLoginResult(cookieID string, success bool) {
|
||||
a.passwordMu.Lock()
|
||||
defer a.passwordMu.Unlock()
|
||||
delete(a.passwordProcessing, cookieID)
|
||||
if state := a.passwordInFlight[cookieID]; state != nil {
|
||||
state.success = success
|
||||
delete(a.passwordInFlight, cookieID)
|
||||
close(state.done)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Adapter) waitPasswordLogin(ctx context.Context, cookieID string) bool {
|
||||
a.passwordMu.Lock()
|
||||
state := a.passwordInFlight[cookieID]
|
||||
a.passwordMu.Unlock()
|
||||
if state == nil {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case <-state.done:
|
||||
return state.success
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, userID int64, status, failureReason, message string) {
|
||||
@@ -677,6 +740,16 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookieDe
|
||||
a.logger.Info("Go 协议续期成功", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
if err == nil {
|
||||
message := strings.TrimSpace(res.Message)
|
||||
if message == "" {
|
||||
message = "协议续期未通过"
|
||||
}
|
||||
return false, errors.New(message)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = errors.New("协议续期未返回结果")
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
@@ -505,6 +505,35 @@ func TestOnPasswordLoginRefreshWaitsForPendingFinalResult(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnPasswordLoginRefreshConcurrentCallersShareResult(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
renewal.GlobalCooldown.Reset("cid")
|
||||
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; havana_lgc_exp=9999999999999"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
started := make(chan struct{})
|
||||
var once sync.Once
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
once.Do(func() { close(started) })
|
||||
time.Sleep(60 * time.Millisecond)
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
a := New(store, nil, nil)
|
||||
a.SetRenewService(xrenew.Service{
|
||||
HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL,
|
||||
RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond,
|
||||
})
|
||||
first := make(chan bool, 1)
|
||||
go func() { first <- a.OnPasswordLoginRefresh(context.Background(), "cid") }()
|
||||
<-started
|
||||
second := a.OnPasswordLoginRefresh(context.Background(), "cid")
|
||||
if got := <-first; !got || !second {
|
||||
t.Fatalf("并发续期调用应共享成功结果: first=%v second=%v", got, second)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure 接口轻量续期也失败后才因浏览器不可用失败。
|
||||
func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
|
||||
@@ -66,7 +66,7 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us
|
||||
var bctx playwright.BrowserContext
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, passwordPersistentContextOptions(headless))
|
||||
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, passwordPersistentContextOptions(headless, m.headlessUserAgent()))
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
@@ -87,8 +87,8 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us
|
||||
return bctx, release, nil
|
||||
}
|
||||
|
||||
func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunchPersistentContextOptions {
|
||||
return playwright.BrowserTypeLaunchPersistentContextOptions{
|
||||
func passwordPersistentContextOptions(headless bool, headlessUserAgent ...*string) playwright.BrowserTypeLaunchPersistentContextOptions {
|
||||
options := playwright.BrowserTypeLaunchPersistentContextOptions{
|
||||
Headless: playwright.Bool(headless),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
@@ -102,6 +102,10 @@ func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunc
|
||||
},
|
||||
Timeout: playwright.Float(quickRenewTimeoutMS),
|
||||
}
|
||||
if headless && len(headlessUserAgent) > 0 {
|
||||
options.UserAgent = headlessUserAgent[0]
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
// BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。
|
||||
@@ -121,13 +125,14 @@ func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cooki
|
||||
// 解释,避免漏掉或错误映射 Path=/im 的连接凭证。
|
||||
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
|
||||
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, quickRenewHeadless(headless))
|
||||
headless = quickRenewHeadless(headless)
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, headless)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer release()
|
||||
|
||||
page, err := bctx.NewPage()
|
||||
page, err := m.newBrowserPage(bctx, headless)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
@@ -180,13 +185,14 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt
|
||||
return "", nil, false, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法执行续期")
|
||||
}
|
||||
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, cookiesRefreshHeadless(headless))
|
||||
headless = cookiesRefreshHeadless(headless)
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, headless)
|
||||
if err != nil {
|
||||
return "", nil, false, err
|
||||
}
|
||||
defer release()
|
||||
|
||||
page, err := bctx.NewPage()
|
||||
page, err := m.newBrowserPage(bctx, headless)
|
||||
if err != nil {
|
||||
return "", nil, false, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
@@ -478,7 +484,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
var bctx playwright.BrowserContext
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, playwright.BrowserTypeLaunchPersistentContextOptions{
|
||||
options := playwright.BrowserTypeLaunchPersistentContextOptions{
|
||||
Headless: playwright.Bool(headless),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
@@ -486,7 +492,11 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
Timeout: playwright.Float(quickRenewTimeoutMS),
|
||||
})
|
||||
}
|
||||
if headless {
|
||||
options.UserAgent = m.headlessUserAgent()
|
||||
}
|
||||
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, options)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
func TestHeadlessFingerprintBrowserIntegration(t *testing.T) {
|
||||
if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" {
|
||||
t.Skip("set RUN_BROWSER_INTEGRATION=1 to verify the effective headless browser fingerprint")
|
||||
}
|
||||
|
||||
requests := make(chan http.Header, 2)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/fingerprint" {
|
||||
requests <- r.Header.Clone()
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, "<!doctype html><title>fingerprint</title>")
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
m := NewManager(nil)
|
||||
defer m.Close()
|
||||
if err := m.init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
userAgent := m.headlessUserAgent()
|
||||
if userAgent == nil {
|
||||
t.Fatal("初始化后无头 UA 为空")
|
||||
}
|
||||
|
||||
t.Run("playwright-context", func(t *testing.T) {
|
||||
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(true),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = browser.Close() }()
|
||||
bctx, err := browser.NewContext(playwright.BrowserNewContextOptions{UserAgent: userAgent})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = bctx.Close() }()
|
||||
page, err := m.newBrowserPage(bctx, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
verifyEffectiveHeadlessFingerprint(t, page, server.URL+"/fingerprint", requests, *userAgent)
|
||||
})
|
||||
|
||||
t.Run("direct-cdp-context", func(t *testing.T) {
|
||||
profileDir := t.TempDir()
|
||||
executable := m.pw.Chromium.ExecutablePath()
|
||||
if configured := chromiumExecutablePath(); configured != nil {
|
||||
executable = *configured
|
||||
}
|
||||
cmd := exec.Command(executable, fallbackChromiumArgs(profileDir, true, userAgent)...)
|
||||
cmd.Stdout = io.Discard
|
||||
cmd.Stderr = io.Discard
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
processDone := make(chan error, 1)
|
||||
go func() { processDone <- cmd.Wait() }()
|
||||
defer func() {
|
||||
if cmd.Process != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
}
|
||||
select {
|
||||
case <-processDone:
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
}()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
endpoint, err := waitForDevToolsEndpoint(ctx, profileDir, processDone, 10*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
browser, err := m.pw.Chromium.ConnectOverCDP(endpoint)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = browser.Close() }()
|
||||
contexts := browser.Contexts()
|
||||
if len(contexts) == 0 {
|
||||
t.Fatal("直接 CDP 浏览器无默认 context")
|
||||
}
|
||||
page, err := m.newBrowserPage(contexts[0], true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
verifyEffectiveHeadlessFingerprint(t, page, server.URL+"/fingerprint", requests, *userAgent)
|
||||
})
|
||||
}
|
||||
|
||||
func verifyEffectiveHeadlessFingerprint(t *testing.T, page playwright.Page, target string, requests <-chan http.Header, expectedUserAgent string) {
|
||||
t.Helper()
|
||||
if _, err := page.Goto(target, playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var headers http.Header
|
||||
select {
|
||||
case headers = <-requests:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("等待浏览器指纹请求超时")
|
||||
}
|
||||
pageIdentity, err := page.Evaluate(`() => ({
|
||||
userAgent: navigator.userAgent,
|
||||
userAgentData: navigator.userAgentData ? navigator.userAgentData.toJSON() : null
|
||||
})`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("effective user-agent=%q sec-ch-ua=%q page=%v", headers.Get("User-Agent"), headers.Get("Sec-CH-UA"), pageIdentity)
|
||||
for source, value := range map[string]string{
|
||||
"http-user-agent": headers.Get("User-Agent"),
|
||||
"http-sec-ch-ua": headers.Get("Sec-CH-UA"),
|
||||
"page-identity": fmt.Sprint(pageIdentity),
|
||||
} {
|
||||
if strings.Contains(strings.ToLower(value), "headless") {
|
||||
t.Fatalf("%s 仍暴露 headless 标记: %s", source, value)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(headers.Get("User-Agent"), "Chrome/") {
|
||||
t.Fatalf("HTTP UA 缺少 Chrome 版本: %q", headers.Get("User-Agent"))
|
||||
}
|
||||
if headers.Get("User-Agent") != expectedUserAgent {
|
||||
t.Fatalf("HTTP UA 与实测 Chromium 版本不一致: got %q want %q", headers.Get("User-Agent"), expectedUserAgent)
|
||||
}
|
||||
identity, ok := pageIdentity.(map[string]any)
|
||||
if !ok || identity["userAgent"] != expectedUserAgent {
|
||||
t.Fatalf("navigator.userAgent 与实测 Chromium 版本不一致: %#v", pageIdentity)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -35,13 +36,30 @@ const (
|
||||
|
||||
// chromiumLaunchArgs 统一 Chromium 启动参数。
|
||||
func chromiumLaunchArgs() []string {
|
||||
return []string{
|
||||
args := []string{
|
||||
"--no-sandbox",
|
||||
"--disable-setuid-sandbox",
|
||||
"--disable-dev-shm-usage",
|
||||
"--disable-blink-features=AutomationControlled",
|
||||
"--lang=zh-CN",
|
||||
}
|
||||
if captchaIgnoreCertificateErrors() {
|
||||
args = append(args, "--ignore-certificate-errors")
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
// captchaIgnoreCertificateErrors is an explicit escape hatch for environments
|
||||
// whose TLS inspection proxy replaces Alibaba's certificate chain. It is off
|
||||
// by default; enabling it is limited to the browser process so the HTTP
|
||||
// clients and stored credentials keep their normal certificate validation.
|
||||
func captchaIgnoreCertificateErrors() bool {
|
||||
value := strings.TrimSpace(os.Getenv("CAPTCHA_IGNORE_CERT_ERRORS"))
|
||||
if value == "" {
|
||||
return false
|
||||
}
|
||||
parsed, err := strconv.ParseBool(value)
|
||||
return err == nil && parsed
|
||||
}
|
||||
|
||||
func chromiumExecutablePath() *string {
|
||||
@@ -107,6 +125,13 @@ type Manager struct {
|
||||
pw *playwright.Playwright
|
||||
logger *slog.Logger
|
||||
|
||||
// browserFingerprint is observed from the bundled Chromium once during
|
||||
// initialization. Headless contexts use the same identity with only the
|
||||
// HeadlessChrome product token removed; headed contexts keep Chromium's
|
||||
// native identity.
|
||||
browserFingerprint xianyu.BrowserFingerprint
|
||||
userAgentMetadata map[string]any
|
||||
|
||||
once sync.Once
|
||||
initErr error
|
||||
installed bool
|
||||
@@ -264,13 +289,185 @@ func (m *Manager) detectBrowserFingerprint() error {
|
||||
if strings.TrimSpace(headers.Get("User-Agent")) == "" {
|
||||
return fmt.Errorf("Chromium 返回空 userAgent")
|
||||
}
|
||||
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{
|
||||
metadata, err := readUserAgentMetadata(page)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取 Chromium User-Agent Client Hints 失败: %w", err)
|
||||
}
|
||||
fingerprint := normalizeBrowserFingerprint(xianyu.BrowserFingerprint{
|
||||
UserAgent: headers.Get("User-Agent"),
|
||||
SecChUA: headers.Get("sec-ch-ua"),
|
||||
Platform: strings.Trim(headers.Get("sec-ch-ua-platform"), `"`),
|
||||
Mobile: headers.Get("sec-ch-ua-mobile"),
|
||||
})
|
||||
m.logger.Info("已读取 Playwright Chromium 原生指纹", "browser_version", b.Version(), "user_agent", headers.Get("User-Agent"))
|
||||
m.browserFingerprint = fingerprint
|
||||
m.userAgentMetadata = normalizeUserAgentMetadata(metadata)
|
||||
xianyu.SetBrowserFingerprint(fingerprint)
|
||||
m.logger.Info("已读取 Playwright Chromium 浏览器指纹", "browser_version", b.Version(), "user_agent", fingerprint.UserAgent, "headless_token_removed", fingerprint.UserAgent != headers.Get("User-Agent"))
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeBrowserFingerprint removes the product marker that Chromium adds to
|
||||
// its legacy UA string in headless mode. It intentionally preserves the
|
||||
// browser version and all Client Hints observed from the same runtime.
|
||||
func normalizeBrowserFingerprint(fingerprint xianyu.BrowserFingerprint) xianyu.BrowserFingerprint {
|
||||
fingerprint.UserAgent = normalizeHeadlessUserAgent(fingerprint.UserAgent)
|
||||
fingerprint.SecChUA = normalizeSecChUA(fingerprint.SecChUA)
|
||||
return fingerprint
|
||||
}
|
||||
|
||||
func normalizeHeadlessUserAgent(userAgent string) string {
|
||||
return strings.ReplaceAll(strings.TrimSpace(userAgent), "HeadlessChrome/", "Chrome/")
|
||||
}
|
||||
|
||||
func normalizeSecChUA(value string) string {
|
||||
parts := strings.Split(value, ",")
|
||||
result := make([]string, 0, len(parts))
|
||||
seen := make(map[string]struct{}, len(parts))
|
||||
for _, part := range parts {
|
||||
part = strings.TrimSpace(strings.ReplaceAll(part, "HeadlessChrome", "Chromium"))
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
brand := part
|
||||
if index := strings.IndexByte(brand, ';'); index >= 0 {
|
||||
brand = strings.TrimSpace(brand[:index])
|
||||
}
|
||||
if _, exists := seen[brand]; exists {
|
||||
continue
|
||||
}
|
||||
seen[brand] = struct{}{}
|
||||
result = append(result, part)
|
||||
}
|
||||
return strings.Join(result, ", ")
|
||||
}
|
||||
|
||||
func readUserAgentMetadata(page playwright.Page) (map[string]any, error) {
|
||||
value, err := page.Evaluate(`async () => {
|
||||
const data = navigator.userAgentData;
|
||||
if (!data) return null;
|
||||
const high = await data.getHighEntropyValues([
|
||||
'architecture', 'bitness', 'fullVersionList', 'model', 'platformVersion', 'wow64'
|
||||
]);
|
||||
return {
|
||||
brands: data.brands,
|
||||
fullVersionList: high.fullVersionList,
|
||||
platform: data.platform,
|
||||
platformVersion: high.platformVersion,
|
||||
architecture: high.architecture,
|
||||
model: high.model,
|
||||
mobile: data.mobile,
|
||||
bitness: high.bitness,
|
||||
wow64: high.wow64
|
||||
};
|
||||
}`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if value == nil {
|
||||
return nil, fmt.Errorf("navigator.userAgentData 不可用")
|
||||
}
|
||||
metadata, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("navigator.userAgentData 类型异常: %T", value)
|
||||
}
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
func normalizeUserAgentMetadata(metadata map[string]any) map[string]any {
|
||||
if len(metadata) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make(map[string]any, len(metadata))
|
||||
for key, value := range metadata {
|
||||
switch key {
|
||||
case "brands", "fullVersionList":
|
||||
result[key] = normalizeUserAgentBrands(value)
|
||||
default:
|
||||
result[key] = value
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func normalizeUserAgentBrands(value any) []any {
|
||||
brands, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
result := make([]any, 0, len(brands))
|
||||
seen := make(map[string]struct{}, len(brands))
|
||||
for _, item := range brands {
|
||||
brandEntry, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
brand, _ := brandEntry["brand"].(string)
|
||||
brand = strings.ReplaceAll(brand, "HeadlessChrome", "Chromium")
|
||||
if brand == "" {
|
||||
continue
|
||||
}
|
||||
if _, exists := seen[brand]; exists {
|
||||
continue
|
||||
}
|
||||
seen[brand] = struct{}{}
|
||||
entry := make(map[string]any, len(brandEntry))
|
||||
for key, itemValue := range brandEntry {
|
||||
entry[key] = itemValue
|
||||
}
|
||||
entry["brand"] = brand
|
||||
result = append(result, entry)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (m *Manager) headlessUserAgent() *string {
|
||||
userAgent := normalizeHeadlessUserAgent(m.browserFingerprint.UserAgent)
|
||||
if userAgent == "" {
|
||||
userAgent = normalizeHeadlessUserAgent(xianyu.CurrentBrowserFingerprint().UserAgent)
|
||||
}
|
||||
if userAgent == "" {
|
||||
return nil
|
||||
}
|
||||
return playwright.String(userAgent)
|
||||
}
|
||||
|
||||
func (m *Manager) newBrowserPage(bctx playwright.BrowserContext, headless bool) (playwright.Page, error) {
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !headless {
|
||||
return page, nil
|
||||
}
|
||||
if err := m.applyHeadlessFingerprint(page); err != nil {
|
||||
_ = page.Close()
|
||||
return nil, err
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (m *Manager) applyHeadlessFingerprint(page playwright.Page) error {
|
||||
userAgent := m.headlessUserAgent()
|
||||
if userAgent == nil {
|
||||
return fmt.Errorf("无头 Chromium User-Agent 未初始化")
|
||||
}
|
||||
metadata := normalizeUserAgentMetadata(m.userAgentMetadata)
|
||||
if len(metadata) == 0 {
|
||||
return fmt.Errorf("无头 Chromium User-Agent Client Hints 未初始化")
|
||||
}
|
||||
session, err := page.Context().NewCDPSession(page)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建 Chromium 指纹 CDP 会话: %w", err)
|
||||
}
|
||||
if _, err := session.Send("Emulation.setUserAgentOverride", map[string]any{
|
||||
"userAgent": *userAgent,
|
||||
"userAgentMetadata": metadata,
|
||||
}); err != nil {
|
||||
_ = session.Detach()
|
||||
return fmt.Errorf("应用 Chromium 无头指纹: %w", err)
|
||||
}
|
||||
// Keep the session attached for the page lifetime. Chromium reverts
|
||||
// navigator.userAgentData when this target-scoped emulation session detaches.
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -303,7 +500,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
page, err := entry.context.NewPage()
|
||||
page, err := m.newBrowserPage(entry.context, headless)
|
||||
if err != nil {
|
||||
// context 损坏,丢弃重建一次。
|
||||
m.releaseEntry(cookieID, entry)
|
||||
@@ -312,7 +509,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
page, err = entry.context.NewPage()
|
||||
page, err = m.newBrowserPage(entry.context, headless)
|
||||
if err != nil {
|
||||
m.releaseEntry(cookieID, entry)
|
||||
m.evict(cookieID)
|
||||
@@ -394,11 +591,15 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("启动 chromium 失败: %w", err)
|
||||
}
|
||||
context, err := browser.NewContext(playwright.BrowserNewContextOptions{
|
||||
contextOptions := playwright.BrowserNewContextOptions{
|
||||
Viewport: &playwright.Size{Width: defaultW, Height: defaultH},
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
})
|
||||
}
|
||||
if headless {
|
||||
contextOptions.UserAgent = m.headlessUserAgent()
|
||||
}
|
||||
context, err := browser.NewContext(contextOptions)
|
||||
if err != nil {
|
||||
_ = browser.Close()
|
||||
return nil, fmt.Errorf("创建 context 失败: %w", err)
|
||||
|
||||
@@ -64,7 +64,7 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
|
||||
}
|
||||
defer release()
|
||||
|
||||
page, err := bctx.NewPage()
|
||||
page, err := m.newBrowserPage(bctx, headless)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
|
||||
@@ -79,12 +79,13 @@ func TestPasswordLoginReferenceProfileAndTiming(t *testing.T) {
|
||||
|
||||
func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) {
|
||||
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "/opt/chromium")
|
||||
opts := passwordPersistentContextOptions(true)
|
||||
userAgent := "Mozilla/5.0 Chrome/149.0.7827.55 Safari/537.36"
|
||||
opts := passwordPersistentContextOptions(true, &userAgent)
|
||||
if opts.Headless == nil || !*opts.Headless {
|
||||
t.Fatal("密码登录应按调用参数使用无头模式")
|
||||
}
|
||||
if opts.UserAgent != nil {
|
||||
t.Fatalf("密码登录不应覆盖 Playwright Chromium 原生 UA: %v", *opts.UserAgent)
|
||||
if opts.UserAgent == nil || *opts.UserAgent != userAgent {
|
||||
t.Fatalf("无头密码登录应使用去除 HeadlessChrome 的运行时 UA: %v", opts.UserAgent)
|
||||
}
|
||||
if opts.Viewport == nil || opts.Viewport.Width != 1980 || opts.Viewport.Height != 1024 {
|
||||
t.Fatalf("密码登录 viewport=%+v", opts.Viewport)
|
||||
@@ -104,6 +105,10 @@ func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) {
|
||||
if opts.ExecutablePath == nil || *opts.ExecutablePath != "/opt/chromium" {
|
||||
t.Fatalf("Chromium 路径=%v", opts.ExecutablePath)
|
||||
}
|
||||
headed := passwordPersistentContextOptions(false, &userAgent)
|
||||
if headed.UserAgent != nil {
|
||||
t.Fatalf("有头密码登录应保留 Chromium 原生 UA: %v", headed.UserAgent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit(t *testing.T) {
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
package browser
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/xianyu"
|
||||
)
|
||||
|
||||
// TestSanitize 特殊字符替换为下划线(用于 userDataDir 命名)。
|
||||
func TestSanitize(t *testing.T) {
|
||||
@@ -95,6 +101,77 @@ func TestChromiumExecutablePathFromEnv(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptchaIgnoreCertificateErrors(t *testing.T) {
|
||||
t.Setenv("CAPTCHA_IGNORE_CERT_ERRORS", "")
|
||||
if captchaIgnoreCertificateErrors() {
|
||||
t.Fatal("默认不应忽略证书错误")
|
||||
}
|
||||
t.Setenv("CAPTCHA_IGNORE_CERT_ERRORS", "true")
|
||||
if !captchaIgnoreCertificateErrors() {
|
||||
t.Fatal("true 应启用 CAPTCHA 证书错误忽略开关")
|
||||
}
|
||||
t.Setenv("CAPTCHA_IGNORE_CERT_ERRORS", "not-a-bool")
|
||||
if captchaIgnoreCertificateErrors() {
|
||||
t.Fatal("无效值不应启用证书错误忽略开关")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeBrowserFingerprintRemovesOnlyHeadlessMarker(t *testing.T) {
|
||||
fingerprint := normalizeBrowserFingerprint(xianyu.BrowserFingerprint{
|
||||
UserAgent: " Mozilla/5.0 HeadlessChrome/149.0.7827.55 Safari/537.36 ",
|
||||
SecChUA: `"HeadlessChrome";v="149", "Chromium";v="149"`,
|
||||
Platform: "macOS",
|
||||
Mobile: "?0",
|
||||
})
|
||||
if strings.Contains(fingerprint.UserAgent, "HeadlessChrome") || strings.Contains(fingerprint.SecChUA, "HeadlessChrome") {
|
||||
t.Fatalf("无头标记未清除: %+v", fingerprint)
|
||||
}
|
||||
if !strings.Contains(fingerprint.UserAgent, "Chrome/149.0.7827.55") {
|
||||
t.Fatalf("Chromium 版本不应变化: %q", fingerprint.UserAgent)
|
||||
}
|
||||
if fingerprint.Platform != "macOS" || fingerprint.Mobile != "?0" {
|
||||
t.Fatalf("非无头字段不应变化: %+v", fingerprint)
|
||||
}
|
||||
if strings.Count(fingerprint.SecChUA, `"Chromium"`) != 1 {
|
||||
t.Fatalf("Client Hints 品牌应去重: %q", fingerprint.SecChUA)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeUserAgentMetadataRemovesAndDeduplicatesHeadlessBrand(t *testing.T) {
|
||||
metadata := normalizeUserAgentMetadata(map[string]any{
|
||||
"brands": []any{
|
||||
map[string]any{"brand": "HeadlessChrome", "version": "149"},
|
||||
map[string]any{"brand": "Chromium", "version": "149"},
|
||||
map[string]any{"brand": "Not)A;Brand", "version": "24"},
|
||||
},
|
||||
"fullVersionList": []any{
|
||||
map[string]any{"brand": "HeadlessChrome", "version": "149.0.7827.55"},
|
||||
map[string]any{"brand": "Chromium", "version": "149.0.7827.55"},
|
||||
},
|
||||
"platform": "macOS",
|
||||
"mobile": false,
|
||||
})
|
||||
if strings.Contains(strings.ToLower(fmt.Sprint(metadata)), "headless") {
|
||||
t.Fatalf("User-Agent metadata 仍暴露 headless: %#v", metadata)
|
||||
}
|
||||
brands, ok := metadata["brands"].([]any)
|
||||
if !ok || len(brands) != 2 {
|
||||
t.Fatalf("brands 未正确去重: %#v", metadata["brands"])
|
||||
}
|
||||
fullVersions, ok := metadata["fullVersionList"].([]any)
|
||||
if !ok || len(fullVersions) != 1 {
|
||||
t.Fatalf("fullVersionList 未正确去重: %#v", metadata["fullVersionList"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagerHeadlessUserAgentUsesDetectedRuntimeVersion(t *testing.T) {
|
||||
m := &Manager{browserFingerprint: xianyu.BrowserFingerprint{UserAgent: "Mozilla/5.0 HeadlessChrome/149.0.7827.55 Safari/537.36"}}
|
||||
userAgent := m.headlessUserAgent()
|
||||
if userAgent == nil || *userAgent != "Mozilla/5.0 Chrome/149.0.7827.55 Safari/537.36" {
|
||||
t.Fatalf("headlessUserAgent=%v", userAgent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkipPlaywrightBrowserDownloadFromEnv(t *testing.T) {
|
||||
t.Setenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "")
|
||||
if skipPlaywrightBrowserDownload() {
|
||||
|
||||
@@ -39,6 +39,7 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
Viewport: &playwright.Size{Width: 1100, Height: 760},
|
||||
Locale: playwright.String(defaultLang),
|
||||
TimezoneId: playwright.String(defaultTZ),
|
||||
UserAgent: m.headlessUserAgent(),
|
||||
})
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("创建 context 失败: %w", err)
|
||||
@@ -52,7 +53,7 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
return "", "", fmt.Errorf("注入临时 cookie 失败: %w", err)
|
||||
}
|
||||
|
||||
page, err := bctx.NewPage()
|
||||
page, err := m.newBrowserPage(bctx, true)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
|
||||
@@ -174,7 +174,7 @@ func (m *Manager) TokenCaptchaRecoverWithEngine(ctx context.Context, cookieID, c
|
||||
)
|
||||
}
|
||||
|
||||
func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (string, error) {
|
||||
func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (result string, resultErr error) {
|
||||
if strings.TrimSpace(cookieStr) == "" {
|
||||
return "", fmt.Errorf("Cookie为空,无法处理 token 风控验证")
|
||||
}
|
||||
@@ -183,7 +183,8 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c
|
||||
}
|
||||
|
||||
currentCookies := cookieStr
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, currentCookies, nil, quickRenewHeadless(headless), true)
|
||||
headless = quickRenewHeadless(headless)
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, currentCookies, nil, headless, true)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -196,11 +197,18 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c
|
||||
}
|
||||
previousX5SecValues := x5SecValues(beforeCookies)
|
||||
|
||||
page, err := bctx.NewPage()
|
||||
page, err := m.newBrowserPage(bctx, headless)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
defer func() { _ = page.Close() }()
|
||||
diagnostic := newTokenCaptchaDiagnostic(cookieID, "playwright", verificationURL, page, m.logger)
|
||||
diagnosticSucceeded := false
|
||||
defer func() {
|
||||
if diagnostic != nil && !diagnosticSucceeded {
|
||||
diagnostic.capture(page, "playwright_failed", resultErr)
|
||||
}
|
||||
}()
|
||||
|
||||
if time.Now().After(browserDeadline) {
|
||||
return "", fmt.Errorf("token 风控浏览器验证超过 %s", tokenCaptchaBrowserTTL)
|
||||
@@ -230,6 +238,9 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c
|
||||
m.logger.Warn("token 风控页面没有可验证滑块,停止自动验证", "cookieID", cookieID, "err", pageErr)
|
||||
return "", pageErr
|
||||
}
|
||||
if diagnostic != nil {
|
||||
diagnostic.snapshotInitial(page)
|
||||
}
|
||||
|
||||
scratch := isScratchCaptcha(content)
|
||||
if err := solveSliderStrict(page, scratch, m.logger, previousX5SecValues, browserDeadline); err != nil {
|
||||
@@ -245,6 +256,7 @@ func (m *Manager) tokenCaptchaPlaywrightRecover(ctx context.Context, cookieID, c
|
||||
merged[k] = v
|
||||
}
|
||||
m.logger.Info("token风控验证成功", "cookieID", cookieID, "x5_cookie_count", len(x5))
|
||||
diagnosticSucceeded = true
|
||||
return cookieMarshal(merged), nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,558 @@
|
||||
package browser
|
||||
|
||||
// Token CAPTCHA diagnostics are deliberately opt-in. They collect enough
|
||||
// information to distinguish a page/DOM change from a server-side rejection,
|
||||
// without changing the frozen slider implementation or writing credentials to
|
||||
// the normal application log.
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
|
||||
"xianyu-go/internal/logsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
tokenCaptchaDiagnosticDirEnv = "CAPTCHA_DIAGNOSTIC_DIR"
|
||||
tokenCaptchaDiagnosticSensitiveEnv = "CAPTCHA_DIAGNOSTIC_INCLUDE_SENSITIVE"
|
||||
tokenCaptchaDiagnosticMaxEvents = 500
|
||||
)
|
||||
|
||||
type tokenCaptchaDiagnostic struct {
|
||||
cookieID string
|
||||
engine string
|
||||
requestedURL string
|
||||
includeSensitive bool
|
||||
dir string
|
||||
startedAt time.Time
|
||||
logger *slog.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
requests []tokenCaptchaDiagnosticNetworkEvent
|
||||
responses []tokenCaptchaDiagnosticNetworkEvent
|
||||
console []tokenCaptchaDiagnosticConsoleEvent
|
||||
pageError []string
|
||||
initial tokenCaptchaDiagnosticSnapshot
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
type tokenCaptchaDiagnosticSnapshot struct {
|
||||
CapturedAt string
|
||||
PageHTML string
|
||||
Screenshot []byte
|
||||
FrameHTML map[int]string
|
||||
Frames []tokenCaptchaDiagnosticFrame
|
||||
Selectors []tokenCaptchaDiagnosticSelector
|
||||
}
|
||||
|
||||
type tokenCaptchaDiagnosticNetworkEvent struct {
|
||||
Kind string `json:"kind"`
|
||||
At string `json:"at"`
|
||||
URL string `json:"url"`
|
||||
Method string `json:"method,omitempty"`
|
||||
ResourceType string `json:"resource_type,omitempty"`
|
||||
Navigation bool `json:"navigation,omitempty"`
|
||||
Status int `json:"status,omitempty"`
|
||||
ContentType string `json:"content_type,omitempty"`
|
||||
Failure string `json:"failure,omitempty"`
|
||||
}
|
||||
|
||||
type tokenCaptchaDiagnosticConsoleEvent struct {
|
||||
At string `json:"at"`
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type tokenCaptchaDiagnosticFrame struct {
|
||||
Index int `json:"index"`
|
||||
Name string `json:"name,omitempty"`
|
||||
URL string `json:"url"`
|
||||
ParentURL string `json:"parent_url,omitempty"`
|
||||
HTMLBytes int `json:"html_bytes,omitempty"`
|
||||
ContentErr string `json:"content_error,omitempty"`
|
||||
}
|
||||
|
||||
type tokenCaptchaDiagnosticSelector struct {
|
||||
FrameIndex int `json:"frame_index"`
|
||||
FrameURL string `json:"frame_url"`
|
||||
Selector string `json:"selector"`
|
||||
Found bool `json:"found"`
|
||||
Visible bool `json:"visible,omitempty"`
|
||||
Box string `json:"box,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type tokenCaptchaDiagnosticManifest struct {
|
||||
Version int `json:"version"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
CookieIDHash string `json:"cookie_id_hash"`
|
||||
Engine string `json:"engine"`
|
||||
Phase string `json:"phase"`
|
||||
Cause string `json:"cause,omitempty"`
|
||||
RequestedURL string `json:"requested_url"`
|
||||
CurrentURL string `json:"current_url"`
|
||||
Title string `json:"title,omitempty"`
|
||||
IncludeSensitive bool `json:"include_sensitive"`
|
||||
PageState map[string]any `json:"page_state,omitempty"`
|
||||
Frames []tokenCaptchaDiagnosticFrame `json:"frames,omitempty"`
|
||||
Selectors []tokenCaptchaDiagnosticSelector `json:"selectors,omitempty"`
|
||||
InitialCapturedAt string `json:"initial_captured_at,omitempty"`
|
||||
InitialFrames []tokenCaptchaDiagnosticFrame `json:"initial_frames,omitempty"`
|
||||
InitialSelectors []tokenCaptchaDiagnosticSelector `json:"initial_selectors,omitempty"`
|
||||
Requests []tokenCaptchaDiagnosticNetworkEvent `json:"requests,omitempty"`
|
||||
Responses []tokenCaptchaDiagnosticNetworkEvent `json:"responses,omitempty"`
|
||||
Console []tokenCaptchaDiagnosticConsoleEvent `json:"console,omitempty"`
|
||||
PageErrors []string `json:"page_errors,omitempty"`
|
||||
}
|
||||
|
||||
func newTokenCaptchaDiagnostic(cookieID, engine, requestedURL string, page playwright.Page, logger *slog.Logger) *tokenCaptchaDiagnostic {
|
||||
dir := strings.TrimSpace(os.Getenv(tokenCaptchaDiagnosticDirEnv))
|
||||
if dir == "" || page == nil {
|
||||
return nil
|
||||
}
|
||||
d := &tokenCaptchaDiagnostic{
|
||||
cookieID: cookieID,
|
||||
engine: engine,
|
||||
requestedURL: requestedURL,
|
||||
includeSensitive: diagnosticBoolEnv(tokenCaptchaDiagnosticSensitiveEnv),
|
||||
dir: dir,
|
||||
startedAt: time.Now().UTC(),
|
||||
logger: logger,
|
||||
}
|
||||
page.OnRequest(func(request playwright.Request) {
|
||||
d.recordRequest(request)
|
||||
})
|
||||
page.OnResponse(func(response playwright.Response) {
|
||||
d.recordResponse(response)
|
||||
})
|
||||
page.OnRequestFailed(func(request playwright.Request) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if len(d.responses) >= tokenCaptchaDiagnosticMaxEvents {
|
||||
return
|
||||
}
|
||||
failure := ""
|
||||
if err := request.Failure(); err != nil {
|
||||
failure = err.Error()
|
||||
}
|
||||
d.responses = append(d.responses, tokenCaptchaDiagnosticNetworkEvent{
|
||||
Kind: "request_failed",
|
||||
At: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
URL: d.safeURL(request.URL()),
|
||||
Method: request.Method(),
|
||||
ResourceType: request.ResourceType(),
|
||||
Navigation: request.IsNavigationRequest(),
|
||||
Failure: failure,
|
||||
})
|
||||
})
|
||||
page.OnConsole(func(message playwright.ConsoleMessage) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if len(d.console) >= tokenCaptchaDiagnosticMaxEvents {
|
||||
return
|
||||
}
|
||||
text := message.Text()
|
||||
if !d.includeSensitive {
|
||||
text = redactDiagnosticText(text)
|
||||
}
|
||||
d.console = append(d.console, tokenCaptchaDiagnosticConsoleEvent{
|
||||
At: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
Type: message.Type(),
|
||||
Text: text,
|
||||
})
|
||||
})
|
||||
page.OnPageError(func(pageErr error) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if pageErr == nil || len(d.pageError) >= tokenCaptchaDiagnosticMaxEvents {
|
||||
return
|
||||
}
|
||||
text := pageErr.Error()
|
||||
if !d.includeSensitive {
|
||||
text = redactDiagnosticText(text)
|
||||
}
|
||||
d.pageError = append(d.pageError, text)
|
||||
})
|
||||
return d
|
||||
}
|
||||
|
||||
func diagnosticBoolEnv(name string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv(name))) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (d *tokenCaptchaDiagnostic) recordRequest(request playwright.Request) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if len(d.requests) >= tokenCaptchaDiagnosticMaxEvents {
|
||||
return
|
||||
}
|
||||
d.requests = append(d.requests, tokenCaptchaDiagnosticNetworkEvent{
|
||||
Kind: "request",
|
||||
At: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
URL: d.safeURL(request.URL()),
|
||||
Method: request.Method(),
|
||||
ResourceType: request.ResourceType(),
|
||||
Navigation: request.IsNavigationRequest(),
|
||||
})
|
||||
}
|
||||
|
||||
func (d *tokenCaptchaDiagnostic) recordResponse(response playwright.Response) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if len(d.responses) >= tokenCaptchaDiagnosticMaxEvents {
|
||||
return
|
||||
}
|
||||
request := response.Request()
|
||||
contentType := response.Headers()["content-type"]
|
||||
d.responses = append(d.responses, tokenCaptchaDiagnosticNetworkEvent{
|
||||
Kind: "response",
|
||||
At: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
URL: d.safeURL(response.URL()),
|
||||
Method: request.Method(),
|
||||
ResourceType: request.ResourceType(),
|
||||
Navigation: request.IsNavigationRequest(),
|
||||
Status: response.Status(),
|
||||
ContentType: contentType,
|
||||
})
|
||||
}
|
||||
|
||||
func (d *tokenCaptchaDiagnostic) safeURL(raw string) string {
|
||||
if d.includeSensitive {
|
||||
return raw
|
||||
}
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
return logsafe.URL(raw)
|
||||
}
|
||||
if u.RawQuery == "" && u.Fragment == "" {
|
||||
return logsafe.URL(raw)
|
||||
}
|
||||
values := u.Query()
|
||||
keys := make([]string, 0, len(values))
|
||||
for key := range values {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
queryDigest := sha256.Sum256([]byte(u.RawQuery))
|
||||
u.RawQuery = "keys=" + strings.Join(keys, ",") + "&query_sha256=" + hex.EncodeToString(queryDigest[:])[:16]
|
||||
u.Fragment = ""
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func (d *tokenCaptchaDiagnostic) capture(page playwright.Page, phase string, cause error) {
|
||||
if d == nil || page == nil {
|
||||
return
|
||||
}
|
||||
d.once.Do(func() {
|
||||
path, err := d.writeBundle(page, phase, cause)
|
||||
if err != nil {
|
||||
// Diagnostics must never affect the CAPTCHA result path.
|
||||
fmt.Fprintf(os.Stderr, "token captcha diagnostic capture failed: %v\n", err)
|
||||
} else if d.logger != nil {
|
||||
d.logger.Info("token风控诊断包已生成", "cookieID", d.cookieID, "engine", d.engine, "path", path, "include_sensitive", d.includeSensitive)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (d *tokenCaptchaDiagnostic) snapshotInitial(page playwright.Page) {
|
||||
if d == nil || page == nil {
|
||||
return
|
||||
}
|
||||
d.mu.Lock()
|
||||
if d.initial.CapturedAt != "" {
|
||||
d.mu.Unlock()
|
||||
return
|
||||
}
|
||||
d.mu.Unlock()
|
||||
|
||||
snapshot := tokenCaptchaDiagnosticSnapshot{
|
||||
CapturedAt: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
FrameHTML: make(map[int]string),
|
||||
}
|
||||
snapshot.PageHTML, _ = page.Content()
|
||||
snapshot.Screenshot, _ = page.Screenshot(playwright.PageScreenshotOptions{FullPage: playwright.Bool(true), Timeout: playwright.Float(5000)})
|
||||
snapshot.Frames, snapshot.Selectors = diagnosticFramesAndSelectors(page, d)
|
||||
for index, frame := range append([]playwright.Frame{page.MainFrame()}, page.Frames()...) {
|
||||
if htmlText, err := frame.Content(); err == nil {
|
||||
snapshot.FrameHTML[index] = htmlText
|
||||
}
|
||||
}
|
||||
d.mu.Lock()
|
||||
if d.initial.CapturedAt == "" {
|
||||
d.initial = snapshot
|
||||
}
|
||||
d.mu.Unlock()
|
||||
}
|
||||
|
||||
func (d *tokenCaptchaDiagnostic) writeBundle(page playwright.Page, phase string, cause error) (string, error) {
|
||||
if err := os.MkdirAll(d.dir, 0o700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
name := fmt.Sprintf("token-captcha-%s-%s-%s.zip", logsafe.ID(d.cookieID), d.startedAt.Format("20060102T150405.000000000Z"), sanitize(d.engine))
|
||||
target := filepath.Join(d.dir, name)
|
||||
tmp, err := os.CreateTemp(d.dir, ".token-captcha-*.zip.tmp")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer func() {
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(tmpName)
|
||||
}()
|
||||
zw := zip.NewWriter(tmp)
|
||||
closeZip := func(closeErr error) error {
|
||||
if closeErr != nil {
|
||||
_ = zw.Close()
|
||||
return closeErr
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmpName, target)
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
requests := append([]tokenCaptchaDiagnosticNetworkEvent(nil), d.requests...)
|
||||
responses := append([]tokenCaptchaDiagnosticNetworkEvent(nil), d.responses...)
|
||||
console := append([]tokenCaptchaDiagnosticConsoleEvent(nil), d.console...)
|
||||
pageErrors := append([]string(nil), d.pageError...)
|
||||
d.mu.Unlock()
|
||||
manifest := tokenCaptchaDiagnosticManifest{
|
||||
Version: 1,
|
||||
CreatedAt: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
CookieIDHash: logsafe.ID(d.cookieID),
|
||||
Engine: d.engine,
|
||||
Phase: phase,
|
||||
RequestedURL: d.safeURL(d.requestedURL),
|
||||
CurrentURL: d.safeURL(page.URL()),
|
||||
IncludeSensitive: d.includeSensitive,
|
||||
Requests: requests,
|
||||
Responses: responses,
|
||||
Console: console,
|
||||
PageErrors: pageErrors,
|
||||
}
|
||||
if cause != nil {
|
||||
manifest.Cause = cause.Error()
|
||||
}
|
||||
if title, titleErr := page.Title(); titleErr == nil {
|
||||
manifest.Title = title
|
||||
}
|
||||
manifest.PageState = diagnosticPageState(page, d.includeSensitive)
|
||||
manifest.Frames, manifest.Selectors = diagnosticFramesAndSelectors(page, d)
|
||||
d.mu.Lock()
|
||||
initial := d.initial
|
||||
initial.FrameHTML = cloneDiagnosticFrameHTML(initial.FrameHTML)
|
||||
initial.Screenshot = append([]byte(nil), initial.Screenshot...)
|
||||
d.mu.Unlock()
|
||||
manifest.InitialCapturedAt = initial.CapturedAt
|
||||
manifest.InitialFrames = initial.Frames
|
||||
manifest.InitialSelectors = initial.Selectors
|
||||
|
||||
manifestJSON, err := json.MarshalIndent(manifest, "", " ")
|
||||
if err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
if err := writeZipEntry(zw, "manifest.json", manifestJSON); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
readme := []byte("This archive was generated by the opt-in token CAPTCHA diagnostic mode.\n" +
|
||||
"It contains page/frame/selector/network metadata and a screenshot captured on failure.\n" +
|
||||
"Cookie values and verification query values are redacted unless CAPTCHA_DIAGNOSTIC_INCLUDE_SENSITIVE=1.\n")
|
||||
if err := writeZipEntry(zw, "README.txt", readme); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
if htmlText, htmlErr := page.Content(); htmlErr == nil {
|
||||
if !d.includeSensitive {
|
||||
htmlText = redactDiagnosticText(htmlText)
|
||||
}
|
||||
if err := writeZipEntry(zw, "page.html", []byte(htmlText)); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
if initial.PageHTML != "" {
|
||||
initialHTML := initial.PageHTML
|
||||
if !d.includeSensitive {
|
||||
initialHTML = redactDiagnosticText(initialHTML)
|
||||
}
|
||||
if err := writeZipEntry(zw, "initial/page.html", []byte(initialHTML)); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
for index, frameHTML := range initial.FrameHTML {
|
||||
if !d.includeSensitive {
|
||||
frameHTML = redactDiagnosticText(frameHTML)
|
||||
}
|
||||
if err := writeZipEntry(zw, fmt.Sprintf("initial/frames/frame-%02d.html", index), []byte(frameHTML)); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
if len(initial.Screenshot) > 0 {
|
||||
if err := writeZipEntry(zw, "initial/page.png", initial.Screenshot); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
for index, frame := range append([]playwright.Frame{page.MainFrame()}, page.Frames()...) {
|
||||
frameHTML, frameErr := frame.Content()
|
||||
if frameErr != nil {
|
||||
continue
|
||||
}
|
||||
if !d.includeSensitive {
|
||||
frameHTML = redactDiagnosticText(frameHTML)
|
||||
}
|
||||
if err := writeZipEntry(zw, fmt.Sprintf("frames/frame-%02d.html", index), []byte(frameHTML)); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
if screenshot, screenshotErr := page.Screenshot(playwright.PageScreenshotOptions{FullPage: playwright.Bool(true), Timeout: playwright.Float(5000)}); screenshotErr == nil {
|
||||
if err := writeZipEntry(zw, "page.png", screenshot); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
if err := closeZip(nil); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
func cloneDiagnosticFrameHTML(input map[int]string) map[int]string {
|
||||
if len(input) == 0 {
|
||||
return nil
|
||||
}
|
||||
output := make(map[int]string, len(input))
|
||||
for index, htmlText := range input {
|
||||
output[index] = htmlText
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
func writeZipEntry(zw *zip.Writer, name string, data []byte) error {
|
||||
writer, err := zw.Create(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = writer.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func diagnosticPageState(page playwright.Page, includeSensitive bool) map[string]any {
|
||||
value, err := page.Evaluate(`async () => {
|
||||
let userAgentData = null;
|
||||
if (navigator.userAgentData) {
|
||||
userAgentData = {
|
||||
brands: navigator.userAgentData.brands,
|
||||
mobile: navigator.userAgentData.mobile,
|
||||
platform: navigator.userAgentData.platform
|
||||
};
|
||||
try {
|
||||
userAgentData.high_entropy = await navigator.userAgentData.getHighEntropyValues([
|
||||
'architecture', 'bitness', 'fullVersionList', 'model', 'platformVersion', 'wow64'
|
||||
]);
|
||||
} catch (error) {
|
||||
userAgentData.high_entropy_error = String(error);
|
||||
}
|
||||
}
|
||||
return {
|
||||
ready_state: document.readyState,
|
||||
location_path: window.location.pathname,
|
||||
location_query_present: Boolean(window.location.search),
|
||||
inner_width: window.innerWidth,
|
||||
inner_height: window.innerHeight,
|
||||
device_pixel_ratio: window.devicePixelRatio,
|
||||
user_agent: navigator.userAgent,
|
||||
user_agent_data: userAgentData,
|
||||
webdriver: navigator.webdriver,
|
||||
has_nc_container: Boolean(document.querySelector('.nc-container')),
|
||||
has_errloading: Boolean(document.querySelector('.errloading')),
|
||||
body_text: (document.body && document.body.innerText || '').slice(0, 1200)
|
||||
};
|
||||
}`)
|
||||
if err != nil {
|
||||
return map[string]any{"error": err.Error()}
|
||||
}
|
||||
if state, ok := value.(map[string]any); ok {
|
||||
if body, ok := state["body_text"].(string); ok && !includeSensitive {
|
||||
state["body_text"] = redactDiagnosticText(body)
|
||||
}
|
||||
return state
|
||||
}
|
||||
return map[string]any{"value": value}
|
||||
}
|
||||
|
||||
func diagnosticFramesAndSelectors(page playwright.Page, d *tokenCaptchaDiagnostic) ([]tokenCaptchaDiagnosticFrame, []tokenCaptchaDiagnosticSelector) {
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
frameMetadata := make([]tokenCaptchaDiagnosticFrame, 0, len(frames))
|
||||
selectors := append([]string{}, sliderButtonSelectors...)
|
||||
selectors = append(selectors, sliderTrackSelectors...)
|
||||
selectors = append(selectors, sliderRetrySelectors...)
|
||||
for index, frame := range frames {
|
||||
parentURL := ""
|
||||
if parent := frame.ParentFrame(); parent != nil {
|
||||
parentURL = d.safeURL(parent.URL())
|
||||
}
|
||||
metadata := tokenCaptchaDiagnosticFrame{Index: index, Name: frame.Name(), URL: d.safeURL(frame.URL()), ParentURL: parentURL}
|
||||
if htmlText, err := frame.Content(); err == nil {
|
||||
metadata.HTMLBytes = len(htmlText)
|
||||
} else {
|
||||
metadata.ContentErr = err.Error()
|
||||
}
|
||||
frameMetadata = append(frameMetadata, metadata)
|
||||
}
|
||||
selectorRecords := make([]tokenCaptchaDiagnosticSelector, 0, len(frames)*len(selectors))
|
||||
for index, frame := range frames {
|
||||
frameURL := d.safeURL(frame.URL())
|
||||
for _, selector := range selectors {
|
||||
entry := tokenCaptchaDiagnosticSelector{FrameIndex: index, FrameURL: frameURL, Selector: selector}
|
||||
el, err := frame.QuerySelector(selector)
|
||||
if err != nil {
|
||||
entry.Error = err.Error()
|
||||
} else if el != nil {
|
||||
entry.Found = true
|
||||
entry.Visible = elementVisible(el)
|
||||
if box, boxErr := el.BoundingBox(); boxErr == nil {
|
||||
entry.Box = formatBoundingBox(box)
|
||||
}
|
||||
}
|
||||
selectorRecords = append(selectorRecords, entry)
|
||||
}
|
||||
}
|
||||
return frameMetadata, selectorRecords
|
||||
}
|
||||
|
||||
func redactDiagnosticText(text string) string {
|
||||
for _, key := range []string{"x5secdata", "x5sec", "_m_h5_tk", "_m_h5_tk_enc", "token", "sign"} {
|
||||
text = redactDiagnosticKey(text, key)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
func redactDiagnosticKey(text, key string) string {
|
||||
pattern := regexp.MustCompile(`(?i)` + regexp.QuoteMeta(key) + `=[^&'"<>\s\\` + "`" + `)]*`)
|
||||
return pattern.ReplaceAllStringFunc(text, func(match string) string {
|
||||
if index := strings.IndexByte(match, '='); index >= 0 {
|
||||
return match[:index+1] + "<redacted>"
|
||||
}
|
||||
return match
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
func TestTokenCaptchaDiagnosticRedactsSensitiveValues(t *testing.T) {
|
||||
d := &tokenCaptchaDiagnostic{includeSensitive: false}
|
||||
got := d.safeURL("https://example.test/punish?x5secdata=secret-value&action=captcha#fragment")
|
||||
if strings.Contains(got, "secret-value") || strings.Contains(got, "fragment") {
|
||||
t.Fatalf("safeURL leaked sensitive data: %q", got)
|
||||
}
|
||||
if !strings.Contains(got, "x5secdata") || !strings.Contains(got, "query_sha256") {
|
||||
t.Fatalf("safeURL lost query diagnostics: %q", got)
|
||||
}
|
||||
text := `x5secdata=secret-value&token=another-secret sign=third-secret`
|
||||
redacted := redactDiagnosticText(text)
|
||||
if strings.Contains(redacted, "secret-value") || strings.Contains(redacted, "another-secret") || strings.Contains(redacted, "third-secret") {
|
||||
t.Fatalf("redactDiagnosticText leaked sensitive data: %q", redacted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaDiagnosticBundleBrowserIntegration(t *testing.T) {
|
||||
if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" {
|
||||
t.Skip("set RUN_BROWSER_INTEGRATION=1 to exercise token CAPTCHA diagnostics")
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, `<!doctype html><html><head><title>诊断验证码</title></head><body>
|
||||
<div class="nc-container"><div id="nc_1_n1t" class="nc_scale" style="width:300px;height:34px"><span id="nc_1_n1z" class="nc_iconfont btn_slide" style="width:42px;height:34px"></span></div></div>
|
||||
</body></html>`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
dir := t.TempDir()
|
||||
t.Setenv(tokenCaptchaDiagnosticDirEnv, dir)
|
||||
t.Setenv(tokenCaptchaDiagnosticSensitiveEnv, "")
|
||||
m := NewManager(nil)
|
||||
defer m.Close()
|
||||
if err := m.init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
|
||||
Headless: playwright.Bool(true),
|
||||
Args: chromiumLaunchArgs(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = browser.Close() }()
|
||||
bctx, err := browser.NewContext()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = bctx.Close() }()
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
diagnostic := newTokenCaptchaDiagnostic("diagnostic-account", "playwright", server.URL+"/punish?x5secdata=secret", page, m.logger)
|
||||
if _, err := page.Goto(server.URL+"/punish?x5secdata=secret", playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
diagnostic.snapshotInitial(page)
|
||||
diagnostic.capture(page, "test_failure", io.ErrUnexpectedEOF)
|
||||
|
||||
archives, err := filepath.Glob(filepath.Join(dir, "*.zip"))
|
||||
if err != nil || len(archives) != 1 {
|
||||
t.Fatalf("diagnostic archive count=%d err=%v", len(archives), err)
|
||||
}
|
||||
archive, err := zip.OpenReader(archives[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer archive.Close()
|
||||
entries := make(map[string][]byte)
|
||||
for _, file := range archive.File {
|
||||
reader, readErr := file.Open()
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
data, readErr := io.ReadAll(reader)
|
||||
_ = reader.Close()
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
entries[file.Name] = data
|
||||
}
|
||||
for _, name := range []string{"README.txt", "manifest.json", "page.html", "page.png", "initial/page.html", "initial/page.png", "frames/frame-00.html", "initial/frames/frame-00.html"} {
|
||||
if len(entries[name]) == 0 {
|
||||
t.Fatalf("diagnostic archive missing %s", name)
|
||||
}
|
||||
}
|
||||
var manifest tokenCaptchaDiagnosticManifest
|
||||
if err := json.Unmarshal(entries["manifest.json"], &manifest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if manifest.Phase != "test_failure" || manifest.Engine != "playwright" {
|
||||
t.Fatalf("unexpected manifest: %+v", manifest)
|
||||
}
|
||||
if manifest.InitialCapturedAt == "" || len(manifest.InitialFrames) == 0 || len(manifest.InitialSelectors) == 0 {
|
||||
t.Fatalf("initial snapshot metadata missing: %+v", manifest)
|
||||
}
|
||||
if strings.Contains(string(entries["page.html"]), "secret") {
|
||||
t.Fatalf("page HTML leaked query value")
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ var fallbackTrackSelectors = []string{
|
||||
|
||||
// tokenCaptchaCDPFallback 直接启动 Chromium 并通过 CDP 连接,复现参考项目的
|
||||
// DrissionPage 第二引擎:它不复用 Playwright launch 协议,使用同一持久化目录和另一套轨迹。
|
||||
func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (string, error) {
|
||||
func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, _ TokenCaptchaURLProvider) (result string, resultErr error) {
|
||||
if strings.TrimSpace(cookieStr) == "" || strings.TrimSpace(verificationURL) == "" {
|
||||
return "", fmt.Errorf("备用滑块引擎参数不完整")
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS
|
||||
if strings.TrimSpace(executable) == "" {
|
||||
return "", fmt.Errorf("备用滑块引擎未找到 Chromium")
|
||||
}
|
||||
args := fallbackChromiumArgs(profileDir, headless)
|
||||
args := fallbackChromiumArgs(profileDir, headless, m.headlessUserAgent())
|
||||
cmd := exec.Command(executable, args...)
|
||||
cmd.Stdout = io.Discard
|
||||
cmd.Stderr = io.Discard
|
||||
@@ -96,11 +96,18 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS
|
||||
return "", fmt.Errorf("备用滑块引擎读取旧 Cookie: %w", err)
|
||||
}
|
||||
previousX5 := x5SecValues(before)
|
||||
page, err := bctx.NewPage()
|
||||
page, err := m.newBrowserPage(bctx, headless)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("备用滑块引擎创建页面: %w", err)
|
||||
}
|
||||
defer func() { _ = page.Close() }()
|
||||
diagnostic := newTokenCaptchaDiagnostic(cookieID, "drissionpage", verificationURL, page, m.logger)
|
||||
diagnosticSucceeded := false
|
||||
defer func() {
|
||||
if diagnostic != nil && !diagnosticSucceeded {
|
||||
diagnostic.capture(page, "drissionpage_failed", resultErr)
|
||||
}
|
||||
}()
|
||||
|
||||
deadline := time.Now().Add(drissionFallbackTimeout())
|
||||
if _, err := page.Goto(verificationURL, playwright.PageGotoOptions{
|
||||
@@ -116,6 +123,9 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS
|
||||
m.logger.Warn("备用滑块引擎页面没有可验证滑块,停止自动验证", "cookieID", cookieID, "err", pageErr)
|
||||
return "", pageErr
|
||||
}
|
||||
if diagnostic != nil {
|
||||
diagnostic.snapshotInitial(page)
|
||||
}
|
||||
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
if err := contextDeadlineError(ctx, deadline); err != nil {
|
||||
@@ -175,6 +185,7 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS
|
||||
merged[name] = value
|
||||
}
|
||||
m.logger.Info("备用滑块引擎验证成功", "cookieID", cookieID, "attempt", attempt+1)
|
||||
diagnosticSucceeded = true
|
||||
return cookieMarshal(merged), nil
|
||||
}
|
||||
logSliderFailureState(m.logger, page, attempt+1)
|
||||
@@ -189,7 +200,7 @@ func (m *Manager) tokenCaptchaCDPFallback(ctx context.Context, cookieID, cookieS
|
||||
return "", fmt.Errorf("备用滑块引擎 3 次均失败")
|
||||
}
|
||||
|
||||
func fallbackChromiumArgs(profileDir string, headless bool) []string {
|
||||
func fallbackChromiumArgs(profileDir string, headless bool, headlessUserAgent ...*string) []string {
|
||||
args := []string{
|
||||
"--user-data-dir=" + profileDir,
|
||||
"--remote-debugging-port=0",
|
||||
@@ -200,8 +211,16 @@ func fallbackChromiumArgs(profileDir string, headless bool) []string {
|
||||
"--no-first-run",
|
||||
"--window-size=1920,1080",
|
||||
"--lang=zh-CN",
|
||||
"about:blank",
|
||||
}
|
||||
if captchaIgnoreCertificateErrors() {
|
||||
args = append(args, "--ignore-certificate-errors")
|
||||
}
|
||||
if headless && len(headlessUserAgent) > 0 && headlessUserAgent[0] != nil {
|
||||
if userAgent := normalizeHeadlessUserAgent(*headlessUserAgent[0]); userAgent != "" {
|
||||
args = append(args, "--user-agent="+userAgent)
|
||||
}
|
||||
}
|
||||
args = append(args, "about:blank")
|
||||
if headless {
|
||||
args = append([]string{"--headless=new"}, args...)
|
||||
}
|
||||
|
||||
@@ -259,12 +259,16 @@ func TestFallbackUsableDistanceMatchesStandardNCDOM(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestFallbackChromiumArgsUsePersistentCDPProfile(t *testing.T) {
|
||||
args := strings.Join(fallbackChromiumArgs("/tmp/profile", true), " ")
|
||||
for _, want := range []string{"--headless=new", "--user-data-dir=/tmp/profile", "--remote-debugging-port=0", "--window-size=1920,1080", "--disable-blink-features=AutomationControlled"} {
|
||||
userAgent := "Mozilla/5.0 HeadlessChrome/149.0.7827.55 Safari/537.36"
|
||||
args := strings.Join(fallbackChromiumArgs("/tmp/profile", true, &userAgent), " ")
|
||||
for _, want := range []string{"--headless=new", "--user-data-dir=/tmp/profile", "--remote-debugging-port=0", "--window-size=1920,1080", "--disable-blink-features=AutomationControlled", "--user-agent=Mozilla/5.0 Chrome/149.0.7827.55 Safari/537.36"} {
|
||||
if !strings.Contains(args, want) {
|
||||
t.Fatalf("args 缺少 %q: %s", want, args)
|
||||
}
|
||||
}
|
||||
if strings.Contains(args, "HeadlessChrome") {
|
||||
t.Fatalf("备用 Chromium 参数仍暴露 HeadlessChrome: %s", args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForDevToolsEndpoint(t *testing.T) {
|
||||
|
||||
+101
-3
@@ -113,9 +113,10 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
||||
if lastMessageAt <= 0 {
|
||||
lastMessageAt = modifyTime
|
||||
}
|
||||
unreadCount := s.conversationUnreadCount(ctx, accountID, cid, peerID, conv, last, summary)
|
||||
session := db.ChatSession{CookieID: accountID, ChatID: cid, BuyerID: peerID, BuyerName: peerName, BuyerAvatar: avatar,
|
||||
ItemID: cleanNilString(ext["itemId"]), ItemTitle: cleanNilString(ext["itemTitle"]), LastMessage: summary,
|
||||
LastMessageAt: lastMessageAt, UnreadCount: int(int64Value(conv["redPoint"]))}
|
||||
LastMessageAt: lastMessageAt, UnreadCount: unreadCount}
|
||||
if err := s.store.Chats.UpsertSession(ctx, session); err != nil {
|
||||
return page, err
|
||||
}
|
||||
@@ -126,6 +127,69 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// conversationUnreadCount keeps redPoint as the platform's authoritative
|
||||
// signal, while using our message-level state for the number shown in the UI.
|
||||
// redPoint counts every unread item in a conversation, including trade cards
|
||||
// and official notices; only incoming non-system messages are user unread.
|
||||
func (s *Service) conversationUnreadCount(ctx context.Context, accountID, chatID, peerID string, conv, last map[string]any, summary string) int {
|
||||
official := int(int64Value(conv["redPoint"]))
|
||||
if official < 0 {
|
||||
official = 0
|
||||
}
|
||||
if official == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
if local, err := s.store.Chats.CountUnreadUserMessages(ctx, accountID, chatID); err == nil && local > 0 {
|
||||
// A stale local event must not make the badge exceed the official
|
||||
// conversation signal. In normal operation these values are equal.
|
||||
if local > official {
|
||||
return official
|
||||
}
|
||||
return local
|
||||
}
|
||||
|
||||
if !historyMessageIsSystem(last, summary) {
|
||||
// No message-level row exists yet (for example immediately after a
|
||||
// fresh login), so retain the official count as a safe fallback.
|
||||
return official
|
||||
}
|
||||
|
||||
// 闲小蜜会话只包含平台消息,永远不能制造用户红点。
|
||||
if strings.TrimSuffix(strings.TrimSpace(peerID), "@goofish") == "1400" {
|
||||
return 0
|
||||
}
|
||||
|
||||
// The official last-message envelope exposes unreadCount/readStatus for
|
||||
// that item. Subtract that system portion from redPoint; when older server
|
||||
// responses omit the fields, conservatively remove one system item.
|
||||
systemUnread := int(int64Value(last["unreadCount"]))
|
||||
readStatus := int64Value(last["readStatus"])
|
||||
if systemUnread <= 0 && readStatus != 2 {
|
||||
systemUnread = 1
|
||||
}
|
||||
if systemUnread > official {
|
||||
systemUnread = official
|
||||
}
|
||||
return official - systemUnread
|
||||
}
|
||||
|
||||
func historyMessageIsSystem(last map[string]any, summary string) bool {
|
||||
extension := mapValue(last["extension"])
|
||||
senderID := cleanNilString(extension["senderUserId"])
|
||||
content := map[string]any{}
|
||||
if contentMap, ok := last["content"].(map[string]any); ok {
|
||||
if custom, ok := contentMap["custom"].(map[string]any); ok {
|
||||
if encoded := cleanNilString(custom["data"]); encoded != "" {
|
||||
if raw, err := base64.StdEncoding.DecodeString(encoded); err == nil {
|
||||
_ = json.Unmarshal(raw, &content)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return isOfficialSystemMessage(content, senderID, summary)
|
||||
}
|
||||
|
||||
var invalidNicknames = map[string]struct{}{
|
||||
"交易消息": {}, "系统消息": {}, "卡片消息": {}, "我完成了评价": {}, "对方完成了评价": {},
|
||||
"快给ta一个评价吧~": {}, "卖家已发货": {}, "买家已付款": {}, "买家已确认收货": {},
|
||||
@@ -164,6 +228,7 @@ type Incoming struct {
|
||||
BuyerID string
|
||||
BuyerName string
|
||||
Text string
|
||||
MessageID string
|
||||
ItemID string
|
||||
Raw map[string]any
|
||||
}
|
||||
@@ -243,7 +308,10 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess
|
||||
if sentAt == 0 {
|
||||
sentAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
key := extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid")
|
||||
key := strings.TrimSpace(in.MessageID)
|
||||
if key == "" {
|
||||
key = extractString(in.Raw, "messageId", "message_id", "msgId", "uuid")
|
||||
}
|
||||
if key == "" {
|
||||
raw, _ := json.Marshal(in.Raw)
|
||||
digest := sha256.Sum256([]byte(in.AccountID + "\x00" + in.ChatID + "\x00" + in.BuyerID + "\x00" + in.Text + "\x00" + string(raw)))
|
||||
@@ -263,7 +331,10 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess
|
||||
}
|
||||
message := db.ChatMessage{MessageKey: key, Direction: "incoming", SenderID: in.BuyerID,
|
||||
SenderName: in.BuyerName, MessageType: messageType, Content: content, Status: "received", SentAt: sentAt}
|
||||
stored, inserted, err := s.store.Chats.SaveMessage(ctx, session, message, true)
|
||||
// Official notices may still reach this side channel when protocol fields
|
||||
// vary. They are rendered as system messages and must never create a user
|
||||
// unread badge.
|
||||
stored, inserted, err := s.store.Chats.SaveMessage(ctx, session, message, messageType != "system")
|
||||
if err == nil && inserted {
|
||||
s.Publish(in.AccountID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||
}
|
||||
@@ -527,6 +598,23 @@ func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status
|
||||
return message, err
|
||||
}
|
||||
|
||||
// MarkOutgoingRead records the platform's read receipt for an outgoing message.
|
||||
func (s *Service) MarkOutgoingRead(ctx context.Context, accountID, key string, readAt int64) (*db.ChatMessage, error) {
|
||||
message, err := s.store.Chats.MarkMessageRead(ctx, accountID, key, readAt)
|
||||
if err == nil {
|
||||
s.Publish(accountID, Event{Type: "message.updated", Message: message})
|
||||
}
|
||||
return message, err
|
||||
}
|
||||
|
||||
func (s *Service) MarkLatestOutgoingRead(ctx context.Context, accountID, chatID string, readAt int64) (*db.ChatMessage, error) {
|
||||
message, err := s.store.Chats.MarkLatestOutgoingRead(ctx, accountID, chatID, readAt)
|
||||
if err == nil {
|
||||
s.Publish(accountID, Event{Type: "message.updated", Message: message})
|
||||
}
|
||||
return message, err
|
||||
}
|
||||
|
||||
func randomID() string {
|
||||
var value [16]byte
|
||||
if _, err := rand.Read(value[:]); err == nil {
|
||||
@@ -562,6 +650,16 @@ func extractString(value any, keys ...string) string {
|
||||
return text
|
||||
}
|
||||
}
|
||||
case string:
|
||||
// Live WS envelopes often keep extJson/bizTag as an encoded JSON
|
||||
// string. Decode it so messageId is preserved instead of falling
|
||||
// back to a local in-* key.
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(x), &decoded) == nil {
|
||||
if text := walk(decoded); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -106,6 +106,24 @@ func TestRecordIncomingClassifiesXianxiaomiAndPlaceholder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordIncomingExtractsMessageIDFromEncodedExtension(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
service := New(store)
|
||||
message, _, err := service.RecordIncoming(context.Background(), Incoming{
|
||||
AccountID: "account-1", ChatID: "live", BuyerID: "peer", BuyerName: "对方", Text: "实时消息",
|
||||
Raw: map[string]any{"1": map[string]any{"10": map[string]any{
|
||||
"extJson": `{"messageId":"live-123"}`,
|
||||
}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if message.MessageKey != "live-123" {
|
||||
t.Fatalf("实时消息未提取平台 messageId: %+v", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
@@ -157,6 +175,7 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t
|
||||
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), "modifyTime": float64(123),
|
||||
"singleChatConversation": map[string]any{"cid": "xiaomi@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "1400"}},
|
||||
"redPoint": float64(3),
|
||||
"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 {
|
||||
@@ -167,11 +186,61 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar {
|
||||
if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar || rows[0].UnreadCount != 0 {
|
||||
t.Fatalf("unexpected sessions: %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConversationUnreadCountUsesRedPointButFiltersSystemMessages(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
service := New(store)
|
||||
|
||||
systemCard := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26}`))
|
||||
systemLast := map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"summary": "[交易通知]", "data": systemCard}},
|
||||
"unreadCount": float64(1), "readStatus": float64(1),
|
||||
}
|
||||
if got := service.conversationUnreadCount(context.Background(), "account-1", "system-last", "peer", map[string]any{"redPoint": float64(3)}, systemLast, "[交易通知]"); got != 2 {
|
||||
t.Fatalf("系统未读未从 redPoint 扣除: got=%d", got)
|
||||
}
|
||||
if got := service.conversationUnreadCount(context.Background(), "account-1", "xiaomi", "1400", map[string]any{"redPoint": float64(3)}, systemLast, "[交易通知]"); got != 0 {
|
||||
t.Fatalf("闲小蜜全是系统消息时仍显示红点: got=%d", got)
|
||||
}
|
||||
|
||||
if _, _, err := service.RecordIncoming(context.Background(), Incoming{
|
||||
AccountID: "account-1", ChatID: "real", BuyerID: "peer", BuyerName: "真实用户", Text: "未读消息",
|
||||
MessageID: "real-unread", Raw: map[string]any{"messageId": "real-unread"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
userLast := map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"summary": "未读消息"}},
|
||||
}
|
||||
if got := service.conversationUnreadCount(context.Background(), "account-1", "real", "peer", map[string]any{"redPoint": float64(3)}, userLast, "未读消息"); got != 1 {
|
||||
t.Fatalf("未使用消息级真实未读数: got=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryMessageIsSystem(t *testing.T) {
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26,"dxCard":{}}`))
|
||||
last := map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"data": encoded}},
|
||||
}
|
||||
if !historyMessageIsSystem(last, "[我已拍下,待付款]") {
|
||||
t.Fatal("交易卡片应被识别为系统消息")
|
||||
}
|
||||
if historyMessageIsSystem(map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"summary": "你好"}},
|
||||
}, "你好") {
|
||||
t.Fatal("真实用户文本不应被识别为系统消息")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
|
||||
+58
-8
@@ -33,6 +33,8 @@ type ChatMessage struct {
|
||||
MessageType string `json:"message_type"`
|
||||
Content string `json:"content"`
|
||||
Status string `json:"status"`
|
||||
ReadStatus int `json:"read_status"`
|
||||
ReadAt int64 `json:"read_at,omitempty"`
|
||||
SentAt int64 `json:"sent_at"`
|
||||
}
|
||||
|
||||
@@ -135,6 +137,13 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag
|
||||
if message.SentAt <= 0 {
|
||||
message.SentAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
// read_status is also used for incoming messages: only a newly received
|
||||
// real-user message starts unread. Imported history and official system
|
||||
// notices must never contribute to the chat badge.
|
||||
if message.Direction == "incoming" && (!unread || message.MessageType == "system") {
|
||||
message.ReadStatus = 2
|
||||
message.ReadAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
message.CookieID, message.ChatID = session.CookieID, session.ChatID
|
||||
now := time.Now().UTC().Unix()
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
@@ -155,11 +164,11 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag
|
||||
|
||||
prefix := dialectInsertIgnorePrefix(s.Dialect)
|
||||
query := prefix + ` INTO chat_messages
|
||||
(cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at,created_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "message_key"})
|
||||
(cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,read_status,read_at,sent_at,created_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "message_key"})
|
||||
res, err := tx.ExecContext(ctx, query, message.CookieID, message.ChatID, message.MessageKey,
|
||||
message.Direction, message.SenderID, message.SenderName, message.MessageType, message.Content,
|
||||
message.Status, message.SentAt, now)
|
||||
message.Status, message.ReadStatus, message.ReadAt, message.SentAt, now)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("保存聊天消息: %w", err)
|
||||
}
|
||||
@@ -188,10 +197,10 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag
|
||||
|
||||
func (s *ChatStore) GetMessageByKey(ctx context.Context, cookieID, key string) (*ChatMessage, error) {
|
||||
var m ChatMessage
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT id,cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT id,cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,read_status,read_at,sent_at
|
||||
FROM chat_messages WHERE cookie_id=? AND message_key=?`, cookieID, key).Scan(
|
||||
&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID, &m.SenderName,
|
||||
&m.MessageType, &m.Content, &m.Status, &m.SentAt)
|
||||
&m.MessageType, &m.Content, &m.Status, &m.ReadStatus, &m.ReadAt, &m.SentAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
@@ -234,7 +243,7 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
query := `SELECT m.id,m.cookie_id,m.chat_id,m.message_key,m.direction,m.sender_id,m.sender_name,m.message_type,m.content,m.status,m.sent_at
|
||||
query := `SELECT m.id,m.cookie_id,m.chat_id,m.message_key,m.direction,m.sender_id,m.sender_name,m.message_type,m.content,m.status,m.read_status,m.read_at,m.sent_at
|
||||
FROM chat_messages m JOIN cookies c ON c.id=m.cookie_id
|
||||
WHERE c.user_id=? AND m.cookie_id=? AND m.chat_id=?`
|
||||
args := []any{userID, cookieID, chatID}
|
||||
@@ -254,7 +263,7 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch
|
||||
for rows.Next() {
|
||||
var m ChatMessage
|
||||
if err := rows.Scan(&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID,
|
||||
&m.SenderName, &m.MessageType, &m.Content, &m.Status, &m.SentAt); err != nil {
|
||||
&m.SenderName, &m.MessageType, &m.Content, &m.Status, &m.ReadStatus, &m.ReadAt, &m.SentAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, m)
|
||||
@@ -267,15 +276,56 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch
|
||||
}
|
||||
|
||||
func (s *ChatStore) MarkRead(ctx context.Context, userID int64, cookieID, chatID string) error {
|
||||
now := time.Now().UTC()
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET read_status=2,read_at=?
|
||||
WHERE cookie_id=? AND chat_id=? AND direction='incoming' AND message_type<>'system' AND read_status<>2`,
|
||||
now.UnixMilli(), cookieID, chatID); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET unread_count=0,updated_at=?
|
||||
WHERE cookie_id=? AND chat_id=? AND EXISTS(SELECT 1 FROM cookies c WHERE c.id=chat_sessions.cookie_id AND c.user_id=?)`,
|
||||
time.Now().UTC().Unix(), cookieID, chatID, userID)
|
||||
now.Unix(), cookieID, chatID, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
// CountUnreadUserMessages returns the message-level unread count used by the
|
||||
// UI badge. It deliberately excludes official/system messages and relies on
|
||||
// read_status rather than the conversation summary counter.
|
||||
func (s *ChatStore) CountUnreadUserMessages(ctx context.Context, cookieID, chatID string) (int, error) {
|
||||
var count int
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM chat_messages
|
||||
WHERE cookie_id=? AND chat_id=? AND direction='incoming' AND message_type<>'system' AND read_status<>2`, cookieID, chatID).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (s *ChatStore) UpdateMessageStatus(ctx context.Context, cookieID, key, status string) (*ChatMessage, error) {
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET status=? WHERE cookie_id=? AND message_key=?`, status, cookieID, key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.GetMessageByKey(ctx, cookieID, key)
|
||||
}
|
||||
|
||||
func (s *ChatStore) MarkMessageRead(ctx context.Context, cookieID, key string, readAt int64) (*ChatMessage, error) {
|
||||
if readAt <= 0 {
|
||||
readAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET read_status=2,read_at=? WHERE cookie_id=? AND message_key=? AND direction='outgoing'`, readAt, cookieID, key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.GetMessageByKey(ctx, cookieID, key)
|
||||
}
|
||||
|
||||
func (s *ChatStore) MarkLatestOutgoingRead(ctx context.Context, cookieID, chatID string, readAt int64) (*ChatMessage, error) {
|
||||
if readAt <= 0 {
|
||||
readAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
var key string
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT message_key FROM chat_messages WHERE cookie_id=? AND chat_id=? AND direction='outgoing' AND status='sent' AND read_status<>2 ORDER BY sent_at DESC,id DESC LIMIT 1`, cookieID, chatID).Scan(&key)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.MarkMessageRead(ctx, cookieID, key, readAt)
|
||||
}
|
||||
@@ -128,8 +128,9 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
t.Fatalf("goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
// 依次回滚最新版本到 13,再整体升级。
|
||||
for i := 0; i < 15; i++ {
|
||||
// 依次回滚最新版本到 13,再整体升级。00029/00030 是聊天已读
|
||||
// 状态迁移,因此需要额外回滚两次才能到达原有的 migration 14 检查点。
|
||||
for i := 0; i < 17; i++ {
|
||||
if err := goose.Down(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("down migration #%d: %v", i+1, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE chat_messages ADD COLUMN read_status INT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE chat_messages ADD COLUMN read_at BIGINT NOT NULL DEFAULT 0;
|
||||
-- +goose Down
|
||||
ALTER TABLE chat_messages DROP COLUMN read_at;
|
||||
ALTER TABLE chat_messages DROP COLUMN read_status;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN UNIX_TIMESTAMP(CURRENT_TIMESTAMP) * 1000 ELSE read_at END
|
||||
WHERE direction='incoming' AND read_status=0;
|
||||
|
||||
-- +goose Down
|
||||
-- No safe reverse: the previous schema had no per-message read boundary.
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE chat_messages ADD COLUMN read_status INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE chat_messages ADD COLUMN read_at BIGINT NOT NULL DEFAULT 0;
|
||||
-- +goose Down
|
||||
ALTER TABLE chat_messages DROP COLUMN read_at;
|
||||
ALTER TABLE chat_messages DROP COLUMN read_status;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN (EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000)::BIGINT ELSE read_at END
|
||||
WHERE direction='incoming' AND read_status=0;
|
||||
|
||||
-- +goose Down
|
||||
-- No safe reverse: the previous schema had no per-message read boundary.
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE chat_messages ADD COLUMN read_status INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE chat_messages ADD COLUMN read_at INTEGER NOT NULL DEFAULT 0;
|
||||
-- +goose Down
|
||||
ALTER TABLE chat_messages DROP COLUMN read_at;
|
||||
ALTER TABLE chat_messages DROP COLUMN read_status;
|
||||
@@ -0,0 +1,8 @@
|
||||
-- +goose Up
|
||||
-- Messages already stored before message-level read tracking was introduced
|
||||
-- are history snapshots, not newly received unread messages.
|
||||
UPDATE chat_messages SET read_status=2, read_at=CASE WHEN read_at=0 THEN strftime('%s','now') * 1000 ELSE read_at END
|
||||
WHERE direction='incoming' AND read_status=0;
|
||||
|
||||
-- +goose Down
|
||||
-- No safe reverse: the previous schema had no per-message read boundary.
|
||||
@@ -771,7 +771,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
t.Fatalf("set goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
for i := 0; i < 15; i++ {
|
||||
for i := 0; i < 17; i++ {
|
||||
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration down #%d: %v", i+1, err)
|
||||
}
|
||||
|
||||
@@ -83,6 +83,19 @@ type Handler interface {
|
||||
OnAccountAlert(ctx context.Context, cookieID, level, title, body string)
|
||||
}
|
||||
|
||||
// MessageReadHandler receives platform read receipts. It is optional so older
|
||||
// integrations and tests remain valid.
|
||||
type MessageReadHandler interface {
|
||||
HandleMessageRead(context.Context, MessageReadEvent) error
|
||||
}
|
||||
|
||||
type MessageReadEvent struct {
|
||||
AccountID string
|
||||
ChatID string
|
||||
MessageID string
|
||||
ReadAt int64
|
||||
}
|
||||
|
||||
type accountEventHandler interface {
|
||||
OnAccountEvent(ctx context.Context, cookieID, eventType, level, title, body string)
|
||||
}
|
||||
@@ -121,6 +134,7 @@ type ChatMessage struct {
|
||||
SenderUserID string
|
||||
SenderName string
|
||||
Text string
|
||||
MessageID string
|
||||
ItemID string
|
||||
Raw map[string]any // 解密后的完整消息
|
||||
}
|
||||
@@ -1799,6 +1813,22 @@ func (a *Account) SendText(ctx context.Context, chatID, toUserID, text string) e
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Account) MarkChatRead(ctx context.Context, chatID string, messageIDs []map[string]any) error {
|
||||
conn, _, err := a.currentSenderState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
readCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
reader, ok := conn.(interface {
|
||||
MarkChatRead(context.Context, string, []map[string]any) error
|
||||
})
|
||||
if !ok {
|
||||
return fmt.Errorf("当前 WebSocket 不支持已读上报")
|
||||
}
|
||||
return reader.MarkChatRead(readCtx, chatID, messageIDs)
|
||||
}
|
||||
|
||||
// SendImage 通过当前 WebSocket 给买家发送图片消息。当前仅支持可直接访问的 CDN/公网 URL。
|
||||
func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64) error {
|
||||
imageURL = strings.TrimSpace(imageURL)
|
||||
|
||||
+191
-3
@@ -3,11 +3,14 @@ package engine
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
// dispatch 是 ws.ReceiveLoop 的回调,对每条解密后的消息做:
|
||||
@@ -59,6 +62,17 @@ func (a *Account) handleMessage(decrypted map[string]any) {
|
||||
}
|
||||
|
||||
func (a *Account) handleMessageContext(ctx context.Context, decrypted map[string]any) {
|
||||
if receipt, ok := extractMessageReadEvent(decrypted); ok {
|
||||
receipt.AccountID = a.CookieID
|
||||
if h, ok := a.handler.(MessageReadHandler); ok {
|
||||
if err := h.HandleMessageRead(ctx, receipt); err != nil {
|
||||
a.logger.Warn("处理聊天已读回执失败", "err", err, "message_id", receipt.MessageID)
|
||||
}
|
||||
} else {
|
||||
a.logger.Debug("收到聊天已读回执,但未接入处理器", "message_id", receipt.MessageID)
|
||||
}
|
||||
return
|
||||
}
|
||||
// 第一优先级:系统卡片和平台通知进入自动化中心。
|
||||
// 这里不判断具体业务,只做“平台事件”事实解析;系统消息永远不进入 AI 回复范围。
|
||||
if task := automation.ExtractTaskFromWS(a.CookieID, a.currentCookieStr(), decrypted); task != nil {
|
||||
@@ -69,6 +83,10 @@ func (a *Account) handleMessageContext(ctx context.Context, decrypted map[string
|
||||
}
|
||||
return
|
||||
}
|
||||
if senderUserID := extractChatSenderUserID(decrypted); isSelfUserID(senderUserID, protocol.TransCookies(a.currentCookieStr())["unb"]) {
|
||||
a.logger.Info("忽略账号自身发送的 WebSocket 聊天回显", "chat_id", extractChatID(decrypted), "sender_id", senderUserID)
|
||||
return
|
||||
}
|
||||
|
||||
chat := extractChatMessage(decrypted, a.CookieID, a.currentCookieStr())
|
||||
if chat != nil && chat.Text != "" {
|
||||
@@ -82,6 +100,89 @@ func (a *Account) handleMessageContext(ctx context.Context, decrypted map[string
|
||||
}
|
||||
}
|
||||
|
||||
func extractMessageReadEvent(v map[string]any) (MessageReadEvent, bool) {
|
||||
// 40103 解密后不会保留外层 objectType,只剩下固定的紧凑字段:
|
||||
// 1=PNM 消息 ID、2=状态(2=已读)、4=会话 ID、6=事件时间。
|
||||
// 不能只在解密后的 map 里继续寻找 "bizType":40103,否则真实回执
|
||||
// 会被当成普通消息静默丢弃。
|
||||
messageID := strings.TrimSpace(toString(v["1"]))
|
||||
if ids, ok := v["1"].([]any); ok && len(ids) > 0 {
|
||||
messageID = strings.TrimSpace(toString(ids[0]))
|
||||
}
|
||||
if strings.HasSuffix(messageID, ".PNM") && toString(v["2"]) == "2" {
|
||||
chatID := strings.TrimSpace(toString(v["4"]))
|
||||
if !strings.Contains(chatID, "@goofish") {
|
||||
chatID = strings.TrimSpace(toString(v["3"]))
|
||||
}
|
||||
chatID = strings.TrimSuffix(chatID, "@goofish")
|
||||
return MessageReadEvent{ChatID: chatID, MessageID: messageID, ReadAt: time.Now().UTC().UnixMilli()}, true
|
||||
}
|
||||
var found bool
|
||||
var ev MessageReadEvent
|
||||
var walk func(any)
|
||||
walk = func(x any) {
|
||||
if found {
|
||||
return
|
||||
}
|
||||
switch m := x.(type) {
|
||||
case map[string]any:
|
||||
for k, val := range m {
|
||||
lk := strings.ToLower(k)
|
||||
if lk == "biztype" || lk == "biz_type" || lk == "type" {
|
||||
if toString(val) == "40103" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if found {
|
||||
ev.MessageID = extractNestedString(m, "messageid", "message_id")
|
||||
ev.ChatID = extractNestedString(m, "cid", "chatid", "chat_id")
|
||||
if ev.MessageID == "" {
|
||||
ev.MessageID = extractNestedString(m, "id")
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, child := range m {
|
||||
walk(child)
|
||||
}
|
||||
case []any:
|
||||
for _, child := range m {
|
||||
walk(child)
|
||||
}
|
||||
case string:
|
||||
// Some sync envelopes carry the event body as an escaped JSON
|
||||
// string instead of an already-decoded object.
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(m), &decoded) == nil {
|
||||
walk(decoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(v)
|
||||
if !found || ev.MessageID == "" {
|
||||
return MessageReadEvent{}, false
|
||||
}
|
||||
return ev, true
|
||||
}
|
||||
|
||||
func extractNestedString(m map[string]any, keys ...string) string {
|
||||
for k, v := range m {
|
||||
for _, want := range keys {
|
||||
if strings.EqualFold(k, want) && strings.TrimSpace(toString(v)) != "" {
|
||||
return strings.TrimSpace(toString(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, v := range m {
|
||||
if child, ok := v.(map[string]any); ok {
|
||||
if s := extractNestedString(child, keys...); s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// markAndCheckDedup 提取消息 ID,检查 1 小时内是否已处理;未处理则标记。
|
||||
// 返回 true 表示应继续处理。移植自 _schedule_debounced_reply 的去重段。
|
||||
func (a *Account) markAndCheckDedup(decrypted map[string]any, chat *ChatMessage) bool {
|
||||
@@ -183,13 +284,21 @@ func (a *Account) scheduleDebouncedReply(chat ChatMessage) {
|
||||
})
|
||||
}
|
||||
|
||||
// extractMessageID 从 message["1"]["10"]["bizTag"] 或 extJson 中提取 messageId。
|
||||
// 移植自 _extract_message_id。
|
||||
// extractMessageID 提取闲鱼消息状态接口使用的消息 ID。
|
||||
//
|
||||
// 实时 WS 聊天消息同时包含两种 ID:message["1"]["3"] 是消息在 IM
|
||||
// 服务中的 PNM ID,/r/MessageStatus/read 使用的正是这个 ID;10.bizTag、
|
||||
// extJson 和 reminderUrl 里的 messageId 是通知/推送侧的关联 ID,不能用来
|
||||
// 上报会话已读。历史消息接口也返回 PNM ID,因此优先使用字段 3,其他
|
||||
// 字段只作为兼容旧消息或缺失字段 3 的兜底。
|
||||
func extractMessageID(decrypted map[string]any) string {
|
||||
m1, ok := decrypted["1"].(map[string]any)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
if id := strings.TrimSpace(toString(m1["3"])); id != "" && id != "<nil>" {
|
||||
return id
|
||||
}
|
||||
m10, ok := m1["10"].(map[string]any)
|
||||
if !ok {
|
||||
return ""
|
||||
@@ -205,6 +314,43 @@ func extractMessageID(decrypted map[string]any) string {
|
||||
return id
|
||||
}
|
||||
}
|
||||
if reminderURL, _ := m10["reminderUrl"].(string); reminderURL != "" {
|
||||
if parsed, err := url.Parse(reminderURL); err == nil {
|
||||
if id := strings.TrimSpace(parsed.Query().Get("messageId")); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
return findMessageID(decrypted)
|
||||
}
|
||||
|
||||
func findMessageID(value any) string {
|
||||
switch x := value.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range x {
|
||||
if strings.EqualFold(key, "messageId") || strings.EqualFold(key, "message_id") {
|
||||
if id := strings.TrimSpace(fmt.Sprint(child)); id != "" && id != "<nil>" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, child := range x {
|
||||
if id := findMessageID(child); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, child := range x {
|
||||
if id := findMessageID(child); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
case string:
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(x), &decoded) == nil {
|
||||
return findMessageID(decoded)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -241,7 +387,13 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
|
||||
if i := strings.Index(chatID, "@"); i >= 0 {
|
||||
chatID = chatID[:i]
|
||||
}
|
||||
senderUserID, _ := m10["senderUserId"].(string)
|
||||
senderUserID := extractChatSenderUserIDFromMaps(m1, m10)
|
||||
if isSelfUserID(senderUserID, protocol.TransCookies(cookieStr)["unb"]) {
|
||||
// The official client echoes messages sent by this account over the
|
||||
// same WebSocket. They are delivery observations, not new buyer input,
|
||||
// and must never enter the automatic-reply pipeline.
|
||||
return nil
|
||||
}
|
||||
senderName, _ := m10["senderNick"].(string)
|
||||
if strings.TrimSpace(senderName) == "" {
|
||||
senderName, _ = m10["reminderTitle"].(string)
|
||||
@@ -255,11 +407,47 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
|
||||
SenderUserID: senderUserID,
|
||||
SenderName: senderName,
|
||||
Text: reminder,
|
||||
MessageID: extractMessageID(decrypted),
|
||||
ItemID: itemID,
|
||||
Raw: decrypted,
|
||||
}
|
||||
}
|
||||
|
||||
func extractChatSenderUserID(decrypted map[string]any) string {
|
||||
m1, _ := decrypted["1"].(map[string]any)
|
||||
if m1 == nil {
|
||||
return ""
|
||||
}
|
||||
m10, _ := m1["10"].(map[string]any)
|
||||
return extractChatSenderUserIDFromMaps(m1, m10)
|
||||
}
|
||||
|
||||
func extractChatSenderUserIDFromMaps(m1, m10 map[string]any) string {
|
||||
if m10 != nil {
|
||||
if sender := strings.TrimSpace(toString(m10["senderUserId"])); sender != "" {
|
||||
return sender
|
||||
}
|
||||
}
|
||||
// Some echoed messages omit 10.senderUserId but retain the sender in the
|
||||
// compact 1.1 envelope.
|
||||
if sender, ok := m1["1"].(map[string]any); ok {
|
||||
return strings.TrimSpace(toString(sender["1"]))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractChatID(decrypted map[string]any) string {
|
||||
m1, _ := decrypted["1"].(map[string]any)
|
||||
chatID := strings.TrimSpace(toString(m1["2"]))
|
||||
return strings.TrimSuffix(chatID, "@goofish")
|
||||
}
|
||||
|
||||
func isSelfUserID(senderUserID, selfUserID string) bool {
|
||||
sender := strings.TrimSuffix(strings.TrimSpace(senderUserID), "@goofish")
|
||||
self := strings.TrimSuffix(strings.TrimSpace(selfUserID), "@goofish")
|
||||
return sender != "" && self != "" && sender == self
|
||||
}
|
||||
|
||||
// isNonUserChatNotice 判断闲鱼 IM 中不应进入自动回复的系统提示或交易卡片。
|
||||
// 典型样本:
|
||||
// - contentType=14:“有蚂蚁森林能量可领”“不想宝贝被砍价?设置不砍价回复”“退款成功”
|
||||
|
||||
@@ -135,6 +135,22 @@ func TestHandleMessage_DedupSkipsRepeat(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMessage_IgnoresOwnWebSocketEcho(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
// newAccountForTest 使用 unb=123;模拟同一账号在闲鱼官方客户端发出的
|
||||
// 消息回显,不能进入自动回复或业务消息处理链。
|
||||
acc.handleMessage(plainChatMessage(t, "官方客户端发送", "123", "chat-own"))
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 0 {
|
||||
t.Fatalf("账号自身消息回显不应触发自动回复,got %d", len(h.chats))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMessage_NoReminderNoOp 无 reminderContent 的消息不进入回复链也不报错。
|
||||
func TestHandleMessage_NoReminderNoOp(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
@@ -522,3 +538,19 @@ func plainChatMessage(t *testing.T, text, senderUserID, chatID string) map[strin
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestExtractMessageReadEvent40103(t *testing.T) {
|
||||
event, ok := extractMessageReadEvent(map[string]any{
|
||||
"1": "4263141580162.PNM", "2": 2, "3": 0,
|
||||
"4": "64725235816@goofish", "5": 1, "6": 1786945729928,
|
||||
})
|
||||
if !ok || event.MessageID != "4263141580162.PNM" || event.ChatID != "64725235816" || event.ReadAt <= 0 {
|
||||
t.Fatalf("40103 event=%+v ok=%v", event, ok)
|
||||
}
|
||||
batch, ok := extractMessageReadEvent(map[string]any{
|
||||
"1": []any{"4263107993838.PNM"}, "2": 2, "3": "64725235816@goofish", "4": 1,
|
||||
})
|
||||
if !ok || batch.MessageID != "4263107993838.PNM" || batch.ChatID != "64725235816" {
|
||||
t.Fatalf("40103 batch event=%+v ok=%v", batch, ok)
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,16 @@ func TestExtractChatMessageUsesReminderTitleAsNickname(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractChatMessageIgnoresOwnWebSocketEcho(t *testing.T) {
|
||||
decrypted := map[string]any{"1": map[string]any{
|
||||
"2": "chat-1@goofish",
|
||||
"10": map[string]any{"reminderContent": "我在官方客户端发送的消息", "senderUserId": "self-1", "senderNick": "我"},
|
||||
}}
|
||||
if chat := extractChatMessage(decrypted, "account-1", "unb=self-1;"); chat != nil {
|
||||
t.Fatalf("账号自身发送的 WS 回显不应进入自动回复链: %+v", chat)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractChatMessage_FiltersRefundTradeCard(t *testing.T) {
|
||||
decrypted := mustRefundTradeCard(t)
|
||||
if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
|
||||
|
||||
@@ -216,17 +216,18 @@ func TestParseMessageIDFromJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractMessageID 优先 bizTag,其次 extJson,无则空。
|
||||
// TestExtractMessageID 优先实时消息的 PNM ID,其次兼容 bizTag/extJson,无则空。
|
||||
func TestExtractMessageID(t *testing.T) {
|
||||
if got := extractMessageID(map[string]any{
|
||||
"1": map[string]any{
|
||||
"3": "4263141580162.PNM",
|
||||
"10": map[string]any{
|
||||
"bizTag": `{"messageId":"biz-id"}`,
|
||||
"extJson": `{"messageId":"ext-id"}`,
|
||||
},
|
||||
},
|
||||
}); got != "biz-id" {
|
||||
t.Errorf("bizTag 优先: got %q", got)
|
||||
}); got != "4263141580162.PNM" {
|
||||
t.Errorf("PNM 优先: got %q", got)
|
||||
}
|
||||
if got := extractMessageID(map[string]any{
|
||||
"1": map[string]any{
|
||||
|
||||
@@ -121,3 +121,34 @@ func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindChatPlatformMessageID(t *testing.T) {
|
||||
raw := map[string]any{
|
||||
"1": map[string]any{
|
||||
"2": "64725235816@goofish",
|
||||
"3": "4263141580162.PNM",
|
||||
"10": map[string]any{
|
||||
"extJson": `{"messageId":"f87f8f6dabca4eff940863ef72a393f7"}`,
|
||||
},
|
||||
},
|
||||
}
|
||||
if got := findChatPlatformMessageID(raw, "64725235816", "f87f8f6dabca4eff940863ef72a393f7"); got != "4263141580162.PNM" {
|
||||
t.Fatalf("platform message id=%q", got)
|
||||
}
|
||||
if got := findChatPlatformMessageID(raw, "other-chat", "f87f8f6dabca4eff940863ef72a393f7"); got != "" {
|
||||
t.Fatalf("跨会话错误匹配: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveChatReadMessageIDsMigratesLegacyID(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
raw := `{"1":{"2":"64725235816@goofish","3":"4263141580162.PNM","10":{"extJson":"{\"messageId\":\"f87f8f6dabca4eff940863ef72a393f7\"}"}}}`
|
||||
if err := store.WSMessages.Add(context.Background(), db.WSMessage{CookieID: "acc1", Direction: "in", ParsedJSON: raw, ParseStatus: "decrypted"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := srv.resolveChatReadMessageIDs(context.Background(), "acc1", "64725235816", []map[string]any{{"messageId": "f87f8f6dabca4eff940863ef72a393f7"}})
|
||||
if len(got) != 1 || got[0]["messageId"] != "4263141580162.PNM" {
|
||||
t.Fatalf("resolved=%+v", got)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,10 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -367,8 +370,9 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
AccountID string `json:"account_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
AccountID string `json:"account_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
MessageIDs []map[string]any `json:"message_ids"`
|
||||
}
|
||||
if decodeJSON(r, &input) != nil || input.ChatID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
@@ -378,14 +382,162 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
slog.Info("收到聊天已读请求", "account", input.AccountID, "chat_id", input.ChatID, "message_count", len(input.MessageIDs))
|
||||
if len(input.MessageIDs) == 0 {
|
||||
// 兼容只传会话 ID 的调用方:从本地最近消息补齐平台消息 ID。
|
||||
userID := auth.SessionFromContext(r.Context()).UserID
|
||||
if rows, err := s.Store.Chats.ListMessages(r.Context(), userID, input.AccountID, input.ChatID, 0, 200); err == nil {
|
||||
for _, row := range rows {
|
||||
if row.Direction == "incoming" && row.MessageType != "system" {
|
||||
input.MessageIDs = append(input.MessageIDs, map[string]any{"messageId": row.MessageKey})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 旧版本把实时 WS 通知里的 bizTag/extJson messageId 当成了平台消息
|
||||
// ID,数据库里会留下 32 位关联 ID。闲鱼的 read 接口实际要求 1.3 的
|
||||
// PNM ID;这里从已保存的解密 WS 诊断帧把旧 ID 转回 PNM,避免升级后
|
||||
// 仍有历史实时消息无法被标记已读。
|
||||
input.MessageIDs = s.resolveChatReadMessageIDs(r.Context(), input.AccountID, input.ChatID, input.MessageIDs)
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if err := s.Store.Chats.MarkRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新已读状态失败")
|
||||
return
|
||||
}
|
||||
if s.Manager != nil {
|
||||
if sender, ok := s.Manager.GetInstance(input.AccountID); ok {
|
||||
if reader, ok := sender.(interface {
|
||||
MarkChatRead(context.Context, string, []map[string]any) error
|
||||
}); ok {
|
||||
if err := reader.MarkChatRead(r.Context(), input.ChatID, input.MessageIDs); err != nil {
|
||||
slog.Warn("上报闲鱼已读状态失败", "account", input.AccountID, "chat_id", input.ChatID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) resolveChatReadMessageIDs(ctx context.Context, accountID, chatID string, messageIDs []map[string]any) []map[string]any {
|
||||
if s == nil || s.Store == nil || s.Store.DB == nil {
|
||||
return messageIDs
|
||||
}
|
||||
resolved := make([]map[string]any, 0, len(messageIDs))
|
||||
seen := make(map[string]struct{}, len(messageIDs))
|
||||
for _, item := range messageIDs {
|
||||
id := strings.TrimSpace(fmt.Sprint(item["messageId"]))
|
||||
if id == "" || id == "<nil>" {
|
||||
continue
|
||||
}
|
||||
if !strings.HasSuffix(id, ".PNM") {
|
||||
if platformID := s.lookupChatPlatformMessageID(ctx, accountID, chatID, id); platformID != "" {
|
||||
slog.Info("已将旧聊天消息 ID 转换为平台 PNM", "account", accountID, "chat_id", chatID, "old_message_id", id, "message_id", platformID)
|
||||
id = platformID
|
||||
} else {
|
||||
slog.Warn("未找到旧聊天消息对应的 PNM,跳过已读上报", "account", accountID, "chat_id", chatID, "message_id", id)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
copyItem := make(map[string]any, len(item)+1)
|
||||
for key, value := range item {
|
||||
copyItem[key] = value
|
||||
}
|
||||
copyItem["messageId"] = id
|
||||
resolved = append(resolved, copyItem)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
func (s *Server) lookupChatPlatformMessageID(ctx context.Context, accountID, chatID, legacyID string) string {
|
||||
rows, err := s.Store.DB.QueryContext(ctx, `SELECT parsed_json FROM ws_messages
|
||||
WHERE cookie_id=? AND direction='in' AND parse_status='decrypted' AND parsed_json LIKE ?
|
||||
ORDER BY id DESC LIMIT 20`, accountID, "%"+legacyID+"%")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
if rows.Scan(&raw) != nil {
|
||||
continue
|
||||
}
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(raw), &decoded) != nil {
|
||||
continue
|
||||
}
|
||||
if platformID := findChatPlatformMessageID(decoded, chatID, legacyID); platformID != "" {
|
||||
return platformID
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func findChatPlatformMessageID(value any, chatID, legacyID string) string {
|
||||
var walk func(any) string
|
||||
walk = func(current any) string {
|
||||
switch typed := current.(type) {
|
||||
case map[string]any:
|
||||
if m10, ok := typed["10"]; ok && chatReadValueContainsID(m10, legacyID) {
|
||||
if candidate := strings.TrimSpace(fmt.Sprint(typed["3"])); strings.HasSuffix(candidate, ".PNM") {
|
||||
if cid := strings.TrimSuffix(strings.TrimSpace(fmt.Sprint(typed["2"])), "@goofish"); cid == "" || cid == chatID {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, child := range typed {
|
||||
if candidate := walk(child); candidate != "" {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, child := range typed {
|
||||
if candidate := walk(child); candidate != "" {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
case string:
|
||||
var nested any
|
||||
if json.Unmarshal([]byte(typed), &nested) == nil {
|
||||
return walk(nested)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return walk(value)
|
||||
}
|
||||
|
||||
func chatReadValueContainsID(value any, legacyID string) bool {
|
||||
switch typed := value.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range typed {
|
||||
if strings.EqualFold(key, "messageId") || strings.EqualFold(key, "message_id") {
|
||||
if strings.TrimSpace(fmt.Sprint(child)) == legacyID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if chatReadValueContainsID(child, legacyID) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, child := range typed {
|
||||
if chatReadValueContainsID(child, legacyID) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case string:
|
||||
var nested any
|
||||
if json.Unmarshal([]byte(typed), &nested) == nil {
|
||||
return chatReadValueContainsID(nested, legacyID)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
if s.chat == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
|
||||
@@ -110,7 +110,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
defer cancel()
|
||||
client := s.mtopClient()
|
||||
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
|
||||
res, callErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{
|
||||
publishReq := mtop.PublishItemRequest{
|
||||
Title: title,
|
||||
Description: description,
|
||||
PriceCents: priceCents,
|
||||
@@ -121,7 +121,8 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
Virtual: true,
|
||||
Location: selectedLocation,
|
||||
Images: images,
|
||||
})
|
||||
}
|
||||
res, callErr := client.PublishItem(mtopCtx, cookieValue, publishReq)
|
||||
runtimeCookie := ""
|
||||
runtimeCookieChanged := false
|
||||
var responseCookieErr error
|
||||
@@ -151,25 +152,47 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
if responseCookieErr != nil {
|
||||
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", responseCookieErr))
|
||||
}
|
||||
s.recoverExpiredMTOPSession(r.Context(), cookieID, callErr)
|
||||
var perr *mtop.PublishError
|
||||
if errors.As(callErr, &perr) {
|
||||
status := http.StatusBadGateway
|
||||
msg := perr.Error()
|
||||
if perr.Code == mtop.PublishErrorStockPermissionMissing {
|
||||
status = http.StatusForbidden
|
||||
msg = "该账号没有库存发布权限,无法按库存数量发布商品"
|
||||
// Session 失效是账号级凭证问题。续期成功后,当前发布请求仍然
|
||||
// 可以安全重试一次:平台已经明确拒绝了这次业务调用,不会把
|
||||
// 同一商品重复发布。重试前重新读取 Cookie,避免继续使用旧会话。
|
||||
if mtop.IsSessionExpiredErr(callErr) && s.recoverExpiredMTOPSession(r.Context(), cookieID, callErr) {
|
||||
retryRes, retryErr, retryCookieErr, credentialChanged := s.retryPublishItemAfterRenewal(ctx, cookieID, userID, publishReq)
|
||||
if credentialChanged {
|
||||
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
|
||||
return
|
||||
}
|
||||
writeJSON(w, status, map[string]any{
|
||||
"success": false,
|
||||
"code": perr.Code,
|
||||
"message": msg,
|
||||
"ret": perr.Ret,
|
||||
})
|
||||
if retryErr == nil && retryRes != nil {
|
||||
res = retryRes
|
||||
callErr = nil
|
||||
responseCookieErr = retryCookieErr
|
||||
} else if retryErr != nil {
|
||||
callErr = retryErr
|
||||
responseCookieErr = retryCookieErr
|
||||
}
|
||||
}
|
||||
if callErr == nil {
|
||||
// The renewed attempt succeeded; continue through the normal local
|
||||
// persistence and success response path below.
|
||||
} else {
|
||||
var perr *mtop.PublishError
|
||||
if errors.As(callErr, &perr) {
|
||||
status := http.StatusBadGateway
|
||||
msg := perr.Error()
|
||||
if perr.Code == mtop.PublishErrorStockPermissionMissing {
|
||||
status = http.StatusForbidden
|
||||
msg = "该账号没有库存发布权限,无法按库存数量发布商品"
|
||||
}
|
||||
writeJSON(w, status, map[string]any{
|
||||
"success": false,
|
||||
"code": perr.Code,
|
||||
"message": msg,
|
||||
"ret": perr.Ret,
|
||||
})
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusBadGateway, callErr.Error())
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusBadGateway, callErr.Error())
|
||||
return
|
||||
}
|
||||
if res == nil || strings.TrimSpace(res.ItemID) == "" {
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{
|
||||
@@ -233,6 +256,51 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// retryPublishItemAfterRenewal re-reads the account credential after a
|
||||
// successful Session renewal and repeats one rejected publish attempt. The
|
||||
// caller already owns the parsed images and request payload, so this method
|
||||
// deliberately does not re-parse the multipart body.
|
||||
func (s *Server) retryPublishItemAfterRenewal(
|
||||
ctx context.Context,
|
||||
cookieID string,
|
||||
userID int64,
|
||||
req mtop.PublishItemRequest,
|
||||
) (result *mtop.PublishItemResult, callErr, cookieErr error, credentialChanged bool) {
|
||||
credentialUnlock := s.Store.LockAccountCredentials(cookieID)
|
||||
defer credentialUnlock()
|
||||
latest, err := s.Store.Cookies.GetDetails(ctx, cookieID)
|
||||
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
|
||||
return nil, nil, nil, true
|
||||
}
|
||||
cookieValue := latest.Value
|
||||
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
|
||||
result, callErr = s.mtopClient().PublishItem(mtopCtx, cookieValue, req)
|
||||
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
|
||||
if persistErr != nil {
|
||||
cookieErr = persistErr
|
||||
if s.Logger != nil {
|
||||
s.Logger.Error("保存重试发布响应 Cookie Jar 失败", "cookie_id", cookieID, "err", persistErr)
|
||||
}
|
||||
} else if handled {
|
||||
if valueChanged {
|
||||
s.updateRunningCookie(ctx, cookieID, value)
|
||||
}
|
||||
} else if callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != cookieValue {
|
||||
if err := s.Store.Cookies.UpdateValueOwned(ctx, cookieID, result.UpdatedCookies, userID); err != nil {
|
||||
cookieErr = err
|
||||
if s.Logger != nil {
|
||||
s.Logger.Error("保存重试发布响应 Cookie 失败", "cookie_id", cookieID, "err", err)
|
||||
}
|
||||
} else {
|
||||
s.updateRunningCookie(ctx, cookieID, result.UpdatedCookies)
|
||||
}
|
||||
}
|
||||
if cookieErr != nil && callErr != nil {
|
||||
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", cookieErr))
|
||||
}
|
||||
return result, callErr, cookieErr, false
|
||||
}
|
||||
|
||||
func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, error) {
|
||||
if r.MultipartForm == nil || r.MultipartForm.File == nil {
|
||||
return nil, errors.New("至少上传 1 张商品图片")
|
||||
|
||||
@@ -317,6 +317,33 @@ func TestPublishItemReportsRemoteSuccessLocalSaveFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryPublishItemAfterRenewalUsesFreshCredential(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
admin, err := store.Users.GetByUsername(context.Background(), "admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Cookies.UpdateValueExisting(context.Background(), "acc1", "unb=123; fresh=1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var gotCookies string
|
||||
srv.MTop = &stubPublishMTop{publish: func(_ context.Context, cookies string, _ mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
|
||||
gotCookies = cookies
|
||||
return &mtop.PublishItemResult{ItemID: "retry-item", Title: "重试商品"}, nil
|
||||
}}
|
||||
result, callErr, cookieErr, changed := srv.retryPublishItemAfterRenewal(
|
||||
context.Background(), "acc1", admin.ID,
|
||||
mtop.PublishItemRequest{Title: "重试商品", PriceCents: 100, Quantity: 1},
|
||||
)
|
||||
if changed || callErr != nil || cookieErr != nil || result == nil || result.ItemID != "retry-item" {
|
||||
t.Fatalf("重试结果异常: result=%+v callErr=%v cookieErr=%v changed=%v", result, callErr, cookieErr, changed)
|
||||
}
|
||||
if !strings.Contains(gotCookies, "fresh=1") {
|
||||
t.Fatalf("重试未读取续期后的 Cookie: %q", gotCookies)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemStockPermissionMissing 库存权限缺失应 403。
|
||||
func TestPublishItemStockPermissionMissing(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import{j as e,r,c as ys,b as qe,d as Ua}from"./react-vendor-C_od1ZSF.js";import{L as Wa,U as ha,M as is,C as os,B as ga,S as ba,Z as cs,a as jt,b as js,G as As,c as _s,d as Ns,e as Ja,f as rt,A as $s,D as Va,g as Ps,P as fa,h as qt,E as ya,T as Qa,i as Ga,j as Pe,X as Me,k as Ka,l as Ha,m as vs,n as ja,o as He,Q as Xt,p as xt,q as Ke,r as yt,s as Tt,t as Rs,R as ze,u as _a,v as Za,w as Qe,K as Ya,x as dt,y as lt,z as et,F as Es,H as Nt,I as _t,J as Dt,N as Na,O as Xa,V as Ds,W as Ts,Y as el,_ as tl,$ as sl,a0 as al,a1 as es,a2 as Bt,a3 as ds,a4 as ll,a5 as rl,a6 as xs,a7 as Ms,a8 as nl,a9 as il,aa as Mt,ab as qs,ac as Gt,ad as va,ae as ol,af as cl,ag as Zt,ah as wa,ai as dl,aj as xl,ak as ml,al as pl,am as ul,an as hl,ao as Fs}from"./icons-vendor-BpMgNNfy.js";import{R as zt,B as gl,X as Bs,Y as zs,T as Ut,a as bl,C as ts,A as fl,b as yl,c as jl,P as Us,d as Ws,L as _l}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const _ of m)if(_.type==="childList")for(const N of _.addedNodes)N.tagName==="LINK"&&N.rel==="modulepreload"&&i(N)}).observe(document,{childList:!0,subtree:!0});function l(m){const _={};return m.integrity&&(_.integrity=m.integrity),m.referrerPolicy&&(_.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?_.credentials="include":m.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function i(m){if(m.ep)return;m.ep=!0;const _=l(m);fetch(m.href,_)}})();const Nl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ms=({sizeClass:t="w-12 h-12",logoClassName:a="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(js,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:n,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Y,children:"取消"}),e.jsxs("button",{onClick:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Y,children:[Y?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),Y?"保存中...":"保存"]})]})})]})}),document.body)]})},ln=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(a=>({order_id:String((a==null?void 0:a.order_id)||"unknown"),success:(a==null?void 0:a.success)===!0,message:String((a==null?void 0:a.message)||"")})):[]}),rn=t=>(t==null?void 0:t.results.filter(a=>!a.success))||[],sa=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${a[t]||a.cancelled}`,children:l[t]||t})},nn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState([]),[m,_]=r.useState([]),[N,I]=r.useState({}),[g,C]=r.useState("all"),[j,F]=r.useState(""),[G,me]=r.useState(""),[oe,v]=r.useState(""),q=r.useRef(0),[ce,Q]=r.useState(1),[ee,B]=r.useState(1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState(!1),[ve,J]=r.useState(!1),[A,E]=r.useState(null),[P,be]=r.useState(null),[Re,ae]=r.useState({}),[T,p]=r.useState(!1),[b,U]=r.useState(""),[M,ne]=r.useState(!1),[he,ye]=r.useState(null),[Ee,ke]=r.useState(null),[x,V]=r.useState(null),[X,c]=r.useState(!1),[d,D]=r.useState(null),[S,Y]=r.useState(null),O=async()=>{const u=++q.current;ue(!0);try{const L=await Xl(j||void 0,g,ce,20,oe);if(u!==q.current)return;a(L.data),B(L.total_pages)}catch(L){console.error("加载订单失败:",L)}finally{u===q.current&&ue(!1)}},de=(u,L,le)=>{if(le&&le.trim())return le;if(N[`${u}:${L}`])return N[`${u}:${L}`];const _e=l.find(Ue=>{if(le&&Ue.item_title){const Fe=le.toLowerCase(),tt=Ue.item_title.toLowerCase();return tt.includes(Fe)||Fe.includes(tt)}return!1});return _e!=null&&_e.item_title?_e.item_title:"未知商品"},Se=u=>{const L={};u.forEach(le=>{le.item_id&&(L[`${le.cookie_id}:${le.item_id}`]=le.item_title||le.item_id)}),I(L)};r.useEffect(()=>{const u=window.setTimeout(()=>{Q(1),v(G.trim())},300);return()=>window.clearTimeout(u)},[G]),r.useEffect(()=>{O()},[j,g,ce,oe]),r.useEffect(()=>{Promise.all([Ft(),vt()]).then(([u,L])=>{_(u),i(L),Se(L)}).catch(u=>{console.error("加载商品列表失败:",u)})},[]);const fe=r.useMemo(()=>new Map(m.map(u=>[u.id,u])),[m]),Oe=u=>{const L=fe.get(u),le=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return le?`${le} · ${u.slice(0,6)}`:`账号 ${u.slice(0,8)}`},re=u=>{const L=fe.get(u);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"},h=async()=>{ue(!0);try{const u=await sr(j||void 0,g);await O(),u!=null&&u.message&&alert(u.message)}catch(u){console.error("同步订单失败:",u),alert((u==null?void 0:u.message)||"同步失败,请重试")}finally{ue(!1)}},f=u=>{U(u),ye(null),p(!0)},R=async u=>{var L;ne(!0),ye(null);try{const le=await lr([b],u),_e=(L=le==null?void 0:le.results)==null?void 0:L[0];_e!=null&&_e.success?(ye({success:!0,message:_e.message}),O()):ye({success:!1,message:(_e==null?void 0:_e.message)||"发货失败"})}catch(le){ye({success:!1,message:(le==null?void 0:le.message)||"请求失败"})}finally{ne(!1)}},z=u=>{E(u),Z(!0)},Ie=u=>{be({...u}),K(!0)},Ae=async()=>{if(!(!P||!P.order_id))try{const u={};P.status!==void 0&&(u.order_status=P.status),P.buyer_id!==void 0&&(u.buyer_id=P.buyer_id),P.amount!==void 0&&(u.amount=P.amount),P.receiver_name!==void 0&&(u.receiver_name=P.receiver_name),P.receiver_phone!==
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(S=>S.map(Y=>`"${String(Y).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),c=new Blob(["\uFEFF"+X],{type:"text/csv;charset=utf-8"}),d=URL.createObjectURL(c),D=document.createElement("a");D.href=d,D.download="卡密组批量导入模板.csv",document.body.appendChild(D),D.click(),D.remove(),URL.revokeObjectURL(d)},ye=async()=>{if(q){ge(!0),ee(null);try{const x=await xr(q);if(ee(x),x.created>0){const V=await Xe();a(V)}}catch(x){ee({error:(x==null?void 0:x.message)||"上传失败"})}finally{ge(!1)}}},Ee=async()=>{if(!(!ue||!Z.trim())){ge(!0),ve(null);try{const x=await mr(ue,Z);ve({added:x.added}),se("");const V=await Xe();a(V)}catch(x){alert("追加失败:"+((x==null?void 0:x.message)||"未知错误"))}finally{ge(!1)}}},ke=()=>{var x;v("create"),ce(null),ee(null),k((x=M[0])!=null&&x.id?String(M[0].id):""),se(""),ve(null),me(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:ke,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Dt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>_(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(et,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(Na,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:J,onChange:x=>A(x.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(Nt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:E,onChange:x=>P(x.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",ne.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:ne.map(x=>{let V="";return x.type==="data"&&x.data_content?V=`库存: ${x.data_content.split(`
|
||||
`).filter(c=>c.trim()).length} 条`:x.type==="text"&&x.text_content?V=x.text_content:x.type==="api"&&x.api_config?V=x.api_config.url:x.type==="image"&&x.image_url&&(V="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(be,{type:x.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:x.name,children:x.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>U(x.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:x.id}),e.jsx(Xa,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${x.type==="text"?"bg-blue-50 text-blue-600":x.type==="data"?"bg-purple-50 text-purple-600":x.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:x.type==="text"?"文本":x.type==="data"?"批量":x.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:V,children:V})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:x.description||"-",children:x.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>b(x),className:`w-12 h-8 rounded-full relative transition-colors ${x.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${x.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>Re(x),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(_t,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>T(x.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Qe,{className:"h-4 w-4"})})]})})]},x.id)})})]})}),ne.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(fa,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&N&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>i(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:g.name||"",onChange:x=>C({...g,name:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:g.type||"text",onChange:x=>C({...g,type:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(N==null?void 0:N.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:g.api_url||"",onChange:x=>C({...g,api_url:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsLine truncated
|
||||
卡号1:密码1
|
||||
卡号2:密码2
|
||||
或者
|
||||
兑换码1
|
||||
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:g.data_content?g.data_content.split(`
|
||||
`).filter(x=>x.trim()).length:0})," 条"]})]})]}),g.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:g.image_url||"",onChange:x=>C({...g,image_url:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),g.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:g.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:x=>{x.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:g.delay_seconds||0,onChange:x=>C({...g,delay_seconds:parseInt(x.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:g.description||"",onChange:x=>C({...g,description:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>C({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${g.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>i(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ae,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),m&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>_(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:j.name,onChange:x=>F({...j,name:x.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>F({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>F({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ds,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>F({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children
Line truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),j.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:j.content.split(`
|
||||
`).filter(x=>x.trim()).length})," 条"]})]}),j.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:j.api_method,onChange:x=>F({...j,api_method:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:j.api_timeout,onChange:x=>F({...j,api_timeout:parseInt(x.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:j.api_headers,onChange:x=>F({...j,api_headers:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:j.api_params,onChange:x=>F({...j,api_params:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:j.description,onChange:x=>F({...j,description:x.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:j.delay_seconds,onChange:x=>F({...j,delay_seconds:parseInt(x.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>_(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:p,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(et,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),G&&qe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>me(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Me,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>v("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(el,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>v("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Dt,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),oe==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:he,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm tran
Line truncated
|
||||
VIP-002
|
||||
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),K&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",K.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>me(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),oe==="create"?e.jsxs("button",{onClick:ye,disabled:!q||B,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(Dt,{className:"w-4 h-4"}),B?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Ee,disabled:!ue||!Z.trim()||B||M.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(et,{className:"w-4 h-4"}),B?"处理中...":"追加卡密"]})]})]})}),document.body)]})},dn=t=>t.find(a=>a.status==="running"||a.status==="canceling"),la="ydisks-amap-js-api",xn="c9b68d4ce9a2a97f22a4a439404488ca";let $t=null;const mn=()=>xn,pn=()=>window.AMap?Promise.resolve(window.AMap):$t||($t=new Promise((t,a)=>{const l=document.getElementById(la),i=l||document.createElement("script"),m=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(N)},_=()=>{window.AMap?(m(),t(window.AMap)):(m(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},N=window.setTimeout(()=>{m(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=_,i.id=la,i.async=!0,i.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(mn())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,i.onerror=()=>{m(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},l||document.head.appendChild(i)}).catch(t=>{throw $t=null,t}),$t),Ht=t=>Number.isFinite(t)&&t!==0,un=t=>{var m,_;const a=Number((m=t.location)==null?void 0:m.lng),l=Number((_=t.location)==null?void 0:_.lat),i={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:a,latitude:l,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!i.division_id||!i.province||!i.city||!i.poi_id||!i.poi_name||!Ht(a)||!Ht(l)||a<-180||a>180||l<-90||l>90?null:i},hn=async(t,a)=>{if(!Ht(t)||!Ht(a)||t<-180||t>180||a<-90||a>90)throw new Error("经纬度无效");const l=await pn();return new Promise((i,m)=>{new l.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,a],1e3,(N,I)=>{var C;if(N!=="complete"){if(N==="no_data"){i([]);return}m(new Error("高德地图附近地址查询失败,请稍后重试"));return}const g=(((C=I==null?void 0:I.poiList)==null?void 0:C.pois)||[]).map(un).filter(j=>j!==null);i(g)})})},gn=t=>{const a=String(t||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},bn=({onConfigureDelivery:t})=>{const[a,l]=r.useState([]),[i,m]=r.useState([]),[_,N]=r.useState([]),[I,g]=r.useState(""),[C,j]=r.useState(""),[F,G]=r.useState(!1),[me,oe]=r.useState(!1),[v,q]=r.useState(!1),[ce,Q]=r.useState(!1),[ee,B]=r.useState(!1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState("upload"),[ve,J]=r.useState(null),[A,E]=r.useState(null),[P,be]=r.useState(""),[Re,ae]=r.useState(!1),[T,p]=r.useState(!1),[b,U]=r.useState([]),[M,ne]=r.useState(null),[he,ye]=r.useState([]),[Ee,ke]=r.useState(null),[x,V]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[X,c]=r.useState(null),[d,D]=r.useState(null),[S,Y]=r.useState(null),O=r.useRef(!1),[de,Se]=r.useState(null),[fe,Oe]=r.useState({}),[re,h]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[f,R]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[z,Ie]=r.useState([]);r.useEffect(()=>{if(!ge||f.images.length===0){Ie([]);return}const n=f.images.map((w,H)=>({key:w.name+H,url:URL.createObjectURL(w)}));return Ie(n),()=>{n.forEach(w=>URL.revokeObjectURL(w.url))}},[ge,f.images]);const Ae=async()=>{const n=await vt();l(n)},we=async()=>{m(await gs())};r.useEffect(()=>{Promise.all([Ft(),vt(),gs(),Hs(20)]).then(([n,w,H,Te])=>{N(n),l(w),m(H);const s=Te.find(o=>["running","canceling"].includes(o.status))||Te.find(o=>o.status!=="preview");Y(s||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!k||!(d!=null&&d.id)||!["running","canceling"].includes(d.status))return;const n=window.setInterval(async()=>{if(!O.current){O.current=!0;try{const w=await bt(d.id);D(w),Y(w),[
Line truncated
|
||||
`),Te=new Blob(["\uFEFF"+H],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(Te),o=document.createElement("a");o.href=s,o.download="批量铺货模板.csv",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(s)},Lt=()=>{h(n=>({...n,cookie_id:I||n.cookie_id})),B(!0)},nt=()=>{R(n=>({...n,cookie_id:I||n.cookie_id})),ue(!0)},it=async n=>{if(!(n?I:f.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");p(!0),navigator.geolocation.getCurrentPosition(async H=>{try{const Te=await hn(H.coords.longitude,H.coords.latitude);if(!Te.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");n?(ye(Te),ke(Te[0])):(U(Te),ne(Te[0]))}catch(Te){alert((Te==null?void 0:Te.message)||"获取发货地失败")}finally{p(!1)}},H=>{p(!1),alert(H.code===H.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Ot=n=>i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id).length>0?i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id):i.filter(w=>w.cookie_id===n.cookie_id&&!w.item_id),pt=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},ut=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},st=r.useMemo(()=>new Map(_.map(n=>[n.id,n])),[_]),ht=r.useMemo(()=>C?a.filter(n=>n.cookie_id===C):a,[C,a]),Ge=n=>{const w=st.get(n),H=(w==null?void 0:w.remark)||(w==null?void 0:w.nickname);return H?`${H} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},ot=n=>{const w=st.get(n);return(w==null?void 0:w.remark)||(w==null?void 0:w.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(al,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:C,onChange:n=>j(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:I,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:De,disabled:F||!I,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(ze,{className:`w-4 h-4 ${F?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Lt,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(et,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:nt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(es,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void _e(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white
Line truncated
|
||||
@@ -0,0 +1,19 @@
|
||||
import{j as e,r,c as ys,b as qe,d as Ja}from"./react-vendor-C_od1ZSF.js";import{L as Va,U as ba,M as is,C as os,B as fa,S as ya,Z as cs,a as jt,b as js,G as As,c as _s,d as Ns,e as Qa,f as rt,A as $s,D as Ga,g as Rs,P as ja,h as qt,E as _a,T as Ka,i as Ha,j as Re,X as Me,k as Za,l as Ya,m as vs,n as Na,o as He,Q as Xt,p as xt,q as Qe,r as yt,s as Tt,t as Ps,R as ze,u as va,v as Xa,w as Ge,K as el,x as dt,y as lt,z as et,F as Es,H as Nt,I as _t,J as Dt,N as wa,O as tl,V as Ds,W as Ts,Y as sl,_ as al,$ as ll,a0 as rl,a1 as es,a2 as Bt,a3 as ds,a4 as nl,a5 as il,a6 as xs,a7 as Ms,a8 as ol,a9 as cl,aa as Mt,ab as qs,ac as Gt,ad as ka,ae as dl,af as xl,ag as Zt,ah as Ca,ai as ml,aj as pl,ak as ul,al as hl,am as gl,an as bl,ao as Fs}from"./icons-vendor-BpMgNNfy.js";import{R as zt,B as fl,X as Bs,Y as zs,T as Ut,a as yl,C as ts,A as jl,b as _l,c as Nl,P as Us,d as Ws,L as vl}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const N of m)if(N.type==="childList")for(const _ of N.addedNodes)_.tagName==="LINK"&&_.rel==="modulepreload"&&i(_)}).observe(document,{childList:!0,subtree:!0});function l(m){const N={};return m.integrity&&(N.integrity=m.integrity),m.referrerPolicy&&(N.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?N.credentials="include":m.crossOrigin==="anonymous"?N.credentials="omit":N.credentials="same-origin",N}function i(m){if(m.ep)return;m.ep=!0;const N=l(m);fetch(m.href,N)}})();const wl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ms=({sizeClass:t="w-12 h-12",logoClassName:a="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(js,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:n,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:X,children:"取消"}),e.jsxs("button",{onClick:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:X,children:[X?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),X?"保存中...":"保存"]})]})})]})}),document.body)]})},nn=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(a=>({order_id:String((a==null?void 0:a.order_id)||"unknown"),success:(a==null?void 0:a.success)===!0,message:String((a==null?void 0:a.message)||"")})):[]}),on=t=>(t==null?void 0:t.results.filter(a=>!a.success))||[],sa=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${a[t]||a.cancelled}`,children:l[t]||t})},cn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState([]),[m,N]=r.useState([]),[_,I]=r.useState({}),[g,C]=r.useState("all"),[j,B]=r.useState(""),[K,me]=r.useState(""),[oe,v]=r.useState(""),F=r.useRef(0),[ce,Q]=r.useState(1),[te,z]=r.useState(1),[ge,he]=r.useState(!1),[k,Y]=r.useState(!1),[se,H]=r.useState(!1),[ve,J]=r.useState(!1),[A,E]=r.useState(null),[P,be]=r.useState(null),[Pe,ae]=r.useState({}),[M,p]=r.useState(!1),[b,U]=r.useState(""),[q,re]=r.useState(!1),[pe,je]=r.useState(null),[Ee,Se]=r.useState(null),[x,V]=r.useState(null),[ee,c]=r.useState(!1),[d,T]=r.useState(null),[S,X]=r.useState(null),O=async()=>{const u=++F.current;he(!0);try{const L=await tr(j||void 0,g,ce,20,oe);if(u!==F.current)return;a(L.data),z(L.total_pages)}catch(L){console.error("加载订单失败:",L)}finally{u===F.current&&he(!1)}},de=(u,L,le)=>{if(le&&le.trim())return le;if(_[`${u}:${L}`])return _[`${u}:${L}`];const _e=l.find(Ue=>{if(le&&Ue.item_title){const Fe=le.toLowerCase(),tt=Ue.item_title.toLowerCase();return tt.includes(Fe)||Fe.includes(tt)}return!1});return _e!=null&&_e.item_title?_e.item_title:"未知商品"},Oe=u=>{const L={};u.forEach(le=>{le.item_id&&(L[`${le.cookie_id}:${le.item_id}`]=le.item_title||le.item_id)}),I(L)};r.useEffect(()=>{const u=window.setTimeout(()=>{Q(1),v(K.trim())},300);return()=>window.clearTimeout(u)},[K]),r.useEffect(()=>{O()},[j,g,ce,oe]),r.useEffect(()=>{Promise.all([Ft(),vt()]).then(([u,L])=>{N(u),i(L),Oe(L)}).catch(u=>{console.error("加载商品列表失败:",u)})},[]);const fe=r.useMemo(()=>new Map(m.map(u=>[u.id,u])),[m]),Ae=u=>{const L=fe.get(u),le=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return le?`${le} · ${u.slice(0,6)}`:`账号 ${u.slice(0,8)}`},ne=u=>{const L=fe.get(u);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"},h=async()=>{he(!0);try{const u=await lr(j||void 0,g);await O(),u!=null&&u.message&&alert(u.message)}catch(u){console.error("同步订单失败:",u),alert((u==null?void 0:u.message)||"同步失败,请重试")}finally{he(!1)}},f=u=>{U(u),je(null),p(!0)},D=async u=>{var L;re(!0),je(null);try{const le=await nr([b],u),_e=(L=le==null?void 0:le.results)==null?void 0:L[0];_e!=null&&_e.success?(je({success:!0,message:_e.message}),O()):je({success:!1,message:(_e==null?void 0:_e.message)||"发货失败"})}catch(le){je({success:!1,message:(le==null?void 0:le.message)||"请求失败"})}finally{re(!1)}},R=u=>{E(u),Y(!0)},we=u=>{be({...u}),H(!0)},Ce=async()=>{if(!(!P||!P.order_id))try{const u={};P.status!==void 0&&(u.order_status=P.status),P.buyer_id!==void 0&&(u.buyer_id=P.buyer_id),P.amount!==void 0&&(u.amount=P.amount),P.receiver_name!==void 0&&(u.receiver_name=P.receiver_name),P.receiver_phone!=
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(S=>S.map(X=>`"${String(X).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),c=new Blob(["\uFEFF"+ee],{type:"text/csv;charset=utf-8"}),d=URL.createObjectURL(c),T=document.createElement("a");T.href=d,T.download="卡密组批量导入模板.csv",document.body.appendChild(T),T.click(),T.remove(),URL.revokeObjectURL(d)},je=async()=>{if(F){ge(!0),te(null);try{const x=await pr(F);if(te(x),x.created>0){const V=await Xe();a(V)}}catch(x){te({error:(x==null?void 0:x.message)||"上传失败"})}finally{ge(!1)}}},Ee=async()=>{if(!(!he||!Y.trim())){ge(!0),ve(null);try{const x=await ur(he,Y);ve({added:x.added}),se("");const V=await Xe();a(V)}catch(x){alert("追加失败:"+((x==null?void 0:x.message)||"未知错误"))}finally{ge(!1)}}},Se=()=>{var x;v("create"),ce(null),te(null),k((x=q[0])!=null&&x.id?String(q[0].id):""),se(""),ve(null),me(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:Se,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Dt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>N(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(et,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(wa,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:J,onChange:x=>A(x.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(Nt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:E,onChange:x=>P(x.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",re.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:re.map(x=>{let V="";return x.type==="data"&&x.data_content?V=`库存: ${x.data_content.split(`
|
||||
`).filter(c=>c.trim()).length} 条`:x.type==="text"&&x.text_content?V=x.text_content:x.type==="api"&&x.api_config?V=x.api_config.url:x.type==="image"&&x.image_url&&(V="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(be,{type:x.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:x.name,children:x.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>U(x.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:x.id}),e.jsx(tl,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${x.type==="text"?"bg-blue-50 text-blue-600":x.type==="data"?"bg-purple-50 text-purple-600":x.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:x.type==="text"?"文本":x.type==="data"?"批量":x.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:V,children:V})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:x.description||"-",children:x.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>b(x),className:`w-12 h-8 rounded-full relative transition-colors ${x.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${x.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>Pe(x),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(_t,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>M(x.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ge,{className:"h-4 w-4"})})]})})]},x.id)})})]})}),re.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ja,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&_&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>i(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:g.name||"",onChange:x=>C({...g,name:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:g.type||"text",onChange:x=>C({...g,type:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(_==null?void 0:_.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:g.api_url||"",onChange:x=>C({...g,api_url:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsLine truncated
|
||||
卡号1:密码1
|
||||
卡号2:密码2
|
||||
或者
|
||||
兑换码1
|
||||
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:g.data_content?g.data_content.split(`
|
||||
`).filter(x=>x.trim()).length:0})," 条"]})]})]}),g.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:g.image_url||"",onChange:x=>C({...g,image_url:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),g.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:g.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:x=>{x.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:g.delay_seconds||0,onChange:x=>C({...g,delay_seconds:parseInt(x.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:g.description||"",onChange:x=>C({...g,description:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>C({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${g.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>i(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ae,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),m&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>N(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:j.name,onChange:x=>B({...j,name:x.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>B({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>B({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ds,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>B({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children
Line truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),j.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:j.content.split(`
|
||||
`).filter(x=>x.trim()).length})," 条"]})]}),j.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:j.api_method,onChange:x=>B({...j,api_method:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:j.api_timeout,onChange:x=>B({...j,api_timeout:parseInt(x.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:j.api_headers,onChange:x=>B({...j,api_headers:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:j.api_params,onChange:x=>B({...j,api_params:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:j.description,onChange:x=>B({...j,description:x.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:j.delay_seconds,onChange:x=>B({...j,delay_seconds:parseInt(x.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>N(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:p,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(et,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),K&&qe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>me(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Me,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>v("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(sl,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>v("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Dt,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),oe==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:pe,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm tran
Line truncated
|
||||
VIP-002
|
||||
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),H&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",H.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>me(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),oe==="create"?e.jsxs("button",{onClick:je,disabled:!F||z,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[z?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(Dt,{className:"w-4 h-4"}),z?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Ee,disabled:!he||!Y.trim()||z||q.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[z?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(et,{className:"w-4 h-4"}),z?"处理中...":"追加卡密"]})]})]})}),document.body)]})},mn=t=>t.find(a=>a.status==="running"||a.status==="canceling"),la="ydisks-amap-js-api",pn="c9b68d4ce9a2a97f22a4a439404488ca";let $t=null;const un=()=>pn,hn=()=>window.AMap?Promise.resolve(window.AMap):$t||($t=new Promise((t,a)=>{const l=document.getElementById(la),i=l||document.createElement("script"),m=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(_)},N=()=>{window.AMap?(m(),t(window.AMap)):(m(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},_=window.setTimeout(()=>{m(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=N,i.id=la,i.async=!0,i.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(un())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,i.onerror=()=>{m(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},l||document.head.appendChild(i)}).catch(t=>{throw $t=null,t}),$t),Ht=t=>Number.isFinite(t)&&t!==0,gn=t=>{var m,N;const a=Number((m=t.location)==null?void 0:m.lng),l=Number((N=t.location)==null?void 0:N.lat),i={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:a,latitude:l,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!i.division_id||!i.province||!i.city||!i.poi_id||!i.poi_name||!Ht(a)||!Ht(l)||a<-180||a>180||l<-90||l>90?null:i},bn=async(t,a)=>{if(!Ht(t)||!Ht(a)||t<-180||t>180||a<-90||a>90)throw new Error("经纬度无效");const l=await hn();return new Promise((i,m)=>{new l.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,a],1e3,(_,I)=>{var C;if(_!=="complete"){if(_==="no_data"){i([]);return}m(new Error("高德地图附近地址查询失败,请稍后重试"));return}const g=(((C=I==null?void 0:I.poiList)==null?void 0:C.pois)||[]).map(gn).filter(j=>j!==null);i(g)})})},fn=t=>{const a=String(t||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},yn=({onConfigureDelivery:t})=>{const[a,l]=r.useState([]),[i,m]=r.useState([]),[N,_]=r.useState([]),[I,g]=r.useState(""),[C,j]=r.useState(""),[B,K]=r.useState(!1),[me,oe]=r.useState(!1),[v,F]=r.useState(!1),[ce,Q]=r.useState(!1),[te,z]=r.useState(!1),[ge,he]=r.useState(!1),[k,Y]=r.useState(!1),[se,H]=r.useState("upload"),[ve,J]=r.useState(null),[A,E]=r.useState(null),[P,be]=r.useState(""),[Pe,ae]=r.useState(!1),[M,p]=r.useState(!1),[b,U]=r.useState([]),[q,re]=r.useState(null),[pe,je]=r.useState([]),[Ee,Se]=r.useState(null),[x,V]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[ee,c]=r.useState(null),[d,T]=r.useState(null),[S,X]=r.useState(null),O=r.useRef(!1),[de,Oe]=r.useState(null),[fe,Ae]=r.useState({}),[ne,h]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[f,D]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[R,we]=r.useState([]);r.useEffect(()=>{if(!ge||f.images.length===0){we([]);return}const n=f.images.map((w,Z)=>({key:w.name+Z,url:URL.createObjectURL(w)}));return we(n),()=>{n.forEach(w=>URL.revokeObjectURL(w.url))}},[ge,f.images]);const Ce=async()=>{const n=await vt();l(n)},ke=async()=>{m(await gs())};r.useEffect(()=>{Promise.all([Ft(),vt(),gs(),Hs(20)]).then(([n,w,Z,Te])=>{_(n),l(w),m(Z);const s=Te.find(o=>["running","canceling"].includes(o.status))||Te.find(o=>o.status!=="preview");X(s||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!k||!(d!=null&&d.id)||!["running","canceling"].includes(d.status))return;const n=window.setInterval(async()=>{if(!O.current){O.current=!0;try{const w=await bt(d.id);T(w),X(w),
Line truncated
|
||||
`),Te=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(Te),o=document.createElement("a");o.href=s,o.download="批量铺货模板.csv",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(s)},Lt=()=>{h(n=>({...n,cookie_id:I||n.cookie_id})),z(!0)},nt=()=>{D(n=>({...n,cookie_id:I||n.cookie_id})),he(!0)},it=async n=>{if(!(n?I:f.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");p(!0),navigator.geolocation.getCurrentPosition(async Z=>{try{const Te=await bn(Z.coords.longitude,Z.coords.latitude);if(!Te.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");n?(je(Te),Se(Te[0])):(U(Te),re(Te[0]))}catch(Te){alert((Te==null?void 0:Te.message)||"获取发货地失败")}finally{p(!1)}},Z=>{p(!1),alert(Z.code===Z.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Ot=n=>i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id).length>0?i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id):i.filter(w=>w.cookie_id===n.cookie_id&&!w.item_id),pt=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},ut=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},st=r.useMemo(()=>new Map(N.map(n=>[n.id,n])),[N]),ht=r.useMemo(()=>C?a.filter(n=>n.cookie_id===C):a,[C,a]),Ke=n=>{const w=st.get(n),Z=(w==null?void 0:w.remark)||(w==null?void 0:w.nickname);return Z?`${Z} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},ot=n=>{const w=st.get(n);return(w==null?void 0:w.remark)||(w==null?void 0:w.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(rl,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:C,onChange:n=>j(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),N.map(n=>e.jsx("option",{value:n.id,children:Ke(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:I,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),N.map(n=>e.jsx("option",{value:n.id,children:Ke(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:De,disabled:B||!I,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(ze,{className:`w-4 h-4 ${B?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Lt,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(et,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:nt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(es,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void _e(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white
Line truncated
|
||||
@@ -6,7 +6,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
|
||||
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
|
||||
<script type="module" crossorigin src="/static/assets/index-CHuZDt8D.js"></script>
|
||||
<script type="module" crossorigin src="/static/assets/index-DxxeH3eR.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-BpMgNNfy.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/vendor-D-Edl3pr.js">
|
||||
|
||||
@@ -766,6 +766,27 @@ func (c *Conn) SendText(ctx context.Context, myID, cid, toID, text string) error
|
||||
return c.sendChatContent(ctx, myID, cid, toID, content)
|
||||
}
|
||||
|
||||
// MarkChatRead notifies the platform that the conversation was opened.
|
||||
func (c *Conn) MarkChatRead(ctx context.Context, cid string, messageIDs []map[string]any) error {
|
||||
ids := make([]string, 0, len(messageIDs))
|
||||
for _, item := range messageIDs {
|
||||
if id := strings.TrimSpace(fmt.Sprint(item["messageId"])); id != "" && id != "<nil>" {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
c.logger.Info("准备上报闲鱼已读", "cid", cid, "message_count", len(ids), "message_ids", ids)
|
||||
// MessageStatusService.read takes one argument: list<string> messageIds.
|
||||
response, err := c.request(ctx, "/r/MessageStatus/read", map[string]any{}, []any{ids}, regResponseTimeout)
|
||||
if err == nil {
|
||||
if code, ok := responseCode(response["code"]); ok && code >= 400 {
|
||||
c.logger.Warn("闲鱼已读上报被拒绝", "cid", cid, "message_count", len(ids), "code", code, "body", response["body"])
|
||||
} else {
|
||||
c.logger.Info("闲鱼已读上报成功", "cid", cid, "message_count", len(ids), "message_ids", ids, "code", response["code"])
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// SendImage 发送一条闲鱼聊天图片消息。imageURL 应为闲鱼可访问的 CDN/公网 URL。
|
||||
func (c *Conn) SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error {
|
||||
if width <= 0 {
|
||||
|
||||
Reference in new issue
Block a user