合并 main:同步聊天、风控诊断与迁移基线
This commit is contained in:
commit
a6c0d36ee9
89 files changed
+2974
-365
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. 备用引擎行为
|
||||
|
||||
@@ -219,6 +230,8 @@ Playwright 主引擎
|
||||
- headless 时使用 `--headless=new`。
|
||||
- 直接 Chromium 必须同时携带与当前 Playwright runtime 匹配的兼容启动参数集合(包括后台网络、扩展、Storage 分区、渲染器后台化、SwiftShader 等参数),否则通过 CDP 访问默认上下文的 Cookie Storage 可能无响应;该集合必须随 Playwright runtime 升级同步核对。
|
||||
- 备用引擎对默认上下文执行 Cookie 清理、注入和读取时,每次操作最多等待 `5s`;超时必须中止当前备用引擎流程并释放浏览器,不得无限阻塞续期协程。
|
||||
- headless 时必须在导航前通过 `--user-agent` 应用同版本、已去除 `HeadlessChrome` 标记的运行时 UA;
|
||||
有头模式不得追加该覆盖。Chromium 原生 Client Hints 必须继续保留,且不得出现 `HeadlessChrome`。
|
||||
- 默认总超时为 `25s`,可由现有环境变量控制;导航超时为 `15s`。
|
||||
|
||||
备用距离规则固定如下:
|
||||
@@ -248,6 +261,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。当前仅把下列注入作为诊断信息记录,不允许它们改变滑块定位、距离或成功判定:
|
||||
@@ -278,6 +293,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 一致。
|
||||
|
||||
不得删除、跳过、弱化或改写断言来让行为变化通过测试。
|
||||
|
||||
@@ -287,6 +305,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. 说明要改变本文哪一条冻结契约及原因。
|
||||
|
||||
@@ -71,11 +71,11 @@ test('chat APIs preserve account and conversation scope', async () => {
|
||||
await getChatSessions('a1');
|
||||
await getChatMessages('a1', 'c1', 9);
|
||||
await sendChatMessage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', text: 'hi' });
|
||||
await markChatRead('a1', 'c1');
|
||||
await markChatRead('a1', 'c1', [{ messageId: 'm1', sessionId: 'c1', cid: 'c1@goofish', conversationType: 1 }]);
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/chat/sessions?account_id=a1');
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/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: [{ messageId: 'm1', sessionId: 'c1', cid: 'c1@goofish', conversationType: 1 }] });
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
test('Chat 会话、消息和发送 API 转发外部取消信号', async () => {
|
||||
@@ -93,7 +93,7 @@ test('Chat 会话、消息和发送 API 转发外部取消信号', async () => {
|
||||
await getChatMessagePage('a1', 'c1', undefined, undefined, { signal: controller.signal });
|
||||
await sendChatMessage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', text: 'hi' }, { signal: controller.signal });
|
||||
await sendChatImage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', image: new File(['image'], 'chat.png', { type: 'image/png' }) }, { signal: controller.signal });
|
||||
await markChatRead('a1', 'c1', { signal: controller.signal });
|
||||
await markChatRead('a1', 'c1', [], { signal: controller.signal });
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/chat/sessions?account_id=a1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/chat/messages?account_id=a1&chat_id=c1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/chat/messages', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
@@ -1369,7 +1369,7 @@ const runVersionedChatTaskAPITest = async () => {
|
||||
await getChatMessages('acc1', 'chat-1', 9);
|
||||
await sendChatMessage({ account_id: 'acc1', chat_id: 'chat-1', buyer_id: 'buyer-1', text: '你好' });
|
||||
await sendChatImage({ account_id: 'acc1', chat_id: 'chat-1', buyer_id: 'buyer-1', image: new File(['image'], 'chat.png', { type: 'image/png' }) });
|
||||
await markChatRead('acc1', 'chat-1');
|
||||
await markChatRead('acc1', 'chat-1', []);
|
||||
await getAccountTaskSettings('acc1');
|
||||
await updateAccountTaskSettings('acc1', { account_id: 'acc1', auto_rate_enabled: true, rate_content: '交易愉快', auto_polish_enabled: false, polish_time: '03:00' });
|
||||
await runAccountTask('acc1', 'auto_rate');
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
import type { ChatReadReceipt } from './types';
|
||||
|
||||
/** 聊天账号选择器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
@@ -68,6 +69,6 @@ export const sendChatImage = async (input: {
|
||||
return postForm('/api/v1/chat/images', form, { timeoutMs: 120_000, ...options });
|
||||
};
|
||||
|
||||
// markChatRead 标记聊天消息已读。
|
||||
export const markChatRead = async (accountId: string, chatId: string, options?: RequestControlOptions): Promise<OperationResponse> =>
|
||||
post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId }, options);
|
||||
/** 向平台确认指定会话中的入站消息已读。 */
|
||||
export const markChatRead = async (accountId: string, chatId: string, messageIDs: ChatReadReceipt[], options?: RequestControlOptions): Promise<OperationResponse> =>
|
||||
post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId, message_ids: messageIDs }, options);
|
||||
@@ -99,7 +99,9 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
expect(hook.result.current.accounts[0]).toMatchObject(accountFixture);
|
||||
expect(hook.result.current.activeChatID).toBe('chat-1');
|
||||
expect(hook.result.current.messages).toEqual([messageFixture]);
|
||||
expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1', [
|
||||
{ messageId: 'message-1', sessionId: 'chat-1', cid: 'chat-1@goofish', conversationType: 1 },
|
||||
], expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(hook.result.current.unreadForAccount('account-1')).toBe(0);
|
||||
await act(
|
||||
// emptySendAction 在没有草稿时阻止文字发送。
|
||||
@@ -191,6 +193,31 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('会话刷新不会让当前打开会话重新显示未读', /* 当前回调验证已读状态与慢刷新响应的竞态边界。 */ async () => {
|
||||
// hook 是当前会话已读后执行刷新的 Hook 渲染结果。
|
||||
const hook = renderHook(
|
||||
// refreshHookFactory 创建会话刷新竞态场景。
|
||||
() => useChat(),
|
||||
);
|
||||
await waitFor(
|
||||
// activeChatAssertion 等待默认会话完成消息读取。
|
||||
() => expect(hook.result.current.activeChatID).toBe('chat-1'),
|
||||
);
|
||||
await waitFor(
|
||||
// readAssertion 等待初始消息读取将本地未读数归零。
|
||||
() => expect(hook.result.current.unreadForAccount('account-1')).toBe(0),
|
||||
);
|
||||
// staleSessionPage 模拟服务端延迟返回的旧未读计数。
|
||||
const staleSessionPage = { ...sessionFixture, unread_count: 4 };
|
||||
getSessionPageMock.mockResolvedValueOnce({ sessions: [staleSessionPage], has_more: false });
|
||||
await act(
|
||||
// refreshAction 执行返回旧未读数据的会话刷新。
|
||||
async () => hook.result.current.reloadSessions('account-1'),
|
||||
);
|
||||
expect(hook.result.current.unreadForAccount('account-1')).toBe(0);
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('WebSocket 连接和消息事件更新聊天状态', /* 当前回调验证实时连接和消息回调边界。 */ async () => {
|
||||
// secondSession 是用于覆盖实时会话排序比较器的第二条会话。
|
||||
const secondSession = { ...sessionFixture, chat_id: 'chat-2', last_message_at: 2, unread_count: 0 };
|
||||
@@ -221,7 +248,9 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
() => latestSocket?.onmessage?.({ data: JSON.stringify({ message: incomingMessage }) }),
|
||||
);
|
||||
expect(hook.result.current.messages).toContainEqual(incomingMessage);
|
||||
expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1');
|
||||
expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1', [
|
||||
{ messageId: 'message-3', sessionId: 'chat-1', cid: 'chat-1@goofish', conversationType: 1 },
|
||||
]);
|
||||
await act(
|
||||
// invalidMessageAction 触发非法消息帧并保持状态稳定。
|
||||
() => latestSocket?.onmessage?.({ data: '{broken' }),
|
||||
|
||||
@@ -3,7 +3,7 @@ import type React from 'react';
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { emojiURL, renderXianyuText, xianyuEmojis } from '../../../chatEmojis';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
|
||||
import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
import type { ChatFeatureState, ChatLiveState, SessionsByAccount } from './types';
|
||||
|
||||
/** Chat Hook 对外暴露的状态、引用和交互动作。 */
|
||||
@@ -156,10 +156,16 @@ export const useChat = (): UseChatResult => {
|
||||
// page 页码。
|
||||
const page = await getChatSessionPage(accountID, undefined, { signal: controller.signal }, true);
|
||||
if (!isCurrentChatRequest(sessionSequence.current, sequence, controller.signal)) return [];
|
||||
setSessionsByAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.sessions }));
|
||||
// sessions 保留当前打开会话的本地已读状态,避免刷新响应迟到后重新展示未读徽标。
|
||||
const sessions = page.sessions.map(/* session 按当前活跃会话覆写已读计数。 */ 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;
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
if (isCurrentChatRequest(sessionSequence.current, sequence, controller.signal) && !isChatAbortError(error)) setError(error instanceof Error ? error.message : '同步会话失败');
|
||||
return [];
|
||||
@@ -271,11 +277,11 @@ export const useChat = (): UseChatResult => {
|
||||
const controller = new AbortController();
|
||||
messageController.current = controller;
|
||||
setMessagesLoading(true);
|
||||
void Promise.all([
|
||||
getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }),
|
||||
markChatRead(activeAccountID, activeChatID, { signal: controller.signal }),
|
||||
]).then(/* 当前回调处理用户交互或异步状态变化。 */ ([page]) => {
|
||||
void getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }).then(/* 当前回调处理用户交互或异步状态变化。 */ page => {
|
||||
if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) return;
|
||||
// readReceipts 只确认可被平台接受的普通入站消息。
|
||||
const readReceipts = collectChatReadReceipts(page.messages, activeChatID);
|
||||
void markChatRead(activeAccountID, activeChatID, readReceipts, { signal: controller.signal });
|
||||
setMessages(page.messages);
|
||||
setHasOlder(page.has_more);
|
||||
setHistoryCursor(page.next_cursor);
|
||||
@@ -394,12 +400,16 @@ export const useChat = (): UseChatResult => {
|
||||
...row,
|
||||
last_message: message.content,
|
||||
last_message_at: message.sent_at,
|
||||
unread_count: message.direction === 'incoming' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) ? row.unread_count + 1 : row.unread_count,
|
||||
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) };
|
||||
});
|
||||
if (activeAccountRef.current === accountID && activeChatRef.current === message.chat_id) {
|
||||
setMessages(/* 当前回调处理用户交互或异步状态变化。 */ current => mergeLiveMessage(current, message));
|
||||
if (message.direction === 'incoming') void markChatRead(accountID, message.chat_id);
|
||||
if (message.direction === 'incoming' && message.message_type !== 'system') {
|
||||
// readReceipts 为当前实时消息生成平台要求的会话读取回执。
|
||||
const readReceipts = collectChatReadReceipts([message], message.chat_id);
|
||||
void markChatRead(accountID, message.chat_id, readReceipts);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略非聊天格式的 WebSocket 帧,后续 REST 查询会恢复权威状态。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
|
||||
// sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。
|
||||
const sessionFixture: ChatSession[] = [
|
||||
@@ -11,6 +11,21 @@ const sessionFixture: ChatSession[] = [
|
||||
// messageFixture 是覆盖消息去重和实时替换的最小消息数据。
|
||||
const messageFixture: ChatMessage = { id: 1, account_id: 'a1', chat_id: 'c1', message_key: 'm1', direction: 'incoming', sender_id: 'b1', sender_name: '张三', message_type: 'text', content: '旧消息', status: 'received', sent_at: 1 };
|
||||
|
||||
test('Chat 已读回执排除系统消息和平台内部消息',
|
||||
// 已读回执测试确保接口仅接收可确认的普通入站消息。
|
||||
() => {
|
||||
// messages 覆盖普通消息、系统通知、内部标记及出站消息。
|
||||
const messages: ChatMessage[] = [
|
||||
messageFixture,
|
||||
{ ...messageFixture, id: 2, message_key: 'in-local', message_type: 'text' },
|
||||
{ ...messageFixture, id: 3, message_key: 'system-1', message_type: 'system' },
|
||||
{ ...messageFixture, id: 4, message_key: 'outgoing-1', direction: 'outgoing' },
|
||||
];
|
||||
expect(collectChatReadReceipts(messages, 'c1')).toEqual([
|
||||
{ messageId: 'm1', sessionId: 'c1', cid: 'c1@goofish', conversationType: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
test('Chat 会话筛选和历史消息合并保持账号内顺序',
|
||||
// 会话状态测试验证搜索、未读筛选和历史消息去重语义。
|
||||
() => {
|
||||
|
||||
@@ -1,4 +1,19 @@
|
||||
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import type { ChatReadReceipt } from './types';
|
||||
|
||||
/** 将可确认的普通入站消息转换为平台已读回执。 */
|
||||
export const collectChatReadReceipts = (messages: ChatMessage[], chatID: string): ChatReadReceipt[] => messages
|
||||
.filter(/* currentMessage 只保留平台可接受的普通入站消息。 */ currentMessage => (
|
||||
currentMessage.direction === 'incoming'
|
||||
&& currentMessage.message_type !== 'system'
|
||||
&& !currentMessage.message_key.startsWith('in-')
|
||||
))
|
||||
.map(/* currentMessage 为每条消息构造其所属会话的已读确认。 */ currentMessage => ({
|
||||
messageId: currentMessage.message_key,
|
||||
sessionId: chatID,
|
||||
cid: `${chatID}@goofish`,
|
||||
conversationType: 1,
|
||||
}));
|
||||
|
||||
/** 按搜索条件筛选会话列表。 */
|
||||
export const filterChatSessions = (sessions: ChatSession[], search: string, unreadOnly: boolean): ChatSession[] => {
|
||||
|
||||
@@ -6,6 +6,18 @@ export type SessionsByAccount = Record<string, ChatSession[]>;
|
||||
/** Chat 实时连接状态。 */
|
||||
export type ChatLiveState = 'connecting' | 'online' | 'offline';
|
||||
|
||||
/** 平台已读接口要求的单条消息回执。 */
|
||||
export interface ChatReadReceipt {
|
||||
/** 平台消息去重键。 */
|
||||
messageId: string;
|
||||
/** 所属平台会话标识。 */
|
||||
sessionId: string;
|
||||
/** 平台会话复合标识。 */
|
||||
cid: string;
|
||||
/** 平台定义的单聊会话类型。 */
|
||||
conversationType: number;
|
||||
}
|
||||
|
||||
/** Chat Hook 的状态与交互能力。 */
|
||||
export type ChatFeatureState = {
|
||||
/** 当前启用账号列表。 */
|
||||
|
||||
@@ -199,6 +199,10 @@ export interface ChatMessage {
|
||||
content: string;
|
||||
/** 消息发送状态。 */
|
||||
status: 'received' | 'sending' | 'sent' | 'failed';
|
||||
/** 平台已读状态;旧消息可能没有该字段。 */
|
||||
read_status?: number;
|
||||
/** 平台确认已读的 Unix 秒时间戳;未确认时省略。 */
|
||||
read_at?: number;
|
||||
/** 消息发送时间的 Unix 秒。 */
|
||||
sent_at: number;
|
||||
}
|
||||
|
||||
+111
-5
@@ -25,6 +25,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"
|
||||
)
|
||||
|
||||
@@ -82,9 +83,20 @@ type Adapter struct {
|
||||
|
||||
orderFetchMu sync.Mutex
|
||||
lastOrderFetch time.Time
|
||||
|
||||
// passwordCoordinator 按账号协调协议凭证恢复,避免重复外部续期并允许不同账号并行执行。
|
||||
passwordCoordinator *accountapp.CredentialRefreshCoordinator
|
||||
// passwordResultMu 仅保护 passwordResults;持锁期间不执行凭证读取或平台 I/O。
|
||||
passwordResultMu sync.Mutex
|
||||
// passwordResults 保存正在执行的协议续期结果,后到调用方可等待同一账号的结果。
|
||||
passwordResults map[string]*passwordRenewalResult
|
||||
}
|
||||
|
||||
// passwordRenewalResult 是同账号并发续期调用共享的完成信号与最终成功状态。
|
||||
type passwordRenewalResult struct {
|
||||
// done 由首次续期调用关闭,所有等待者只接收不关闭。
|
||||
done chan struct{}
|
||||
// renewed 在关闭 done 前写入,关闭 channel 建立等待者读取该字段的 happens-before 关系。
|
||||
renewed bool
|
||||
}
|
||||
|
||||
// notifyNotifier 是 *notify.Notifier 的最小接口,避免 adapter 直接依赖 notify 包
|
||||
@@ -115,6 +127,7 @@ func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter {
|
||||
captchaReq: mtop.NewClient(),
|
||||
orderMTop: mtop.NewClient(),
|
||||
passwordCoordinator: accountapp.NewCredentialRefreshCoordinator(),
|
||||
passwordResults: make(map[string]*passwordRenewalResult),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,14 +188,21 @@ 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") {
|
||||
// selfID 保存当前账号从 Cookie 解析出的平台用户标识,用于过滤同账号 WebSocket 回显。
|
||||
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 保存err,供当前处理流程使用
|
||||
_, _, err := a.chat.RecordIncoming(ctx, chat.Incoming{
|
||||
// stored、inserted、err 保存落库消息、是否首次插入及持久化错误。
|
||||
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
|
||||
}
|
||||
|
||||
@@ -199,6 +219,23 @@ func (a *Adapter) HandleOutgoingChatMessage(ctx context.Context, message engine.
|
||||
return err
|
||||
}
|
||||
|
||||
// HandleMessageRead 接收平台出站消息已读回执,并把非敏感已读状态更新委托给聊天服务。
|
||||
func (a *Adapter) HandleMessageRead(ctx context.Context, event engine.MessageReadEvent) error {
|
||||
if a.chat == nil {
|
||||
return nil
|
||||
}
|
||||
// message、err 保存按平台消息键更新的出站消息及持久化错误,以便缺键时回退会话最近消息。
|
||||
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 失效/自动恢复失败/风控验证等)转发给通知器,
|
||||
// 推送到该账号已绑定的通知渠道。
|
||||
// OnAccountAlert 负责On账号Alert相关处理。
|
||||
@@ -611,6 +648,14 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", reason, fmt.Sprintf("协议续期冷却中,还需等待 %s", remain.Round(time.Second)))
|
||||
return false
|
||||
}
|
||||
// primary 标识当前调用是否负责执行协议续期;后到调用方只等待其结果。
|
||||
if primary := a.beginPasswordRenewalResult(cookieID); !primary {
|
||||
a.logger.Warn("协议续期已在处理中,等待当前结果", "account", cookieID)
|
||||
return a.waitPasswordRenewalResult(ctx, cookieID)
|
||||
}
|
||||
// sharedRenewed 保存首次调用的最终恢复结果,并在所有返回路径唤醒等待者。
|
||||
sharedRenewed := false
|
||||
defer func() { a.finishPasswordRenewalResult(cookieID, sharedRenewed) }()
|
||||
// platformData 保存成功或失败时用于审计的账号平台运行数据;明文凭证只在续期工作闭包内短暂使用。
|
||||
var platformData db.CookiePlatformRuntimeData
|
||||
// lookupFailed 标识是否在调用协议续期前读取账号数据失败,以保持历史审计原因。
|
||||
@@ -626,6 +671,7 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
|
||||
platformData = loaded
|
||||
return a.tryProtocolCredentialRenew(runCtx, &platformData)
|
||||
})
|
||||
sharedRenewed = renewed
|
||||
if !accepted {
|
||||
if errors.Is(renewErr, accountapp.ErrCredentialRefreshInFlight) {
|
||||
a.logger.Warn("协议续期已在处理中", "account", cookieID)
|
||||
@@ -690,6 +736,55 @@ func (a *Adapter) finishPasswordLogin(cookieID string) {
|
||||
}
|
||||
}
|
||||
|
||||
// beginPasswordRenewalResult 为账号首次协议续期创建共享结果状态;返回 false 表示已有调用负责续期。
|
||||
func (a *Adapter) beginPasswordRenewalResult(cookieID string) bool {
|
||||
// passwordResultMu 只保护账号到共享结果状态的映射,绝不跨越慢速外部 I/O。
|
||||
a.passwordResultMu.Lock()
|
||||
defer a.passwordResultMu.Unlock()
|
||||
if a.passwordResults == nil {
|
||||
a.passwordResults = make(map[string]*passwordRenewalResult)
|
||||
}
|
||||
// exists 表示该账号是否已有首个调用负责协议续期,存在时当前调用改为等待共享结果。
|
||||
if _, exists := a.passwordResults[cookieID]; exists {
|
||||
return false
|
||||
}
|
||||
a.passwordResults[cookieID] = &passwordRenewalResult{done: make(chan struct{})}
|
||||
return true
|
||||
}
|
||||
|
||||
// finishPasswordRenewalResult 写入首次协议续期结果并唤醒同账号等待者;重复收尾保持幂等。
|
||||
func (a *Adapter) finishPasswordRenewalResult(cookieID string, renewed bool) {
|
||||
// passwordResultMu 只保护结果写入、映射删除和 channel 关闭的唯一性。
|
||||
a.passwordResultMu.Lock()
|
||||
defer a.passwordResultMu.Unlock()
|
||||
// result 保存当前账号等待者共享的续期结果状态,负责承载最终结果并关闭通知通道。
|
||||
result := a.passwordResults[cookieID]
|
||||
if result == nil {
|
||||
return
|
||||
}
|
||||
result.renewed = renewed
|
||||
delete(a.passwordResults, cookieID)
|
||||
close(result.done)
|
||||
}
|
||||
|
||||
// waitPasswordRenewalResult 等待首次协议续期完成或调用上下文取消,返回其最终恢复结果。
|
||||
func (a *Adapter) waitPasswordRenewalResult(ctx context.Context, cookieID string) bool {
|
||||
// passwordResultMu 只保护共享状态快照读取,等待发生在释放锁之后。
|
||||
a.passwordResultMu.Lock()
|
||||
// result 保存锁内取得的共享续期状态快照;释放锁后只等待其完成信号。
|
||||
result := a.passwordResults[cookieID]
|
||||
a.passwordResultMu.Unlock()
|
||||
if result == nil {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case <-result.done:
|
||||
return result.renewed
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// recordPasswordLogin 负责record密码登录相关处理。
|
||||
func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, userID int64, status, failureReason, message string) {
|
||||
if a.store == nil || a.store.LoginLogs == nil {
|
||||
@@ -827,6 +922,17 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookiePl
|
||||
a.logger.Info("Go 协议续期成功", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
if err == nil {
|
||||
// message 保存平台续期失败原因;空原因使用稳定的非敏感默认提示。
|
||||
message := strings.TrimSpace(res.Message)
|
||||
if message == "" {
|
||||
message = "协议续期未通过"
|
||||
}
|
||||
return false, errors.New(message)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = errors.New("协议续期未返回结果")
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
@@ -605,6 +605,45 @@ func TestOnPasswordLoginRefreshWaitsForPendingFinalResult(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefreshConcurrentCallersShareResult 验证同账号并发续期只执行一次外部请求且共享成功结果。
|
||||
func TestOnPasswordLoginRefreshConcurrentCallersShareResult(t *testing.T) {
|
||||
// store、cleanup 保存测试专用数据库及其资源释放函数,避免并发用例污染其他测试。
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
renewal.GlobalCooldown.Reset("cid")
|
||||
// err 保存写入可续期账号 Cookie 的错误;失败时无法建立本用例的续期前置状态。
|
||||
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; havana_lgc_exp=9999999999999"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// started 用于确认首个调用已进入慢速续期请求,使第二个调用确实与其并发。
|
||||
started := make(chan struct{})
|
||||
// once 保证测试 HTTP 处理器只关闭一次开始信号。
|
||||
var once sync.Once
|
||||
// srv 模拟延迟完成的协议续期端点,暴露并发调用共享结果的时序。
|
||||
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 是注入测试续期服务的适配器,被两个调用方并发复用。
|
||||
a := New(store, nil, nil)
|
||||
a.SetRenewService(xrenew.Service{
|
||||
HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL,
|
||||
RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond,
|
||||
})
|
||||
// first 接收首个续期调用的最终布尔结果,避免 goroutine 泄漏。
|
||||
first := make(chan bool, 1)
|
||||
go func() { first <- a.OnPasswordLoginRefresh(context.Background(), "cid") }()
|
||||
<-started
|
||||
// second 保存第二个并发调用收到的共享续期结果。
|
||||
second := a.OnPasswordLoginRefresh(context.Background(), "cid")
|
||||
// got 保存首个调用的最终结果,应与等待共享状态的第二个调用一致。
|
||||
if got := <-first; !got || !second {
|
||||
t.Fatalf("并发续期调用应共享成功结果: first=%v second=%v", got, second)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure 接口轻量续期也失败后才因浏览器不可用失败。
|
||||
func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
|
||||
@@ -84,6 +84,14 @@ func (r chatRepository) MarkRead(ctx context.Context, userID int64, accountID, c
|
||||
return r.store.Chats.MarkRead(ctx, userID, accountID, chatID)
|
||||
}
|
||||
|
||||
// FindInboundParsedJSONContaining 提供旧版聊天消息标识迁移所需的受限诊断帧查询。
|
||||
func (r chatRepository) FindInboundParsedJSONContaining(ctx context.Context, accountID, fragment string, limit int) ([]string, error) {
|
||||
if r.store == nil || r.store.WSMessages == nil {
|
||||
return nil, errors.New("聊天诊断存储未初始化")
|
||||
}
|
||||
return r.store.WSMessages.FindInboundParsedJSONContaining(ctx, accountID, fragment, limit)
|
||||
}
|
||||
|
||||
// chatIdentityResolver 在适配器内读取 Cookie 并调用平台身份查询接口。
|
||||
type chatIdentityResolver struct {
|
||||
// store 提供账号凭证读取能力,明文只在本次平台调用期间存在。
|
||||
|
||||
@@ -46,6 +46,21 @@ func (subscriptionDomainRepository) UpdateMessageStatus(context.Context, string,
|
||||
return &db.ChatMessage{}, nil
|
||||
}
|
||||
|
||||
// CountUnreadUserMessages 为订阅测试提供没有本地未读消息的稳定结果。
|
||||
func (subscriptionDomainRepository) CountUnreadUserMessages(context.Context, string, string) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// MarkMessageRead 为订阅测试模拟指定出站消息的已读回执写入。
|
||||
func (subscriptionDomainRepository) MarkMessageRead(_ context.Context, _ string, key string, readAt int64) (*db.ChatMessage, error) {
|
||||
return &db.ChatMessage{MessageKey: key, ReadStatus: 2, ReadAt: readAt}, nil
|
||||
}
|
||||
|
||||
// MarkLatestOutgoingRead 为订阅测试模拟缺失消息键时的会话级已读回退。
|
||||
func (subscriptionDomainRepository) MarkLatestOutgoingRead(_ context.Context, _ string, chatID string, readAt int64) (*db.ChatMessage, error) {
|
||||
return &db.ChatMessage{ChatID: chatID, ReadStatus: 2, ReadAt: readAt}, nil
|
||||
}
|
||||
|
||||
// TestChatSubscriptionProviderConvertsAndCleansEvents 验证领域事件转换和订阅取消可重复执行。
|
||||
func TestChatSubscriptionProviderConvertsAndCleansEvents(t *testing.T) {
|
||||
// service 是使用内存仓储构造的领域聊天事件中心。
|
||||
|
||||
@@ -48,7 +48,7 @@ func (d *ItemDependencies) NewItemBatchPublishPort(client func() MTOPClient, log
|
||||
}
|
||||
|
||||
// NewItemPublishPort 创建单商品发布与类目推荐共用的平台端口。
|
||||
func (d *ItemDependencies) NewItemPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error)) *ItemPublishPort {
|
||||
func (d *ItemDependencies) NewItemPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error) bool) *ItemPublishPort {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -24,12 +24,12 @@ type ItemPublishPort struct {
|
||||
logger *slog.Logger
|
||||
// updateRunningCookie 将平台返回的新 Cookie 同步到运行中的账号实例。
|
||||
updateRunningCookie func(context.Context, string, string)
|
||||
// recoverExpiredSession 在平台报告会话过期时触发账号恢复。
|
||||
recoverExpiredSession func(context.Context, string, error)
|
||||
// recoverExpiredSession 在平台报告会话过期时触发账号恢复并返回是否已获得可重试凭证。
|
||||
recoverExpiredSession func(context.Context, string, error) bool
|
||||
}
|
||||
|
||||
// NewItemPublishPort 构造单商品发布基础设施端口。
|
||||
func NewItemPublishPort(store *db.Store, client func() mtop.Client, logger *slog.Logger, updateRunningCookie func(context.Context, string, string), recoverExpiredSession func(context.Context, string, error)) *ItemPublishPort {
|
||||
func NewItemPublishPort(store *db.Store, client func() mtop.Client, logger *slog.Logger, updateRunningCookie func(context.Context, string, string), recoverExpiredSession func(context.Context, string, error) bool) *ItemPublishPort {
|
||||
// resolvedLogger 保存可用于记录发布适配错误的日志器。
|
||||
resolvedLogger := logger
|
||||
if resolvedLogger == nil {
|
||||
@@ -120,6 +120,11 @@ func (p *ItemPublishPort) persistCategorySession(ctx context.Context, userID int
|
||||
|
||||
// Publish 执行单商品平台发布及响应 Cookie 持久化,不向应用层泄露 MTOP 类型。
|
||||
func (p *ItemPublishPort) Publish(ctx context.Context, input itemapp.PublishInput) (itemapp.PublishOutcome, error) {
|
||||
return p.publish(ctx, input, true)
|
||||
}
|
||||
|
||||
// publish 执行一次商品发布;会话恢复成功时最多用新凭证重试一次。
|
||||
func (p *ItemPublishPort) publish(ctx context.Context, input itemapp.PublishInput, allowRetry bool) (itemapp.PublishOutcome, error) {
|
||||
if p == nil || p.store == nil || p.store.Cookies == nil {
|
||||
return itemapp.PublishOutcome{}, errors.New("商品发布存储未初始化")
|
||||
}
|
||||
@@ -173,6 +178,9 @@ func (p *ItemPublishPort) Publish(ctx context.Context, input itemapp.PublishInpu
|
||||
if persistErr != nil {
|
||||
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", persistErr))
|
||||
}
|
||||
if allowRetry && mtop.IsSessionExpiredErr(callErr) && p.recoverExpired(ctx, input.CookieID, callErr) {
|
||||
return p.publish(ctx, input, false)
|
||||
}
|
||||
p.recoverExpired(ctx, input.CookieID, callErr)
|
||||
return itemapp.PublishOutcome{ResponseCookieErr: persistErr}, callErr
|
||||
}
|
||||
@@ -289,10 +297,11 @@ func (p *ItemPublishPort) mtopClient() mtop.Client {
|
||||
}
|
||||
|
||||
// recoverExpired 在平台会话过期时通知账号恢复协调器。
|
||||
func (p *ItemPublishPort) recoverExpired(ctx context.Context, cookieID string, err error) {
|
||||
func (p *ItemPublishPort) recoverExpired(ctx context.Context, cookieID string, err error) bool {
|
||||
if p != nil && p.recoverExpiredSession != nil && err != nil {
|
||||
p.recoverExpiredSession(ctx, cookieID, err)
|
||||
return p.recoverExpiredSession(ctx, cookieID, err)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// 确保发布端口和仓储实现覆盖应用层定义的最小接口。
|
||||
|
||||
@@ -141,6 +141,47 @@ func TestItemPublishPortReleasesCredentialLockDuringRemoteCall(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestItemPublishPortRetriesAfterSessionRecovery 验证续期成功后发布端口使用重新读取的凭证重试一次。
|
||||
func TestItemPublishPortRetriesAfterSessionRecovery(t *testing.T) {
|
||||
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// calls 保存平台发布调用次数,用于确认最多执行一次恢复后的重试。
|
||||
calls := 0
|
||||
// secondCookies 保存第二次发布实际使用的凭证快照。
|
||||
secondCookies := ""
|
||||
// client 是首次返回会话失效、第二次成功的平台客户端替身。
|
||||
client := itemPublishClientStub{publish: func(_ context.Context, cookies string, _ mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return nil, &mtop.SessionExpiredError{API: "publish"}
|
||||
}
|
||||
secondCookies = cookies
|
||||
return &mtop.PublishItemResult{ItemID: "retry-item", Title: "重试商品"}, nil
|
||||
}}
|
||||
// recovered 保存恢复回调是否被调用,确保发布端口不会静默跳过会话恢复。
|
||||
recovered := false
|
||||
// recovery 保存测试用会话恢复回调,并模拟恢复逻辑写入的新凭证。
|
||||
recovery := func(ctx context.Context, cookieID string, recoveryErr error) bool {
|
||||
recovered = recoveryErr != nil
|
||||
// updateErr 保存模拟续期凭证写入的持久化错误。
|
||||
if updateErr := store.Cookies.UpdateValueExisting(ctx, cookieID, "unb=1; fresh=1"); updateErr != nil {
|
||||
t.Fatalf("写入续期凭证失败: %v", updateErr)
|
||||
}
|
||||
return true
|
||||
}
|
||||
// port 是注入恢复回调后的发布适配器。
|
||||
port := NewItemPublishPort(store, func() mtop.Client { return client }, nil, nil, recovery)
|
||||
// outcome、publishErr 保存恢复重试后的发布结果及错误。
|
||||
outcome, publishErr := port.Publish(context.Background(), itemapp.PublishInput{UserID: 1, CookieID: "cid", Title: "重试商品", PriceCents: 100, Quantity: 1})
|
||||
if publishErr != nil || outcome.Result == nil || outcome.Result.ItemID != "retry-item" {
|
||||
t.Fatalf("恢复后发布结果异常: outcome=%+v err=%v", outcome, publishErr)
|
||||
}
|
||||
if !recovered || calls != 2 || secondCookies != "unb=1; fresh=1" {
|
||||
t.Fatalf("续期重试未使用新凭证: recovered=%v calls=%d cookies=%q", recovered, calls, secondCookies)
|
||||
}
|
||||
}
|
||||
|
||||
// TestItemPublishRepositoryUpsertMapsApplicationRecord 验证商品仓储适配器正确转换应用记录。
|
||||
func TestItemPublishRepositoryUpsertMapsApplicationRecord(t *testing.T) {
|
||||
// store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。
|
||||
|
||||
@@ -3,7 +3,9 @@ package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -166,6 +168,12 @@ type SessionRepository interface {
|
||||
MarkRead(ctx context.Context, userID int64, accountID, chatID string) error
|
||||
}
|
||||
|
||||
// ReadMessageIDResolver 定义旧版聊天关联标识解析需要的最小诊断查询能力。
|
||||
type ReadMessageIDResolver interface {
|
||||
// FindInboundParsedJSONContaining 返回可能包含旧关联标识的有限已解密入站诊断帧。
|
||||
FindInboundParsedJSONContaining(ctx context.Context, accountID, fragment string, limit int) ([]string, error)
|
||||
}
|
||||
|
||||
// Service 编排聊天历史查询,不持有 HTTP 请求或数据库连接。
|
||||
type Service struct {
|
||||
// repository 保存由调用方注入的最小持久化端口。
|
||||
@@ -260,6 +268,116 @@ func (s *Service) FindSession(ctx context.Context, userID int64, accountID, chat
|
||||
return session, nil
|
||||
}
|
||||
|
||||
// ResolveReadMessageID 将旧版实时消息关联标识转换为闲鱼已读接口要求的 PNM 标识。
|
||||
func (s *Service) ResolveReadMessageID(ctx context.Context, accountID, chatID, messageID string) string {
|
||||
// legacyID 保存去除空白后的待迁移消息关联标识。
|
||||
legacyID := strings.TrimSpace(messageID)
|
||||
if legacyID == "" || strings.HasSuffix(legacyID, ".PNM") || s == nil || s.repository == nil {
|
||||
return legacyID
|
||||
}
|
||||
// resolver 保存仓储实现的可选诊断帧查询能力。
|
||||
resolver, ok := s.repository.(ReadMessageIDResolver)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
// values、err 保存可能匹配旧标识的诊断 JSON 及读取错误。
|
||||
values, err := resolver.FindInboundParsedJSONContaining(ctx, accountID, legacyID, 20)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
// value 保存当前待解析的诊断 JSON。
|
||||
for _, value := range values {
|
||||
// decoded 保存当前诊断帧反序列化后的动态结构。
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(value), &decoded) != nil {
|
||||
continue
|
||||
}
|
||||
// platformID 保存当前诊断帧中解析出的平台 PNM 标识。
|
||||
if platformID := FindPlatformMessageID(decoded, chatID, legacyID); platformID != "" {
|
||||
return platformID
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// FindPlatformMessageID 在已解密的实时消息结构中定位与旧关联标识对应的 PNM 标识。
|
||||
func FindPlatformMessageID(value any, chatID, legacyID string) string {
|
||||
// walk 递归检查嵌套 map、数组和嵌入 JSON 文本。
|
||||
var walk func(any) string
|
||||
walk = func(current any) string {
|
||||
// typed 保存当前动态节点按容器类别断言后的值。
|
||||
switch typed := current.(type) {
|
||||
case map[string]any:
|
||||
// payload、ok 保存协议第 10 段及其存在标识。
|
||||
if payload, ok := typed["10"]; ok && readValueContainsID(payload, legacyID) {
|
||||
// candidate 保存当前协议节点提供的平台消息标识。
|
||||
candidate := strings.TrimSpace(fmt.Sprint(typed["3"]))
|
||||
if strings.HasSuffix(candidate, ".PNM") {
|
||||
// currentChatID 保存协议节点所属的聊天会话标识。
|
||||
currentChatID := strings.TrimSuffix(strings.TrimSpace(fmt.Sprint(typed["2"])), "@goofish")
|
||||
if currentChatID == "" || currentChatID == chatID {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
}
|
||||
// child 保存当前 map 的嵌套协议节点。
|
||||
for _, child := range typed {
|
||||
// candidate 保存递归解析得到的候选 PNM 标识。
|
||||
if candidate := walk(child); candidate != "" {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
// child 保存当前数组中的嵌套协议节点。
|
||||
for _, child := range typed {
|
||||
// candidate 保存递归解析得到的候选 PNM 标识。
|
||||
if candidate := walk(child); candidate != "" {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
case string:
|
||||
// nested 保存嵌入 JSON 文本反序列化后的结构。
|
||||
var nested any
|
||||
if json.Unmarshal([]byte(typed), &nested) == nil {
|
||||
return walk(nested)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return walk(value)
|
||||
}
|
||||
|
||||
// readValueContainsID 判断嵌套诊断字段是否保存了指定旧关联标识。
|
||||
func readValueContainsID(value any, legacyID string) bool {
|
||||
// typed 保存当前动态节点按容器类别断言后的值。
|
||||
switch typed := value.(type) {
|
||||
case map[string]any:
|
||||
// key、child 保存当前字段名及其嵌套值。
|
||||
for key, child := range typed {
|
||||
if (strings.EqualFold(key, "messageId") || strings.EqualFold(key, "message_id")) && strings.TrimSpace(fmt.Sprint(child)) == legacyID {
|
||||
return true
|
||||
}
|
||||
if readValueContainsID(child, legacyID) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
// child 保存当前数组中的嵌套值。
|
||||
for _, child := range typed {
|
||||
if readValueContainsID(child, legacyID) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case string:
|
||||
// nested 保存嵌入 JSON 文本反序列化后的结构。
|
||||
var nested any
|
||||
if json.Unmarshal([]byte(typed), &nested) == nil {
|
||||
return readValueContainsID(nested, legacyID)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// CleanupEmptySessions 清理平台分页产生的无效空会话壳。
|
||||
func (s *Service) CleanupEmptySessions(ctx context.Context, accountID string) error {
|
||||
accountID = strings.TrimSpace(accountID)
|
||||
|
||||
@@ -90,9 +90,9 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us
|
||||
var bctx playwright.BrowserContext
|
||||
// lastErr 保存lastErr,供当前处理流程使用
|
||||
var lastErr error
|
||||
for // attempt 保存尝试次数,供当前处理流程使用
|
||||
attempt := 1; attempt <= 2; attempt++ {
|
||||
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, passwordPersistentContextOptions(headless))
|
||||
// attempt 表示当前持久化 Chromium 的重试序号;启动失败时会先清理 profile 锁文件再重试一次。
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, passwordPersistentContextOptions(headless, m.headlessUserAgent()))
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
@@ -116,9 +116,10 @@ func (m *Manager) newPersistentPasswordContext(ctx context.Context, cookieID, us
|
||||
return bctx, release, nil
|
||||
}
|
||||
|
||||
// passwordPersistentContextOptions 负责密码Persistent上下文Options相关处理。
|
||||
func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunchPersistentContextOptions {
|
||||
return playwright.BrowserTypeLaunchPersistentContextOptions{
|
||||
// passwordPersistentContextOptions 为密码登录构造持久化上下文;无头模式仅使用实测运行时并去除 HeadlessChrome 标记的 UA。
|
||||
func passwordPersistentContextOptions(headless bool, headlessUserAgent ...*string) playwright.BrowserTypeLaunchPersistentContextOptions {
|
||||
// options 是密码登录持久化 context 的完整启动配置,避免把 UA 覆盖泄漏到有头会话。
|
||||
options := playwright.BrowserTypeLaunchPersistentContextOptions{
|
||||
Headless: playwright.Bool(headless),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
@@ -132,6 +133,10 @@ func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunc
|
||||
},
|
||||
Timeout: playwright.Float(quickRenewTimeoutMS),
|
||||
}
|
||||
if headless && len(headlessUserAgent) > 0 {
|
||||
options.UserAgent = headlessUserAgent[0]
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
// BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。
|
||||
@@ -154,15 +159,17 @@ func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cooki
|
||||
// effectiveSnapshot 保存effectiveSnapshot,供当前处理流程使用
|
||||
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
|
||||
|
||||
// bctx、release、err 保存bctx、release、err,供当前处理流程使用
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, quickRenewHeadless(headless))
|
||||
// headless 是经环境覆盖后的本次续期浏览器可见性,并决定是否必须应用运行时指纹。
|
||||
headless = quickRenewHeadless(headless)
|
||||
// bctx 是持久化续期上下文;release 释放 profile 锁和并发槽位;err 仅表示上下文创建失败。
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, headless)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer release()
|
||||
|
||||
// page、err 保存page、err,供当前处理流程使用
|
||||
page, err := bctx.NewPage()
|
||||
// page 是已在导航前附加无头 UA 和 Client Hints 覆盖的续期页面。
|
||||
page, err := m.newBrowserPage(bctx, headless)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
@@ -222,15 +229,17 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt
|
||||
}
|
||||
// effectiveSnapshot 保存effectiveSnapshot,供当前处理流程使用
|
||||
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
|
||||
// bctx、release、err 保存bctx、release、err,供当前处理流程使用
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, cookiesRefreshHeadless(headless))
|
||||
// headless 是经环境覆盖后的定时续期浏览器可见性,并决定页面级指纹覆盖。
|
||||
headless = cookiesRefreshHeadless(headless)
|
||||
// bctx 是定时续期使用的持久化上下文;release 归还 profile 资源;err 表示启动或注入 Cookie 失败。
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, headless)
|
||||
if err != nil {
|
||||
return "", nil, false, err
|
||||
}
|
||||
defer release()
|
||||
|
||||
// page、err 保存page、err,供当前处理流程使用
|
||||
page, err := bctx.NewPage()
|
||||
// page 是已在导航前附加无头 UA 和 Client Hints 覆盖的官方续期页。
|
||||
page, err := m.newBrowserPage(bctx, headless)
|
||||
if err != nil {
|
||||
return "", nil, false, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
@@ -588,9 +597,10 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
|
||||
var bctx playwright.BrowserContext
|
||||
// lastErr 保存lastErr,供当前处理流程使用
|
||||
var lastErr error
|
||||
for // attempt 保存尝试次数,供当前处理流程使用
|
||||
attempt := 1; attempt <= 2; attempt++ {
|
||||
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, playwright.BrowserTypeLaunchPersistentContextOptions{
|
||||
// attempt 表示当前持久化 profile 的启动序号;失败后只进行一次清理后的重试。
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
// options 保存本次启动的独立配置,避免重试时复用可能被 Playwright 修改的对象。
|
||||
options := playwright.BrowserTypeLaunchPersistentContextOptions{
|
||||
Headless: playwright.Bool(headless),
|
||||
Args: chromiumLaunchArgs(),
|
||||
ExecutablePath: chromiumExecutablePath(),
|
||||
@@ -598,7 +608,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,177 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
// TestHeadlessFingerprintBrowserIntegration 在真实 Chromium 中验证 Playwright 与直连 CDP 的请求和页面指纹均不暴露无头标记;仅在显式开启浏览器集成测试时运行。
|
||||
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 接收两个浏览器路径访问本地探针时的请求头,由测试 goroutine 创建且不关闭。
|
||||
requests := make(chan http.Header, 2)
|
||||
// server 是本地指纹探针,只记录目标路径请求而不涉及真实平台或凭证。
|
||||
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 管理本次测试创建的 Playwright runtime,defer Close 负责同步回收其浏览器资源。
|
||||
m := NewManager(nil)
|
||||
defer m.Close()
|
||||
// err 表示 runtime 初始化或实测 Chromium 指纹读取失败。
|
||||
if err := m.init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// userAgent 是从当前打包 Chromium 实测并移除 HeadlessChrome 标记后的 UA。
|
||||
userAgent := m.headlessUserAgent()
|
||||
if userAgent == nil {
|
||||
t.Fatal("初始化后无头 UA 为空")
|
||||
}
|
||||
|
||||
t.Run("playwright-context", func(t *testing.T) {
|
||||
// browser 是 Playwright 独立启动的无头 Chromium,子测试结束时关闭。
|
||||
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 是 browser 的隔离上下文,使用实测 UA 并在子测试结束时释放。
|
||||
bctx, err := browser.NewContext(playwright.BrowserNewContextOptions{UserAgent: userAgent})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = bctx.Close() }()
|
||||
// page 是导航前已应用 Client Hints 覆盖的探针页面;err 表示页面或覆盖创建失败。
|
||||
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 是直连 CDP Chromium 的临时用户目录,测试结束后由 testing 清理。
|
||||
profileDir := t.TempDir()
|
||||
// executable 默认使用 Playwright 管理的 Chromium,环境配置可指定同一兼容运行时。
|
||||
executable := m.pw.Chromium.ExecutablePath()
|
||||
// configured 是可选的环境指定可执行路径,存在时覆盖默认 runtime 路径。
|
||||
if configured := chromiumExecutablePath(); configured != nil {
|
||||
executable = *configured
|
||||
}
|
||||
// cmd 是直连 CDP 的 Chromium 进程,defer 中终止并等待其退出。
|
||||
cmd := exec.Command(executable, fallbackChromiumArgs(profileDir, true, userAgent)...)
|
||||
cmd.Stdout = io.Discard
|
||||
cmd.Stderr = io.Discard
|
||||
// err 表示 Chromium 子进程未能启动。
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// processDone 由等待 goroutine 发送一次子进程退出结果,defer 接收以避免遗留 goroutine。
|
||||
processDone := make(chan error, 1)
|
||||
// 等待 goroutine 只负责把 cmd.Wait 的结果转交给测试清理逻辑。
|
||||
go func() { processDone <- cmd.Wait() }()
|
||||
defer func() {
|
||||
if cmd.Process != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
}
|
||||
select {
|
||||
case <-processDone:
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
}()
|
||||
|
||||
// ctx 限制 DevTools 发现总时长;cancel 在子测试退出时释放 timer 资源。
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
// endpoint 是发现到的本地 DevTools 地址;err 表示进程提前退出或在限定时间内未就绪。
|
||||
endpoint, err := waitForDevToolsEndpoint(ctx, profileDir, processDone, 10*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// browser 是附着到外部 Chromium 的 CDP 句柄;关闭仅断开客户端连接。
|
||||
browser, err := m.pw.Chromium.ConnectOverCDP(endpoint)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = browser.Close() }()
|
||||
// contexts 是外部 Chromium 已创建的 context 列表,直连模式应至少提供默认 context。
|
||||
contexts := browser.Contexts()
|
||||
if len(contexts) == 0 {
|
||||
t.Fatal("直接 CDP 浏览器无默认 context")
|
||||
}
|
||||
// page 是默认 context 中附加 CDP 指纹覆盖的验证页;err 表示覆盖建立失败。
|
||||
page, err := m.newBrowserPage(contexts[0], true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
verifyEffectiveHeadlessFingerprint(t, page, server.URL+"/fingerprint", requests, *userAgent)
|
||||
})
|
||||
}
|
||||
|
||||
// verifyEffectiveHeadlessFingerprint 导航 page 到本地 target,读取 requests 中的 HTTP 指纹并与 expectedUserAgent 对比;失败即终止所属测试。
|
||||
func verifyEffectiveHeadlessFingerprint(t *testing.T, page playwright.Page, target string, requests <-chan http.Header, expectedUserAgent string) {
|
||||
t.Helper()
|
||||
// err 表示探针页面导航失败,页面未完成 DOM 加载时不能继续断言。
|
||||
if _, err := page.Goto(target, playwright.PageGotoOptions{WaitUntil: playwright.WaitUntilStateDomcontentloaded}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// headers 保存本次导航由本地探针捕获的 HTTP 请求头。
|
||||
var headers http.Header
|
||||
select {
|
||||
case headers = <-requests:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("等待浏览器指纹请求超时")
|
||||
}
|
||||
// pageIdentity 是页面内 navigator 暴露的 UA 与 Client Hints;err 表示脚本执行失败。
|
||||
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)
|
||||
// source 标识待检查的 HTTP 或页面指纹来源;value 是该来源暴露给目标站点的文本。
|
||||
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 证明 Playwright 未改变预期的对象编码。
|
||||
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"
|
||||
@@ -36,13 +37,30 @@ const (
|
||||
|
||||
// chromiumLaunchArgs 统一 Chromium 启动参数。
|
||||
func chromiumLaunchArgs() []string {
|
||||
return []string{
|
||||
// args 是所有 Chromium 启动路径共享的参数;证书绕过仅在环境明确授权时追加。
|
||||
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 仅为 TLS 检查代理替换平台证书链的受控环境提供浏览器证书校验绕过;默认关闭,且不会影响 HTTP 客户端或已保存凭证的校验。
|
||||
func captchaIgnoreCertificateErrors() bool {
|
||||
// value 是环境变量的去空白值,空值按安全默认值禁用证书绕过。
|
||||
value := strings.TrimSpace(os.Getenv("CAPTCHA_IGNORE_CERT_ERRORS"))
|
||||
if value == "" {
|
||||
return false
|
||||
}
|
||||
// parsed 是环境开关的布尔解释;err 表示值不属于 Go 支持的布尔文本。
|
||||
parsed, err := strconv.ParseBool(value)
|
||||
return err == nil && parsed
|
||||
}
|
||||
|
||||
// chromiumExecutablePath 负责chromiumExecutable路径相关处理。
|
||||
@@ -139,6 +157,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
|
||||
@@ -363,13 +388,219 @@ func (m *Manager) detectBrowserFingerprint() error {
|
||||
if strings.TrimSpace(headers.Get("User-Agent")) == "" {
|
||||
return fmt.Errorf("Chromium 返回空 userAgent")
|
||||
}
|
||||
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{
|
||||
// metadata 是本次实测 Chromium 的高熵 Client Hints;err 表示页面未暴露或无法读取该浏览器信息。
|
||||
metadata, err := readUserAgentMetadata(page)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取 Chromium User-Agent Client Hints 失败: %w", err)
|
||||
}
|
||||
// fingerprint 是去除无头产品标记后的运行时身份,供后续无头页面和协议请求一致使用。
|
||||
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 移除 Chromium 无头模式附加的产品标记,同时保留同一运行时实测的版本和 Client Hints。
|
||||
func normalizeBrowserFingerprint(fingerprint xianyu.BrowserFingerprint) xianyu.BrowserFingerprint {
|
||||
fingerprint.UserAgent = normalizeHeadlessUserAgent(fingerprint.UserAgent)
|
||||
fingerprint.SecChUA = normalizeSecChUA(fingerprint.SecChUA)
|
||||
return fingerprint
|
||||
}
|
||||
|
||||
// normalizeHeadlessUserAgent 只替换 UA 中的 HeadlessChrome 产品名,避免伪造浏览器版本、平台或其他身份字段。
|
||||
func normalizeHeadlessUserAgent(userAgent string) string {
|
||||
return strings.ReplaceAll(strings.TrimSpace(userAgent), "HeadlessChrome/", "Chrome/")
|
||||
}
|
||||
|
||||
// normalizeSecChUA 规范化 Sec-CH-UA 品牌并按品牌去重,保证无头标记不会通过 Client Hints 泄露。
|
||||
func normalizeSecChUA(value string) string {
|
||||
// parts 是按逗号拆分的原始品牌条目,保留同一 Chromium 实测版本字段。
|
||||
parts := strings.Split(value, ",")
|
||||
// result 以原始顺序收集保留后的品牌条目;seen 防止替换 HeadlessChrome 后的重复品牌。
|
||||
result := make([]string, 0, len(parts))
|
||||
// seen 按规范化品牌名去重,避免同一产品经替换后重复出现在请求头。
|
||||
seen := make(map[string]struct{}, len(parts))
|
||||
// part 是当前待规范化的 Sec-CH-UA 品牌条目。
|
||||
for _, part := range parts {
|
||||
part = strings.TrimSpace(strings.ReplaceAll(part, "HeadlessChrome", "Chromium"))
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
// brand 是用于去重的品牌名,不含版本参数。
|
||||
brand := part
|
||||
// index 是品牌名与版本参数分隔分号的位置,负值表示条目没有参数。
|
||||
if index := strings.IndexByte(brand, ';'); index >= 0 {
|
||||
brand = strings.TrimSpace(brand[:index])
|
||||
}
|
||||
// exists 表示同名品牌已被保留,避免 HeadlessChrome 归一化后出现重复条目。
|
||||
if _, exists := seen[brand]; exists {
|
||||
continue
|
||||
}
|
||||
seen[brand] = struct{}{}
|
||||
result = append(result, part)
|
||||
}
|
||||
return strings.Join(result, ", ")
|
||||
}
|
||||
|
||||
// readUserAgentMetadata 从页面读取 Chromium 公开的低、高熵 Client Hints,返回可传给 CDP 的对象或读取失败原因。
|
||||
func readUserAgentMetadata(page playwright.Page) (map[string]any, error) {
|
||||
// value 是页面脚本返回的任意值;err 表示浏览器脚本执行或高熵字段读取失败。
|
||||
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 是可作为 CDP userAgentMetadata 使用的对象;ok 证明脚本结果的结构正确。
|
||||
metadata, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("navigator.userAgentData 类型异常: %T", value)
|
||||
}
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
// normalizeUserAgentMetadata 复制 Client Hints 并仅规范化品牌列表,避免修改 Manager 持有的实测元数据。
|
||||
func normalizeUserAgentMetadata(metadata map[string]any) map[string]any {
|
||||
if len(metadata) == 0 {
|
||||
return nil
|
||||
}
|
||||
// result 是供当前页面 CDP 覆盖使用的独立元数据副本。
|
||||
result := make(map[string]any, len(metadata))
|
||||
// key 是当前 Client Hints 字段名;value 是其待复制或规范化的值。
|
||||
for key, value := range metadata {
|
||||
switch key {
|
||||
case "brands", "fullVersionList":
|
||||
result[key] = normalizeUserAgentBrands(value)
|
||||
default:
|
||||
result[key] = value
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// normalizeUserAgentBrands 将品牌列表中的无头标记替换为 Chromium,并按品牌保留首个实测版本条目。
|
||||
func normalizeUserAgentBrands(value any) []any {
|
||||
// brands 是页面返回的品牌数组;ok 表示该字段可以安全按数组处理。
|
||||
brands, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
// result 收集归一化后的品牌对象;seen 防止别名替换后的品牌重复。
|
||||
result := make([]any, 0, len(brands))
|
||||
// seen 记录已经保留的规范化品牌名,保证 CDP metadata 与 Sec-CH-UA 一致。
|
||||
seen := make(map[string]struct{}, len(brands))
|
||||
// item 是当前页面返回的候选品牌对象。
|
||||
for _, item := range brands {
|
||||
// brandEntry 是转换后的品牌对象;ok 表示候选条目有可读取字段。
|
||||
brandEntry, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// brand 是去重和覆盖写回使用的产品名,非字符串字段按空值丢弃。
|
||||
brand, _ := brandEntry["brand"].(string)
|
||||
brand = strings.ReplaceAll(brand, "HeadlessChrome", "Chromium")
|
||||
if brand == "" {
|
||||
continue
|
||||
}
|
||||
// exists 表示相同规范化品牌已经收录。
|
||||
if _, exists := seen[brand]; exists {
|
||||
continue
|
||||
}
|
||||
seen[brand] = struct{}{}
|
||||
// entry 是独立拷贝,防止更改本次页面覆盖时改写原始实测对象。
|
||||
entry := make(map[string]any, len(brandEntry))
|
||||
// key 是当前品牌字段名;itemValue 是需原样保留的版本等字段。
|
||||
for key, itemValue := range brandEntry {
|
||||
entry[key] = itemValue
|
||||
}
|
||||
entry["brand"] = brand
|
||||
result = append(result, entry)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// headlessUserAgent 返回当前实测 Chromium 的规范化无头 UA;未完成指纹探测时回退全局实测值,仍不可用则返回 nil。
|
||||
func (m *Manager) headlessUserAgent() *string {
|
||||
// userAgent 是移除 HeadlessChrome 标记后的 runtime UA,保持版本与协议侧指纹一致。
|
||||
userAgent := normalizeHeadlessUserAgent(m.browserFingerprint.UserAgent)
|
||||
if userAgent == "" {
|
||||
userAgent = normalizeHeadlessUserAgent(xianyu.CurrentBrowserFingerprint().UserAgent)
|
||||
}
|
||||
if userAgent == "" {
|
||||
return nil
|
||||
}
|
||||
return playwright.String(userAgent)
|
||||
}
|
||||
|
||||
// newBrowserPage 从 bctx 创建页面;无头模式会在首次导航前应用 UA/Client Hints 覆盖,失败时关闭半成品页面并返回错误。
|
||||
func (m *Manager) newBrowserPage(bctx playwright.BrowserContext, headless bool) (playwright.Page, error) {
|
||||
// page 是新建的浏览器页面;err 表示 context 不可用或页面创建失败。
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !headless {
|
||||
return page, nil
|
||||
}
|
||||
// err 表示页面级 CDP 指纹覆盖失败,不能继续导航以免暴露无头身份。
|
||||
if err := m.applyHeadlessFingerprint(page); err != nil {
|
||||
_ = page.Close()
|
||||
return nil, err
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// applyHeadlessFingerprint 通过页面级 CDP 在首次导航前覆盖 UA 与 Client Hints;成功后故意保持会话附着以维持页面身份。
|
||||
func (m *Manager) applyHeadlessFingerprint(page playwright.Page) error {
|
||||
// userAgent 是当前运行时的规范化 UA,nil 表示未完成必须的初始化探测。
|
||||
userAgent := m.headlessUserAgent()
|
||||
if userAgent == nil {
|
||||
return fmt.Errorf("无头 Chromium User-Agent 未初始化")
|
||||
}
|
||||
// metadata 是可安全传给当前页面的 Client Hints 拷贝,不能含 HeadlessChrome 品牌。
|
||||
metadata := normalizeUserAgentMetadata(m.userAgentMetadata)
|
||||
if len(metadata) == 0 {
|
||||
return fmt.Errorf("无头 Chromium User-Agent Client Hints 未初始化")
|
||||
}
|
||||
// session 是页面生命周期内保持附着的 CDP 会话;err 表示 Chromium 拒绝创建目标会话。
|
||||
session, err := page.Context().NewCDPSession(page)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建 Chromium 指纹 CDP 会话: %w", err)
|
||||
}
|
||||
// err 表示 Chromium 未接受身份覆盖;此时立即分离 session 防止资源泄漏。
|
||||
if _, err := session.Send("Emulation.setUserAgentOverride", map[string]any{
|
||||
"userAgent": *userAgent,
|
||||
"userAgentMetadata": metadata,
|
||||
}); err != nil {
|
||||
_ = session.Detach()
|
||||
return fmt.Errorf("应用 Chromium 无头指纹: %w", err)
|
||||
}
|
||||
// session 在 page 生命周期内必须保持附着;目标级仿真会话分离后 Chromium 会还原 navigator.userAgentData。
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -471,8 +702,8 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
|
||||
finishOperation()
|
||||
return nil, nil, err
|
||||
}
|
||||
// page、err 保存page、err,供当前处理流程使用
|
||||
page, err := entry.context.NewPage()
|
||||
// page 在无头模式下会在首次导航前收到运行时 UA 与 Client Hints 覆盖。
|
||||
page, err := m.newBrowserPage(entry.context, headless)
|
||||
if err != nil {
|
||||
// context 损坏,丢弃重建一次。
|
||||
m.releaseEntry(cookieID, entry)
|
||||
@@ -482,7 +713,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
|
||||
finishOperation()
|
||||
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)
|
||||
@@ -578,12 +809,17 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("启动 chromium 失败: %w", err)
|
||||
}
|
||||
// context、err 保存context、err,供当前处理流程使用
|
||||
context, err := browser.NewContext(playwright.BrowserNewContextOptions{
|
||||
// contextOptions 保留 Chromium 原生上下文配置;无头 UA 仅使用本次实测 runtime 的规范化版本。
|
||||
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 是 browser 的新隔离上下文;err 表示 context 创建失败并触发已启动浏览器回收。
|
||||
context, err := browser.NewContext(contextOptions)
|
||||
if err != nil {
|
||||
_ = browser.Close()
|
||||
return nil, fmt.Errorf("创建 context 失败: %w", err)
|
||||
|
||||
@@ -74,8 +74,8 @@ func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID
|
||||
}
|
||||
defer release()
|
||||
|
||||
// page、err 保存page、err,供当前处理流程使用
|
||||
page, err := bctx.NewPage()
|
||||
// page 在无头密码登录时会在导航前覆盖 UA 和 Client Hints,避免暴露 HeadlessChrome。
|
||||
page, err := m.newBrowserPage(bctx, headless)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("新建 page 失败: %w", err)
|
||||
}
|
||||
|
||||
@@ -92,13 +92,15 @@ func TestPasswordLoginReferenceProfileAndTiming(t *testing.T) {
|
||||
// TestPasswordPersistentContextOptionsMatchReference 负责Test密码Persistent上下文OptionsMatchReference相关处理。
|
||||
func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) {
|
||||
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "/opt/chromium")
|
||||
// opts 保存opts,供当前处理流程使用
|
||||
opts := passwordPersistentContextOptions(true)
|
||||
// userAgent 模拟从同版本 Chromium 实测后规范化出的无头身份。
|
||||
userAgent := "Mozilla/5.0 Chrome/149.0.7827.55 Safari/537.36"
|
||||
// opts 验证无头持久化密码登录会把该身份交给 Playwright context。
|
||||
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)
|
||||
@@ -118,6 +120,11 @@ func TestPasswordPersistentContextOptionsMatchReference(t *testing.T) {
|
||||
if opts.ExecutablePath == nil || *opts.ExecutablePath != "/opt/chromium" {
|
||||
t.Fatalf("Chromium 路径=%v", opts.ExecutablePath)
|
||||
}
|
||||
// headed 是有头密码登录配置,必须保留 Chromium 的原生 UA 而不使用无头覆盖。
|
||||
headed := passwordPersistentContextOptions(false, &userAgent)
|
||||
if headed.UserAgent != nil {
|
||||
t.Fatalf("有头密码登录应保留 Chromium 原生 UA: %v", headed.UserAgent)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPasswordLoginRejectsBlankCredentialsBeforeBrowserInit 负责Test密码登录RejectsBlankCredentialsBefore浏览器Init相关处理。
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
package browser
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/xianyu"
|
||||
)
|
||||
|
||||
// TestSanitize 特殊字符替换为下划线(用于 userDataDir 命名)。
|
||||
func TestSanitize(t *testing.T) {
|
||||
@@ -107,7 +113,88 @@ func TestChromiumExecutablePathFromEnv(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSkipPlaywrightBrowserDownloadFromEnv 负责TestSkipPlaywright浏览器DownloadFromEnv相关处理。
|
||||
// TestCaptchaIgnoreCertificateErrors 验证证书例外仅在明确环境开关为真时进入浏览器启动参数。
|
||||
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("无效值不应启用证书错误忽略开关")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeBrowserFingerprintRemovesOnlyHeadlessMarker 验证规范化不伪造 Chromium 的版本或平台身份。
|
||||
func TestNormalizeBrowserFingerprintRemovesOnlyHeadlessMarker(t *testing.T) {
|
||||
// fingerprint 是含无头标记的实测身份经过规范化后的结果,用于断言只移除产品标记。
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeUserAgentMetadataRemovesAndDeduplicatesHeadlessBrand 验证导航前 CDP 覆盖不会泄露无头品牌。
|
||||
func TestNormalizeUserAgentMetadataRemovesAndDeduplicatesHeadlessBrand(t *testing.T) {
|
||||
// metadata 是模拟页面返回的 Client Hints 经规范化后的副本,不应再暴露无头品牌。
|
||||
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 表示 CDP 可接收数组结构。
|
||||
brands, ok := metadata["brands"].([]any)
|
||||
if !ok || len(brands) != 2 {
|
||||
t.Fatalf("brands 未正确去重: %#v", metadata["brands"])
|
||||
}
|
||||
// fullVersions 是规范化后的完整版本品牌列表;ok 表示字段没有被意外改变类型。
|
||||
fullVersions, ok := metadata["fullVersionList"].([]any)
|
||||
if !ok || len(fullVersions) != 1 {
|
||||
t.Fatalf("fullVersionList 未正确去重: %#v", metadata["fullVersionList"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestManagerHeadlessUserAgentUsesDetectedRuntimeVersion 验证无头 UA 沿用实测 Chromium 版本而非静态伪造值。
|
||||
func TestManagerHeadlessUserAgentUsesDetectedRuntimeVersion(t *testing.T) {
|
||||
// m 模拟已完成运行时指纹探测的管理器,不需要启动真实 Chromium。
|
||||
m := &Manager{browserFingerprint: xianyu.BrowserFingerprint{UserAgent: "Mozilla/5.0 HeadlessChrome/149.0.7827.55 Safari/537.36"}}
|
||||
// userAgent 是 m 基于实测版本生成的无头 UA,应只替换产品标记。
|
||||
userAgent := m.headlessUserAgent()
|
||||
if userAgent == nil || *userAgent != "Mozilla/5.0 Chrome/149.0.7827.55 Safari/537.36" {
|
||||
t.Fatalf("headlessUserAgent=%v", userAgent)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSkipPlaywrightBrowserDownloadFromEnv 验证打包运行时可显式禁止 Playwright 下载新的浏览器。
|
||||
func TestSkipPlaywrightBrowserDownloadFromEnv(t *testing.T) {
|
||||
t.Setenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "")
|
||||
if skipPlaywrightBrowserDownload() {
|
||||
|
||||
@@ -47,6 +47,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)
|
||||
@@ -62,8 +63,8 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
|
||||
return "", "", fmt.Errorf("注入临时 cookie 失败: %w", err)
|
||||
}
|
||||
|
||||
// page、err 保存page、err,供当前处理流程使用
|
||||
page, err := bctx.NewPage()
|
||||
// page 在导航前应用无头运行时指纹,避免扫码换取 Cookie 时暴露 HeadlessChrome。
|
||||
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,661 @@
|
||||
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 指定诊断 zip 的本地目录;未设置时完全不创建诊断器。
|
||||
tokenCaptchaDiagnosticDirEnv = "CAPTCHA_DIAGNOSTIC_DIR"
|
||||
// tokenCaptchaDiagnosticSensitiveEnv 允许显式保留敏感正文,仅供受控排障环境,默认一律脱敏。
|
||||
tokenCaptchaDiagnosticSensitiveEnv = "CAPTCHA_DIAGNOSTIC_INCLUDE_SENSITIVE"
|
||||
// tokenCaptchaDiagnosticMaxEvents 限制每类事件最多记录 500 条,避免诊断失败放大内存或磁盘消耗。
|
||||
tokenCaptchaDiagnosticMaxEvents = 500
|
||||
)
|
||||
|
||||
// tokenCaptchaDiagnostic 在显式启用时收集一次 token CAPTCHA 失败现场;mu 保护事件与 initial,once 保证只写出一个包,且不得影响验证码结果路径。
|
||||
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
|
||||
}
|
||||
|
||||
// tokenCaptchaDiagnosticSnapshot 保存首次现场的页面、frame、选择器和截图,用于与最终失败现场比较。
|
||||
type tokenCaptchaDiagnosticSnapshot struct {
|
||||
CapturedAt string
|
||||
PageHTML string
|
||||
Screenshot []byte
|
||||
FrameHTML map[int]string
|
||||
Frames []tokenCaptchaDiagnosticFrame
|
||||
Selectors []tokenCaptchaDiagnosticSelector
|
||||
}
|
||||
|
||||
// tokenCaptchaDiagnosticNetworkEvent 是脱敏后的单条网络请求、响应或失败记录。
|
||||
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"`
|
||||
}
|
||||
|
||||
// tokenCaptchaDiagnosticConsoleEvent 保存页面控制台输出,默认先去除可能出现的凭证和验证参数。
|
||||
type tokenCaptchaDiagnosticConsoleEvent struct {
|
||||
At string `json:"at"`
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// tokenCaptchaDiagnosticFrame 描述当前页面树中一个 frame 的来源、父级和可读 HTML 状态。
|
||||
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"`
|
||||
}
|
||||
|
||||
// tokenCaptchaDiagnosticSelector 记录冻结选择器在某个 frame 中的发现、可见和边界框状态,不改变选择器本身。
|
||||
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"`
|
||||
}
|
||||
|
||||
// tokenCaptchaDiagnosticManifest 是诊断 zip 的脱敏索引,关联失败阶段、页面快照和有限事件流。
|
||||
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"`
|
||||
}
|
||||
|
||||
// newTokenCaptchaDiagnostic 在环境指定目录且 page 可用时安装只读诊断监听器;cookieID 仅存于内存且写包时哈希,返回 nil 表示诊断未启用。
|
||||
func newTokenCaptchaDiagnostic(cookieID, engine, requestedURL string, page playwright.Page, logger *slog.Logger) *tokenCaptchaDiagnostic {
|
||||
// dir 是诊断包输出目录,空值保持功能完全关闭。
|
||||
dir := strings.TrimSpace(os.Getenv(tokenCaptchaDiagnosticDirEnv))
|
||||
if dir == "" || page == nil {
|
||||
return nil
|
||||
}
|
||||
// d 持有本页监听器共享的诊断状态,回调通过 mu 串行写入有限事件列表。
|
||||
d := &tokenCaptchaDiagnostic{
|
||||
cookieID: cookieID,
|
||||
engine: engine,
|
||||
requestedURL: requestedURL,
|
||||
includeSensitive: diagnosticBoolEnv(tokenCaptchaDiagnosticSensitiveEnv),
|
||||
dir: dir,
|
||||
startedAt: time.Now().UTC(),
|
||||
logger: logger,
|
||||
}
|
||||
// request 是 Playwright 提供的请求事件,回调仅记录已脱敏的元数据。
|
||||
page.OnRequest(func(request playwright.Request) {
|
||||
d.recordRequest(request)
|
||||
})
|
||||
// response 是 Playwright 提供的响应事件,回调不会读取或持久化响应正文。
|
||||
page.OnResponse(func(response playwright.Response) {
|
||||
d.recordResponse(response)
|
||||
})
|
||||
// request 是失败的网络请求,回调在 d.mu 保护下追加一条受限数量的失败事件。
|
||||
page.OnRequestFailed(func(request playwright.Request) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if len(d.responses) >= tokenCaptchaDiagnosticMaxEvents {
|
||||
return
|
||||
}
|
||||
// failure 保存底层失败文本,默认不会包含请求 Cookie;err 表示 Playwright 无法提供失败详情。
|
||||
failure := ""
|
||||
// err 表示 Playwright 未能返回底层失败详情,失败事件仍保留其他无敏感元数据。
|
||||
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,
|
||||
})
|
||||
})
|
||||
// message 是页面控制台事件,内容在未授权敏感采集时先经过文本脱敏。
|
||||
page.OnConsole(func(message playwright.ConsoleMessage) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if len(d.console) >= tokenCaptchaDiagnosticMaxEvents {
|
||||
return
|
||||
}
|
||||
// text 是待写入诊断包的控制台文本,敏感模式关闭时会就地替换秘密参数。
|
||||
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 是待脱敏的页面异常文本,不能直接写入普通应用日志。
|
||||
text := pageErr.Error()
|
||||
if !d.includeSensitive {
|
||||
text = redactDiagnosticText(text)
|
||||
}
|
||||
d.pageError = append(d.pageError, text)
|
||||
})
|
||||
return d
|
||||
}
|
||||
|
||||
// diagnosticBoolEnv 按受限真值集合读取诊断开关,任何未知文本均按关闭处理。
|
||||
func diagnosticBoolEnv(name string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv(name))) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// recordRequest 在 d.mu 保护下记录一条脱敏请求元数据;达到上限后静默丢弃后续事件。
|
||||
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(),
|
||||
})
|
||||
}
|
||||
|
||||
// recordResponse 在 d.mu 保护下记录一条脱敏响应元数据,不读取可能包含凭证的响应正文。
|
||||
func (d *tokenCaptchaDiagnostic) recordResponse(response playwright.Response) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if len(d.responses) >= tokenCaptchaDiagnosticMaxEvents {
|
||||
return
|
||||
}
|
||||
// request 是与响应关联的请求,只用于记录方法和资源类型;contentType 只记录公开的响应媒体类型。
|
||||
request := response.Request()
|
||||
// contentType 记录响应的公开媒体类型,不读取可能携带账号数据的响应正文。
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
// safeURL 在默认模式删除 URL 查询值与 fragment,仅保留排序后的参数名和查询摘要;敏感模式由显式环境授权才原样返回。
|
||||
func (d *tokenCaptchaDiagnostic) safeURL(raw string) string {
|
||||
if d.includeSensitive {
|
||||
return raw
|
||||
}
|
||||
// u 是可结构化脱敏的 URL;err 表示输入不符合完整 URL 格式,此时回退通用日志脱敏。
|
||||
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 是解析出的查询参数;keys 只保留键名以表达请求形状而不暴露验证值。
|
||||
values := u.Query()
|
||||
// keys 只收集诊断中允许暴露的参数名,容量按查询字段数预留。
|
||||
keys := make([]string, 0, len(values))
|
||||
// key 是当前查询参数名,诊断包中允许保留但不保留对应值。
|
||||
for key := range values {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
// queryDigest 是原始查询串的短摘要,用于关联重复请求而不记录实际参数值。
|
||||
queryDigest := sha256.Sum256([]byte(u.RawQuery))
|
||||
u.RawQuery = "keys=" + strings.Join(keys, ",") + "&query_sha256=" + hex.EncodeToString(queryDigest[:])[:16]
|
||||
u.Fragment = ""
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// capture 在 d.once 保护下为一次失败写出诊断包;任何写包错误只输出脱敏错误并绝不改变 CAPTCHA 结果。
|
||||
func (d *tokenCaptchaDiagnostic) capture(page playwright.Page, phase string, cause error) {
|
||||
if d == nil || page == nil {
|
||||
return
|
||||
}
|
||||
// once 回调是唯一允许写包的路径,避免多个失败回调竞争创建诊断文件。
|
||||
d.once.Do(func() {
|
||||
// path 是生成 zip 的本地路径;err 表示诊断写入失败,不能向调用路径传播。
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// snapshotInitial 最多捕获一次导航后的初始现场;先在无锁状态读取 Playwright,再持锁发布完整快照,避免持锁外部 I/O。
|
||||
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 是无锁构造的初始页面副本,完成后仅在 initial 仍为空时发布。
|
||||
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)
|
||||
// index 是诊断包中的稳定 frame 序号;frame 是当前待抓取 HTML 的页面 frame。
|
||||
for index, frame := range append([]playwright.Frame{page.MainFrame()}, page.Frames()...) {
|
||||
// htmlText 是 frame 的初始 HTML;err 表示 frame 内容暂不可读,此时不影响整体诊断。
|
||||
if htmlText, err := frame.Content(); err == nil {
|
||||
snapshot.FrameHTML[index] = htmlText
|
||||
}
|
||||
}
|
||||
d.mu.Lock()
|
||||
if d.initial.CapturedAt == "" {
|
||||
d.initial = snapshot
|
||||
}
|
||||
d.mu.Unlock()
|
||||
}
|
||||
|
||||
// writeBundle 将当前和初始诊断现场写为原子 zip;返回最终本地路径,错误仅供 capture 记录而不得影响验证码流程。
|
||||
func (d *tokenCaptchaDiagnostic) writeBundle(page playwright.Page, phase string, cause error) (string, error) {
|
||||
// err 表示私有诊断目录无法创建,目录权限固定为仅当前用户可访问。
|
||||
if err := os.MkdirAll(d.dir, 0o700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// name 是不含明文账号标识的诊断文件名;target 是最终原子替换目标。
|
||||
name := fmt.Sprintf("token-captcha-%s-%s-%s.zip", logsafe.ID(d.cookieID), d.startedAt.Format("20060102T150405.000000000Z"), sanitize(d.engine))
|
||||
// target 是完成写入后通过同目录 Rename 发布的最终诊断 zip 路径。
|
||||
target := filepath.Join(d.dir, name)
|
||||
// tmp 是同目录的临时 zip;err 表示临时文件无法创建。
|
||||
tmp, err := os.CreateTemp(d.dir, ".token-captcha-*.zip.tmp")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// tmpName 用于 defer 清理和最终同目录 Rename,保证读者不会看到半写入文件。
|
||||
tmpName := tmp.Name()
|
||||
defer func() {
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(tmpName)
|
||||
}()
|
||||
// zw 是写入临时文件的 zip 流;closeZip 负责按成功或失败路径关闭并执行原子发布。
|
||||
zw := zip.NewWriter(tmp)
|
||||
// closeZip 在任一路径关闭流;成功时关闭临时文件并原子发布,失败时只返回原始操作错误。
|
||||
closeZip := func(closeErr error) error {
|
||||
if closeErr != nil {
|
||||
_ = zw.Close()
|
||||
return closeErr
|
||||
}
|
||||
// err 表示 zip 尾部无法完成写入,此时不发布损坏的诊断包。
|
||||
if err := zw.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 表示临时文件无法落盘关闭,Rename 前必须返回失败。
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmpName, target)
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
// requests、responses、console、pageErrors 是锁内事件的独立副本,后续 zip I/O 不持有 d.mu。
|
||||
requests := append([]tokenCaptchaDiagnosticNetworkEvent(nil), d.requests...)
|
||||
// responses 是响应和请求失败事件的锁内副本,后续写 zip 时不访问共享切片。
|
||||
responses := append([]tokenCaptchaDiagnosticNetworkEvent(nil), d.responses...)
|
||||
// console 是已按敏感模式处理的控制台事件副本。
|
||||
console := append([]tokenCaptchaDiagnosticConsoleEvent(nil), d.console...)
|
||||
// pageErrors 是已按敏感模式处理的页面异常文本副本。
|
||||
pageErrors := append([]string(nil), d.pageError...)
|
||||
d.mu.Unlock()
|
||||
// manifest 汇总可安全序列化的失败上下文,URL 和正文依赖当前敏感模式决定是否脱敏。
|
||||
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()
|
||||
}
|
||||
// title 是当前页面标题;titleErr 表示读取失败,此项可缺失且不阻塞诊断。
|
||||
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 是初始快照副本,FrameHTML 与 Screenshot 必须深拷贝后才能在无锁状态写包。
|
||||
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 表示存在无法编码的诊断字段。
|
||||
manifestJSON, err := json.MarshalIndent(manifest, "", " ")
|
||||
if err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
// err 表示索引条目未能写入 zip,closeZip 负责关闭资源并保留原始错误。
|
||||
if err := writeZipEntry(zw, "manifest.json", manifestJSON); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
// readme 说明诊断包来源和默认脱敏边界,不包含任何运行时凭证。
|
||||
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")
|
||||
// err 表示说明文件写入失败,诊断包不能作为完整工件发布。
|
||||
if err := writeZipEntry(zw, "README.txt", readme); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
// htmlText 是最终页面 HTML;htmlErr 表示页面内容暂不可读取,可继续输出其余诊断信息。
|
||||
if htmlText, htmlErr := page.Content(); htmlErr == nil {
|
||||
if !d.includeSensitive {
|
||||
htmlText = redactDiagnosticText(htmlText)
|
||||
}
|
||||
// err 表示最终页面 HTML 条目写入失败。
|
||||
if err := writeZipEntry(zw, "page.html", []byte(htmlText)); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
if initial.PageHTML != "" {
|
||||
// initialHTML 是待输出的初始页面 HTML,敏感模式关闭时在写入前脱敏。
|
||||
initialHTML := initial.PageHTML
|
||||
if !d.includeSensitive {
|
||||
initialHTML = redactDiagnosticText(initialHTML)
|
||||
}
|
||||
// err 表示初始页面 HTML 条目写入失败。
|
||||
if err := writeZipEntry(zw, "initial/page.html", []byte(initialHTML)); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
// index 是初始 frame 序号;frameHTML 是对应 HTML 副本,写前按敏感模式脱敏。
|
||||
for index, frameHTML := range initial.FrameHTML {
|
||||
if !d.includeSensitive {
|
||||
frameHTML = redactDiagnosticText(frameHTML)
|
||||
}
|
||||
// err 表示初始 frame 条目写入失败。
|
||||
if err := writeZipEntry(zw, fmt.Sprintf("initial/frames/frame-%02d.html", index), []byte(frameHTML)); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
if len(initial.Screenshot) > 0 {
|
||||
// err 表示初始截图条目写入失败。
|
||||
if err := writeZipEntry(zw, "initial/page.png", initial.Screenshot); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
// index 是最终现场 frame 序号;frame 是待读取和输出 HTML 的页面 frame。
|
||||
for index, frame := range append([]playwright.Frame{page.MainFrame()}, page.Frames()...) {
|
||||
// frameHTML 是最终 HTML;frameErr 表示当前 frame 内容不可用,可跳过而继续打包。
|
||||
frameHTML, frameErr := frame.Content()
|
||||
if frameErr != nil {
|
||||
continue
|
||||
}
|
||||
if !d.includeSensitive {
|
||||
frameHTML = redactDiagnosticText(frameHTML)
|
||||
}
|
||||
// err 表示最终 frame 条目写入失败。
|
||||
if err := writeZipEntry(zw, fmt.Sprintf("frames/frame-%02d.html", index), []byte(frameHTML)); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
// screenshot 是最终页面截图;screenshotErr 表示截图暂不可用,此时仍允许发布文本诊断。
|
||||
if screenshot, screenshotErr := page.Screenshot(playwright.PageScreenshotOptions{FullPage: playwright.Bool(true), Timeout: playwright.Float(5000)}); screenshotErr == nil {
|
||||
// err 表示截图条目写入失败。
|
||||
if err := writeZipEntry(zw, "page.png", screenshot); err != nil {
|
||||
return "", closeZip(err)
|
||||
}
|
||||
}
|
||||
// err 表示 zip 收尾或原子发布失败,调用方只记录该诊断错误。
|
||||
if err := closeZip(nil); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
// cloneDiagnosticFrameHTML 深拷贝 frame HTML 索引,避免 writeBundle 无锁处理时与 snapshot 发布共享 map。
|
||||
func cloneDiagnosticFrameHTML(input map[int]string) map[int]string {
|
||||
if len(input) == 0 {
|
||||
return nil
|
||||
}
|
||||
// output 是供调用方独占修改的 frame HTML map。
|
||||
output := make(map[int]string, len(input))
|
||||
// index 是 frame 序号;htmlText 是其已捕获的 HTML 文本。
|
||||
for index, htmlText := range input {
|
||||
output[index] = htmlText
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
// writeZipEntry 在 zw 中创建 name 并写入 data,返回创建或写入错误但不关闭调用方拥有的 zip 流。
|
||||
func writeZipEntry(zw *zip.Writer, name string, data []byte) error {
|
||||
// writer 是当前 zip 条目的写入器;err 表示条目名冲突或底层临时文件写入失败。
|
||||
writer, err := zw.Create(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = writer.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
// diagnosticPageState 读取页面公开运行状态;includeSensitive 为 false 时正文文本在返回前脱敏,脚本失败也返回可序列化错误状态。
|
||||
func diagnosticPageState(page playwright.Page, includeSensitive bool) map[string]any {
|
||||
// value 是页面脚本状态对象;err 表示脚本评估失败并转换为诊断字段而非向上返回。
|
||||
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()}
|
||||
}
|
||||
// state 是可写入 manifest 的页面状态对象;ok 表示脚本结果保持了预期结构。
|
||||
if state, ok := value.(map[string]any); ok {
|
||||
// body 是页面正文摘要;ok 表示该字段可按字符串脱敏处理。
|
||||
if body, ok := state["body_text"].(string); ok && !includeSensitive {
|
||||
state["body_text"] = redactDiagnosticText(body)
|
||||
}
|
||||
return state
|
||||
}
|
||||
return map[string]any{"value": value}
|
||||
}
|
||||
|
||||
// diagnosticFramesAndSelectors 枚举页面及嵌套 frame 中冻结选择器的观测结果;仅读取 DOM,不改变滑块实现、选择器优先级或页面状态。
|
||||
func diagnosticFramesAndSelectors(page playwright.Page, d *tokenCaptchaDiagnostic) ([]tokenCaptchaDiagnosticFrame, []tokenCaptchaDiagnosticSelector) {
|
||||
// frames 是主 frame 加全部已知 frame 的诊断遍历序列。
|
||||
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
|
||||
// frameMetadata 保存每个 frame 的来源和 HTML 可读性;selectors 是冻结选择器的本地副本,仅供观测。
|
||||
frameMetadata := make([]tokenCaptchaDiagnosticFrame, 0, len(frames))
|
||||
// selectors 是三个冻结选择器列表的本地拼接副本,仅用于诊断查询。
|
||||
selectors := append([]string{}, sliderButtonSelectors...)
|
||||
selectors = append(selectors, sliderTrackSelectors...)
|
||||
selectors = append(selectors, sliderRetrySelectors...)
|
||||
// index 是 frame 在诊断包中的稳定序号;frame 是当前待记录的页面 frame。
|
||||
for index, frame := range frames {
|
||||
// parentURL 是脱敏后的父 frame 地址,主 frame 保持空字符串。
|
||||
parentURL := ""
|
||||
// parent 是当前 frame 的父级,存在时用于记录嵌套来源。
|
||||
if parent := frame.ParentFrame(); parent != nil {
|
||||
parentURL = d.safeURL(parent.URL())
|
||||
}
|
||||
// metadata 是当前 frame 的可序列化观测记录。
|
||||
metadata := tokenCaptchaDiagnosticFrame{Index: index, Name: frame.Name(), URL: d.safeURL(frame.URL()), ParentURL: parentURL}
|
||||
// htmlText 是用来计算大小的 frame HTML;err 表示内容不可读并记录到 metadata。
|
||||
if htmlText, err := frame.Content(); err == nil {
|
||||
metadata.HTMLBytes = len(htmlText)
|
||||
} else {
|
||||
metadata.ContentErr = err.Error()
|
||||
}
|
||||
frameMetadata = append(frameMetadata, metadata)
|
||||
}
|
||||
// selectorRecords 保存每个 frame/选择器组合的只读探测结果。
|
||||
selectorRecords := make([]tokenCaptchaDiagnosticSelector, 0, len(frames)*len(selectors))
|
||||
// index 是当前被探测 frame 的序号;frame 是执行只读选择器查询的 frame。
|
||||
for index, frame := range frames {
|
||||
// frameURL 是写入诊断包的脱敏 frame 地址。
|
||||
frameURL := d.safeURL(frame.URL())
|
||||
// selector 是当前冻结选择器文本,只读取其可用状态,绝不修改定义或顺序。
|
||||
for _, selector := range selectors {
|
||||
// entry 是当前 frame/选择器组合的诊断结果。
|
||||
entry := tokenCaptchaDiagnosticSelector{FrameIndex: index, FrameURL: frameURL, Selector: selector}
|
||||
// el 是匹配到的页面元素;err 表示查询失败并记录在 entry 中。
|
||||
el, err := frame.QuerySelector(selector)
|
||||
if err != nil {
|
||||
entry.Error = err.Error()
|
||||
} else if el != nil {
|
||||
entry.Found = true
|
||||
entry.Visible = elementVisible(el)
|
||||
// box 是元素边界框;boxErr 表示当前无法读取位置,仍保留已发现状态。
|
||||
if box, boxErr := el.BoundingBox(); boxErr == nil {
|
||||
entry.Box = formatBoundingBox(box)
|
||||
}
|
||||
}
|
||||
selectorRecords = append(selectorRecords, entry)
|
||||
}
|
||||
}
|
||||
return frameMetadata, selectorRecords
|
||||
}
|
||||
|
||||
// redactDiagnosticText 替换已知 Cookie、验证码和签名参数值,供默认诊断包的 URL、HTML、控制台和错误文本共同使用。
|
||||
func redactDiagnosticText(text string) string {
|
||||
// key 是当前要隐藏值的敏感参数名,保留键名以便定位问题类别。
|
||||
for _, key := range []string{"x5secdata", "x5sec", "_m_h5_tk", "_m_h5_tk_enc", "token", "sign"} {
|
||||
text = redactDiagnosticKey(text, key)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// redactDiagnosticKey 用大小写无关模式隐藏 text 中指定 key 的值,不记录 Cookie、Token 或签名明文。
|
||||
func redactDiagnosticKey(text, key string) string {
|
||||
// pattern 匹配参数值直到常见分隔符,键名由 QuoteMeta 处理以避免改变正则语义。
|
||||
pattern := regexp.MustCompile(`(?i)` + regexp.QuoteMeta(key) + `=[^&'"<>\s\\` + "`" + `)]*`)
|
||||
return pattern.ReplaceAllStringFunc(text, func(match string) string {
|
||||
// index 是键和值之间等号的位置,存在时仅保留键和等号。
|
||||
if index := strings.IndexByte(match, '='); index >= 0 {
|
||||
return match[:index+1] + "<redacted>"
|
||||
}
|
||||
return match
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
// TestTokenCaptchaDiagnosticRedactsSensitiveValues 验证默认诊断输出不会保留验证码查询值、fragment 或文本中的敏感凭证。
|
||||
func TestTokenCaptchaDiagnosticRedactsSensitiveValues(t *testing.T) {
|
||||
// d 是禁用敏感内容采集的最小诊断器,不需要真实浏览器或输出目录。
|
||||
d := &tokenCaptchaDiagnostic{includeSensitive: false}
|
||||
// got 是脱敏后的 URL,允许保留参数名与查询摘要以支持问题关联。
|
||||
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 是同时含 Cookie 验证和签名类参数的模拟诊断文本。
|
||||
text := `x5secdata=secret-value&token=another-secret sign=third-secret`
|
||||
// redacted 是可安全写入默认诊断包的替换后文本。
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTokenCaptchaDiagnosticBundleBrowserIntegration 在真实 Chromium 中验证诊断包包含必要现场且默认不泄漏验证码查询值;仅在显式浏览器集成模式运行。
|
||||
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 提供含冻结滑块元素的本地页面,避免访问真实平台或使用真实账号。
|
||||
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 是 testing 管理的临时诊断输出目录,测试结束后自动清理。
|
||||
dir := t.TempDir()
|
||||
t.Setenv(tokenCaptchaDiagnosticDirEnv, dir)
|
||||
t.Setenv(tokenCaptchaDiagnosticSensitiveEnv, "")
|
||||
// m 管理本次集成测试的 Playwright runtime,defer Close 负责回收资源。
|
||||
m := NewManager(nil)
|
||||
defer m.Close()
|
||||
// err 表示 runtime 初始化失败,无法继续验证真实浏览器诊断。
|
||||
if err := m.init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// browser 是测试启动的无头 Chromium;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 是 browser 的隔离页面上下文;err 表示 context 创建失败。
|
||||
bctx, err := browser.NewContext()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = bctx.Close() }()
|
||||
// page 是承载诊断监听器的本地测试页面;err 表示页面创建失败。
|
||||
page, err := bctx.NewPage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// diagnostic 是由显式临时目录启用的诊断器,账户标识在产物中仅以哈希形式出现。
|
||||
diagnostic := newTokenCaptchaDiagnostic("diagnostic-account", "playwright", server.URL+"/punish?x5secdata=secret", page, m.logger)
|
||||
// err 表示本地滑块页面导航失败,不能继续捕获诊断快照。
|
||||
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 是输出目录中生成的诊断 zip;err 表示文件模式匹配失败。
|
||||
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 是待检查的唯一诊断 zip;err 表示压缩包无法读取。
|
||||
archive, err := zip.OpenReader(archives[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer archive.Close()
|
||||
// entries 按条目名保存压缩包内容,供后续完整性和脱敏断言使用。
|
||||
entries := make(map[string][]byte)
|
||||
// file 是当前压缩包条目,逐个读取后立即关闭其 reader。
|
||||
for _, file := range archive.File {
|
||||
// reader 是当前条目的读取器;readErr 表示条目打开失败。
|
||||
reader, readErr := file.Open()
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
// data 是条目完整字节内容;readErr 表示读取过程失败。
|
||||
data, readErr := io.ReadAll(reader)
|
||||
_ = reader.Close()
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
entries[file.Name] = data
|
||||
}
|
||||
// name 是每个必须存在的诊断条目路径,缺失说明捕获或写包协议被破坏。
|
||||
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)
|
||||
}
|
||||
}
|
||||
// manifest 是从包内索引反序列化的结构,供断言失败阶段与初始快照信息。
|
||||
var manifest tokenCaptchaDiagnosticManifest
|
||||
// err 表示 manifest JSON 不符合诊断包契约。
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,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("备用滑块引擎参数不完整")
|
||||
}
|
||||
@@ -59,7 +59,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
|
||||
@@ -103,11 +103,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{
|
||||
@@ -123,6 +130,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 {
|
||||
@@ -182,6 +192,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)
|
||||
@@ -196,7 +207,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",
|
||||
@@ -205,9 +216,17 @@ func fallbackChromiumArgs(profileDir string, headless bool) []string {
|
||||
"--disable-blink-features=AutomationControlled",
|
||||
"--window-size=1920,1080",
|
||||
"--lang=zh-CN",
|
||||
"about:blank",
|
||||
}
|
||||
args = append(playwrightChromiumCompatibilityArgs(), args...)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFallbackChromiumArgsIncludePlaywrightCompatibilityFlags 验证备用 Chromium 保留 Playwright 兼容启动参数。
|
||||
|
||||
@@ -22,6 +22,12 @@ type Repository interface {
|
||||
UpdateMessageType(ctx context.Context, cookieID, key, messageType string) error
|
||||
// UpdateMessageStatus 更新外发消息状态并返回最新消息。
|
||||
UpdateMessageStatus(ctx context.Context, cookieID, key, status string) (*db.ChatMessage, error)
|
||||
// CountUnreadUserMessages 返回当前会话中非系统入站消息的未读数量。
|
||||
CountUnreadUserMessages(ctx context.Context, cookieID, chatID string) (int, error)
|
||||
// MarkMessageRead 根据平台回执标记指定出站消息已读。
|
||||
MarkMessageRead(ctx context.Context, cookieID, key string, readAt int64) (*db.ChatMessage, error)
|
||||
// MarkLatestOutgoingRead 在回执缺失消息键时标记会话最近一条未读出站消息。
|
||||
MarkLatestOutgoingRead(ctx context.Context, cookieID, chatID string, readAt int64) (*db.ChatMessage, error)
|
||||
}
|
||||
|
||||
// storeRepository 将聚合 Store 的聊天相关 repository 适配为窄接口。
|
||||
@@ -65,6 +71,21 @@ func (r storeRepository) UpdateMessageStatus(ctx context.Context, cookieID, key,
|
||||
return r.store.Chats.UpdateMessageStatus(ctx, cookieID, key, status)
|
||||
}
|
||||
|
||||
// CountUnreadUserMessages 委托消息级真实用户未读数统计。
|
||||
func (r storeRepository) CountUnreadUserMessages(ctx context.Context, cookieID, chatID string) (int, error) {
|
||||
return r.store.Chats.CountUnreadUserMessages(ctx, cookieID, chatID)
|
||||
}
|
||||
|
||||
// MarkMessageRead 委托指定出站消息的已读回执写入。
|
||||
func (r storeRepository) MarkMessageRead(ctx context.Context, cookieID, key string, readAt int64) (*db.ChatMessage, error) {
|
||||
return r.store.Chats.MarkMessageRead(ctx, cookieID, key, readAt)
|
||||
}
|
||||
|
||||
// MarkLatestOutgoingRead 委托会话级出站消息已读回退写入。
|
||||
func (r storeRepository) MarkLatestOutgoingRead(ctx context.Context, cookieID, chatID string, readAt int64) (*db.ChatMessage, error) {
|
||||
return r.store.Chats.MarkLatestOutgoingRead(ctx, cookieID, chatID, readAt)
|
||||
}
|
||||
|
||||
// newStoreRepository 从完整 Store 构造聊天服务使用的窄 repository。
|
||||
func newStoreRepository(store *db.Store) Repository {
|
||||
if store == nil || store.Cookies == nil || store.Chats == nil {
|
||||
|
||||
@@ -42,6 +42,21 @@ func (*fakeRepository) UpdateMessageStatus(_ context.Context, _ string, _ string
|
||||
return &db.ChatMessage{Status: status}, nil
|
||||
}
|
||||
|
||||
// CountUnreadUserMessages 为窄仓储测试提供空的真实用户未读统计结果。
|
||||
func (*fakeRepository) CountUnreadUserMessages(context.Context, string, string) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// MarkMessageRead 为窄仓储测试模拟指定出站消息的已读更新。
|
||||
func (*fakeRepository) MarkMessageRead(_ context.Context, _ string, key string, readAt int64) (*db.ChatMessage, error) {
|
||||
return &db.ChatMessage{MessageKey: key, ReadStatus: 2, ReadAt: readAt}, nil
|
||||
}
|
||||
|
||||
// MarkLatestOutgoingRead 为窄仓储测试模拟缺失消息键时的会话级回退更新。
|
||||
func (*fakeRepository) MarkLatestOutgoingRead(_ context.Context, _ string, chatID string, readAt int64) (*db.ChatMessage, error) {
|
||||
return &db.ChatMessage{ChatID: chatID, ReadStatus: 2, ReadAt: readAt}, nil
|
||||
}
|
||||
|
||||
// TestServiceUsesNarrowRepository 验证聊天服务可以脱离完整 db.Store 运行。
|
||||
func TestServiceUsesNarrowRepository(t *testing.T) {
|
||||
// repository 是只实现聊天所需方法的内存替身。
|
||||
|
||||
+118
-8
@@ -145,10 +145,12 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
||||
if lastMessageAt <= 0 {
|
||||
lastMessageAt = modifyTime
|
||||
}
|
||||
// session 保存会话,供当前处理流程使用
|
||||
// unreadCount 是平台红点与本地真实用户消息状态归一后的展示数量。
|
||||
unreadCount := s.conversationUnreadCount(ctx, accountID, cid, peerID, conv, last, summary)
|
||||
// session 保存待写入的非敏感会话摘要及归一后的未读数量。
|
||||
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 保存err,供当前处理流程使用
|
||||
err := s.repository.UpsertSession(ctx, session); err != nil {
|
||||
return page, err
|
||||
@@ -161,7 +163,79 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// invalidNicknames 保存invalidNicknames,供当前处理流程使用
|
||||
// conversationUnreadCount 以平台红点为上限,并用本地真实用户消息已读状态排除系统卡片。
|
||||
func (s *Service) conversationUnreadCount(ctx context.Context, accountID, chatID, peerID string, conv, last map[string]any, summary string) int {
|
||||
// official 保存平台会话红点;负数响应按零处理。
|
||||
official := int(int64Value(conv["redPoint"]))
|
||||
if official < 0 {
|
||||
official = 0
|
||||
}
|
||||
if official == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
// local、err 保存本地真实用户未读数及查询错误;查询失败时回退平台红点。
|
||||
if local, err := s.repository.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 保存最后一条系统消息在官方会话红点中的未读份额。
|
||||
systemUnread := int(int64Value(last["unreadCount"]))
|
||||
// readStatus 保存最后一条系统消息的协议已读状态,缺少未读数时用于保守扣除。
|
||||
readStatus := int64Value(last["readStatus"])
|
||||
if systemUnread <= 0 && readStatus != 2 {
|
||||
systemUnread = 1
|
||||
}
|
||||
if systemUnread > official {
|
||||
systemUnread = official
|
||||
}
|
||||
return official - systemUnread
|
||||
}
|
||||
|
||||
// historyMessageIsSystem 判断平台会话摘要是否代表系统消息,避免系统卡片制造用户未读。
|
||||
func historyMessageIsSystem(last map[string]any, summary string) bool {
|
||||
// extension 保存会话末条消息的扩展字段,包含协议发送者身份。
|
||||
extension := mapValue(last["extension"])
|
||||
// senderID 保存协议发送者标识,供系统账号和系统卡片分类使用。
|
||||
senderID := cleanNilString(extension["senderUserId"])
|
||||
// content 保存解码后的系统卡片内容;解码失败时保留空对象供后续摘要规则判断。
|
||||
content := map[string]any{}
|
||||
// contentMap、ok 保存消息内容对象及其类型断言结果,非对象响应无需继续读取卡片字段。
|
||||
if contentMap, ok := last["content"].(map[string]any); ok {
|
||||
// custom、ok 保存自定义消息容器及其类型断言结果,卡片编码仅存在于该容器。
|
||||
if custom, ok := contentMap["custom"].(map[string]any); ok {
|
||||
// encoded 保存 Base64 卡片载荷,空载荷代表没有可解码的系统协议内容。
|
||||
if encoded := cleanNilString(custom["data"]); encoded != "" {
|
||||
// raw、err 保存解码后的卡片 JSON 与解码错误;错误时退回摘要分类,且不传播载荷。
|
||||
if raw, err := base64.StdEncoding.DecodeString(encoded); err == nil {
|
||||
_ = json.Unmarshal(raw, &content)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return isOfficialSystemMessage(content, senderID, summary)
|
||||
}
|
||||
|
||||
// invalidNicknames 保存不能作为买家真实昵称持久化的系统展示文本。
|
||||
var invalidNicknames = map[string]struct{}{
|
||||
"交易消息": {}, "系统消息": {}, "卡片消息": {}, "我完成了评价": {}, "对方完成了评价": {},
|
||||
"快给ta一个评价吧~": {}, "卖家已发货": {}, "买家已付款": {}, "买家已确认收货": {},
|
||||
@@ -207,6 +281,7 @@ type Incoming struct {
|
||||
BuyerID string
|
||||
BuyerName string
|
||||
Text string
|
||||
MessageID string
|
||||
ItemID string
|
||||
Raw map[string]any
|
||||
}
|
||||
@@ -308,8 +383,11 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess
|
||||
if sentAt == 0 {
|
||||
sentAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
// key 保存key,供当前处理流程使用
|
||||
key := extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid")
|
||||
// key 优先使用引擎提供的稳定平台消息 ID,缺失时再从原始消息递归提取。
|
||||
key := strings.TrimSpace(in.MessageID)
|
||||
if key == "" {
|
||||
key = extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid")
|
||||
}
|
||||
if key == "" {
|
||||
// raw 保存原始,供当前处理流程使用
|
||||
raw, _ := json.Marshal(in.Raw)
|
||||
@@ -334,8 +412,8 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess
|
||||
// message 保存消息,供当前处理流程使用
|
||||
message := db.ChatMessage{MessageKey: key, Direction: "incoming", SenderID: in.BuyerID,
|
||||
SenderName: in.BuyerName, MessageType: messageType, Content: content, Status: "received", SentAt: sentAt}
|
||||
// stored、inserted、err 保存stored、inserted、err,供当前处理流程使用
|
||||
stored, inserted, err := s.repository.SaveMessage(ctx, session, message, true)
|
||||
// stored、inserted、err 保存落库消息、首次插入标识及错误;系统消息永不增加用户红点。
|
||||
stored, inserted, err := s.repository.SaveMessage(ctx, session, message, messageType != "system")
|
||||
if err == nil && inserted {
|
||||
s.Publish(in.AccountID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||
}
|
||||
@@ -665,7 +743,27 @@ func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status
|
||||
return message, err
|
||||
}
|
||||
|
||||
// randomID 负责randomID相关处理。
|
||||
// MarkOutgoingRead 根据平台回执把指定出站消息标记已读并广播增量事件。
|
||||
func (s *Service) MarkOutgoingRead(ctx context.Context, accountID, key string, readAt int64) (*db.ChatMessage, error) {
|
||||
// message、err 保存已读更新后的消息及持久化错误。
|
||||
message, err := s.repository.MarkMessageRead(ctx, accountID, key, readAt)
|
||||
if err == nil {
|
||||
s.Publish(accountID, Event{Type: "message.updated", Message: message})
|
||||
}
|
||||
return message, err
|
||||
}
|
||||
|
||||
// MarkLatestOutgoingRead 在回执未带幂等键时回退标记会话最近待确认的出站消息。
|
||||
func (s *Service) MarkLatestOutgoingRead(ctx context.Context, accountID, chatID string, readAt int64) (*db.ChatMessage, error) {
|
||||
// message、err 保存回退更新后的消息及持久化错误。
|
||||
message, err := s.repository.MarkLatestOutgoingRead(ctx, accountID, chatID, readAt)
|
||||
if err == nil {
|
||||
s.Publish(accountID, Event{Type: "message.updated", Message: message})
|
||||
}
|
||||
return message, err
|
||||
}
|
||||
|
||||
// randomID 生成本地出站消息幂等键的随机后缀;随机源失败时使用时间回退避免阻断发送。
|
||||
func randomID() string {
|
||||
// value 保存值,供当前处理流程使用
|
||||
var value [16]byte
|
||||
@@ -715,6 +813,18 @@ 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.
|
||||
// decoded 保存 extJson/bizTag 解码后的动态对象,供递归查找平台消息键。
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(x), &decoded) == nil {
|
||||
// text 保存递归命中的非空消息键,命中后立即返回避免生成本地回退键。
|
||||
if text := walk(decoded); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -130,7 +130,29 @@ func TestRecordIncomingClassifiesXianxiaomiAndPlaceholder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordConversationPageImportsHistoricalContacts 负责TestRecordConversation页码ImportsHistoricalContacts相关处理。
|
||||
// TestRecordIncomingExtractsMessageIDFromEncodedExtension 验证嵌套扩展中的平台消息键优先进入实时落库。
|
||||
func TestRecordIncomingExtractsMessageIDFromEncodedExtension(t *testing.T) {
|
||||
// store、cleanup 保存隔离聊天数据库及清理函数,确保消息键提取不依赖其他用例数据。
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
// service 是待测聊天服务,使用上述存储验证实时消息落库。
|
||||
service := New(store)
|
||||
// message、err 保存落库后的消息和处理错误,消息键必须来自编码扩展字段。
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordConversationPageImportsHistoricalContacts 验证联系人历史页不会覆盖较新的会话摘要。
|
||||
func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := chatTestStore(t)
|
||||
@@ -197,6 +219,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 保存err,供当前处理流程使用
|
||||
@@ -210,12 +233,75 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordConversationPageSkipsEmptyConversationShells 负责TestRecordConversation页码SkipsEmptyConversationShells相关处理。
|
||||
// TestConversationUnreadCountUsesRedPointButFiltersSystemMessages 验证官方红点不会把系统卡片计为用户未读。
|
||||
func TestConversationUnreadCountUsesRedPointButFiltersSystemMessages(t *testing.T) {
|
||||
// store、cleanup 保存隔离聊天数据库及清理函数,供红点与本地未读数交叉验证。
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
// service 是待测聊天服务,负责按系统消息规则折算会话红点。
|
||||
service := New(store)
|
||||
|
||||
// systemCard 保存模拟交易通知的 Base64 卡片载荷,使末条消息被归类为系统消息。
|
||||
systemCard := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26}`))
|
||||
// systemLast 保存带官方红点和系统未读状态的末条消息协议对象。
|
||||
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),
|
||||
}
|
||||
// got 保存扣除系统消息后的用户未读数,系统部分不得显示为用户红点。
|
||||
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)
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
|
||||
// err 保存真实用户消息持久化错误;成功后本地消息级未读数应优先于官方红点。
|
||||
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 保存真实用户末条消息协议对象,不含系统卡片字段。
|
||||
userLast := map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"summary": "未读消息"}},
|
||||
}
|
||||
// got 保存本地记录的真实用户未读数,必须防止较慢官方刷新复活已读红点。
|
||||
if got := service.conversationUnreadCount(context.Background(), "account-1", "real", "peer", map[string]any{"redPoint": float64(3)}, userLast, "未读消息"); got != 1 {
|
||||
t.Fatalf("未使用消息级真实未读数: got=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHistoryMessageIsSystem 验证历史卡片载荷和普通用户文本被正确区分,避免误算未读。
|
||||
func TestHistoryMessageIsSystem(t *testing.T) {
|
||||
// encoded 保存模拟交易卡片的 Base64 载荷,触发内容类型的系统消息识别。
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26,"dxCard":{}}`))
|
||||
// last 保存待识别的历史末条消息协议对象。
|
||||
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("真实用户文本不应被识别为系统消息")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordConversationPageSkipsEmptyConversationShells 验证空会话壳不会被错误展示为联系人。
|
||||
func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := chatTestStore(t)
|
||||
|
||||
+77
-18
@@ -35,6 +35,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"`
|
||||
}
|
||||
|
||||
@@ -156,6 +158,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 保存now,供当前处理流程使用
|
||||
now := time.Now().UTC().Unix()
|
||||
@@ -181,14 +190,14 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag
|
||||
|
||||
// prefix 保存prefix,供当前处理流程使用
|
||||
prefix := dialectInsertIgnorePrefix(s.Dialect)
|
||||
// query 保存查询,供当前处理流程使用
|
||||
// query 保存带已读字段的幂等插入 SQL,三方言冲突时保持同一列顺序。
|
||||
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"})
|
||||
// res、err 保存res、err,供当前处理流程使用
|
||||
(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 保存插入结果及执行错误,用于判断是否更新会话摘要。
|
||||
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)
|
||||
}
|
||||
@@ -222,13 +231,13 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag
|
||||
|
||||
// GetMessageByKey 读取消息ByKey。
|
||||
func (s *ChatStore) GetMessageByKey(ctx context.Context, cookieID, key string) (*ChatMessage, error) {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 保存按账号和幂等键读取的完整聊天消息。
|
||||
var m ChatMessage
|
||||
// err 保存err,供当前处理流程使用
|
||||
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 保存查询错误;不存在时转换为仓储统一的 ErrNotFound。
|
||||
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
|
||||
}
|
||||
@@ -279,8 +288,8 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
// query 保存查询,供当前处理流程使用
|
||||
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 保存按时间倒序读取再反转为时间正序的分页 SQL。
|
||||
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 保存args,供当前处理流程使用
|
||||
@@ -301,11 +310,11 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch
|
||||
// result 保存结果,供当前处理流程使用
|
||||
var result []ChatMessage
|
||||
for rows.Next() {
|
||||
// m 保存m,供当前处理流程使用
|
||||
// m 保存当前扫描出的消息及其本地已读状态。
|
||||
var m ChatMessage
|
||||
if // err 保存err,供当前处理流程使用
|
||||
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 {
|
||||
// err 保存当前行字段映射错误,避免返回缺少已读字段的不完整消息。
|
||||
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.ReadStatus, &m.ReadAt, &m.SentAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, m)
|
||||
@@ -318,15 +327,33 @@ func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, ch
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
// MarkRead 负责MarkRead相关处理。
|
||||
// MarkRead 仅对当前用户拥有账号的非系统入站消息标记已读,并同步归零会话红点。
|
||||
func (s *ChatStore) MarkRead(ctx context.Context, userID int64, cookieID, chatID string) error {
|
||||
// err 保存err,供当前处理流程使用
|
||||
// now 是同一批消息和会话状态使用的统一 UTC 时间,避免页面显示先后矛盾。
|
||||
now := time.Now().UTC()
|
||||
// err 保存批量更新非系统入站消息的错误;失败时不得清空会话红点以避免状态不一致。
|
||||
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 保存归零会话红点的错误,该更新通过用户归属子查询阻止越权修改。
|
||||
_, 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 返回界面红点使用的入站真实用户未读数,系统消息永不计入。
|
||||
func (s *ChatStore) CountUnreadUserMessages(ctx context.Context, cookieID, chatID string) (int, error) {
|
||||
// count 保存符合当前账号、会话及未读条件的消息总数。
|
||||
var count int
|
||||
// err 保存聚合查询错误,调用方可在平台响应缺失时退回官方红点值。
|
||||
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
|
||||
}
|
||||
|
||||
// UpdateMessageStatus 更新消息状态。
|
||||
func (s *ChatStore) UpdateMessageStatus(ctx context.Context, cookieID, key, status string) (*ChatMessage, error) {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
@@ -335,3 +362,35 @@ func (s *ChatStore) UpdateMessageStatus(ctx context.Context, cookieID, key, stat
|
||||
}
|
||||
return s.GetMessageByKey(ctx, cookieID, key)
|
||||
}
|
||||
|
||||
// MarkMessageRead 按平台回执把一条出站消息标记为已读,并返回更新后的消息。
|
||||
func (s *ChatStore) MarkMessageRead(ctx context.Context, cookieID, key string, readAt int64) (*ChatMessage, error) {
|
||||
// readAt 保存平台已读时间;缺失时使用本机 UTC 时间作为展示回退。
|
||||
if readAt <= 0 {
|
||||
readAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
// err 保存只更新出站消息的数据库错误,防止错误改写入站状态。
|
||||
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)
|
||||
}
|
||||
|
||||
// MarkLatestOutgoingRead 在回执未带消息键时回退标记会话中最近待确认的出站消息。
|
||||
func (s *ChatStore) MarkLatestOutgoingRead(ctx context.Context, cookieID, chatID string, readAt int64) (*ChatMessage, error) {
|
||||
// readAt 保存平台已读时间;缺失时使用本机 UTC 时间作为展示回退。
|
||||
if readAt <= 0 {
|
||||
readAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
// key 保存最近一条已发送且未标记已读的消息幂等键。
|
||||
var key string
|
||||
// err 保存查询错误;没有可更新消息时返回统一 ErrNotFound。
|
||||
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)
|
||||
}
|
||||
@@ -105,6 +105,53 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
|
||||
db2.Close()
|
||||
}
|
||||
|
||||
// TestMigrate_UpgradesDatabaseWithMainChatVersions 验证已发布 main 的 00029/00030
|
||||
// 聊天迁移可以原样升级到合并后的 dev 最终版本。
|
||||
func TestMigrate_UpgradesDatabaseWithMainChatVersions(t *testing.T) {
|
||||
// tmpDir 保存隔离的已发布 main 数据库目录,测试结束后由 testing 清理。
|
||||
tmpDir := t.TempDir()
|
||||
// dbPath 指向模拟已运行至 main 00030 的 SQLite 文件。
|
||||
dbPath := filepath.Join(tmpDir, "main-chat-v30.db")
|
||||
// rawDB 在调用 Open 前控制 Goose 只执行已发布的 main 迁移。
|
||||
rawDB, openErr := sql.Open("sqlite", sqliteDSN(dbPath))
|
||||
if openErr != nil {
|
||||
t.Fatalf("open legacy database: %v", openErr)
|
||||
}
|
||||
defer rawDB.Close()
|
||||
|
||||
// dialectErr 保存 Goose SQLite 方言设置失败,失败时不能构造已发布迁移基线。
|
||||
if dialectErr := goose.SetDialect("sqlite3"); dialectErr != nil {
|
||||
t.Fatalf("set goose dialect: %v", dialectErr)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
// upErr 将数据库推进到已发布 main 的 00030,验证之后的 dev 迁移连续接续。
|
||||
upErr := goose.UpTo(rawDB, "migrations/sqlite", 30)
|
||||
if upErr != nil {
|
||||
t.Fatalf("apply released main migrations: %v", upErr)
|
||||
}
|
||||
|
||||
// ctx 提供迁移 API 所需的调用上下文;升级本身不依赖请求生命周期。
|
||||
ctx := context.Background()
|
||||
// migrateErr 保存从 main 00030 接续 dev 00031 时的迁移失败。
|
||||
if migrateErr := Migrate(ctx, rawDB, DialectSQLite); migrateErr != nil {
|
||||
t.Fatalf("upgrade from main 00030: %v", migrateErr)
|
||||
}
|
||||
if !tableExists(t, rawDB, "order_reconciliations") {
|
||||
t.Fatal("order_reconciliations should be created by the dev schema baseline migration")
|
||||
}
|
||||
if !columnExists(t, rawDB, "chat_messages", "read_status") || !columnExists(t, rawDB, "chat_messages", "read_at") {
|
||||
t.Fatal("chat read tracking columns should remain after dev schema baseline upgrade")
|
||||
}
|
||||
// finalVersion 验证迁移账本已推进到合并后的单一 dev schema 基线版本。
|
||||
finalVersion, versionErr := goose.GetDBVersion(rawDB)
|
||||
if versionErr != nil {
|
||||
t.Fatalf("read final migration version: %v", versionErr)
|
||||
}
|
||||
if finalVersion != 31 {
|
||||
t.Fatalf("final migration version=%d, want 31", finalVersion)
|
||||
}
|
||||
}
|
||||
|
||||
// columnExists 负责columnExists相关处理。
|
||||
func columnExists(t *testing.T, db *sql.DB, table, col string) bool {
|
||||
t.Helper()
|
||||
@@ -156,7 +203,7 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
}
|
||||
// i 表示本次回滚操作序号。
|
||||
for i := 0; version >= 14; i++ {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 保存当前迁移回滚错误,任一方言步骤失败即终止验证。
|
||||
err := goose.Down(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("down migration #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -220,6 +267,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
{"account_task_runs", "run_key"},
|
||||
{"chat_sessions", "unread_count"},
|
||||
{"chat_messages", "message_key"},
|
||||
{"chat_messages", "read_status"},
|
||||
{"chat_messages", "read_at"},
|
||||
{"notification_outbox", "uncertain_at"},
|
||||
} {
|
||||
if !columnExists(t, d, c.table, c.col) {
|
||||
|
||||
@@ -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;
|
||||
@@ -1,16 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS order_reconciliations (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
order_id VARCHAR(255) NOT NULL,
|
||||
cookie_id VARCHAR(255) NOT NULL,
|
||||
kind VARCHAR(100) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'pending',
|
||||
error_message TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
INDEX idx_order_reconciliations_pending (status, created_at, id)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS order_reconciliations;
|
||||
@@ -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.
|
||||
@@ -1,5 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE INDEX idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX idx_orders_cursor ON orders;
|
||||
@@ -0,0 +1,57 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS order_reconciliations (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
order_id VARCHAR(255) NOT NULL,
|
||||
cookie_id VARCHAR(255) NOT NULL,
|
||||
kind VARCHAR(100) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'pending',
|
||||
error_message TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
INDEX idx_order_reconciliations_pending (status, created_at, id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
|
||||
id VARCHAR(64) PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
cookie_id VARCHAR(255) NOT NULL DEFAULT '',
|
||||
filter_status VARCHAR(64) NOT NULL DEFAULT '',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'queued',
|
||||
result_json LONGTEXT NOT NULL,
|
||||
error_message TEXT NOT NULL,
|
||||
worker_token VARCHAR(128) NOT NULL DEFAULT '',
|
||||
lease_expires_at BIGINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_order_refresh_jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
INDEX idx_order_refresh_jobs_user (user_id, created_at, id),
|
||||
INDEX idx_order_refresh_jobs_lease (status, lease_expires_at)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS security_audit_logs (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
user_id BIGINT NOT NULL,
|
||||
action VARCHAR(128) NOT NULL,
|
||||
resource VARCHAR(255) NOT NULL,
|
||||
keys_json TEXT NOT NULL,
|
||||
outcome VARCHAR(32) NOT NULL DEFAULT 'accepted',
|
||||
created_at BIGINT NOT NULL,
|
||||
INDEX idx_security_audit_logs_user_created (user_id, created_at, id)
|
||||
);
|
||||
|
||||
ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE notification_outbox ADD COLUMN idempotency_key VARCHAR(255) NULL;
|
||||
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
|
||||
ON notification_outbox(channel_id, idempotency_key);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX idx_notification_outbox_channel_idempotency ON notification_outbox;
|
||||
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
|
||||
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
|
||||
DROP TABLE IF EXISTS security_audit_logs;
|
||||
DROP TABLE IF EXISTS order_refresh_jobs;
|
||||
DROP INDEX idx_orders_cursor ON orders;
|
||||
DROP TABLE IF EXISTS order_reconciliations;
|
||||
@@ -1,20 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
|
||||
id VARCHAR(64) PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
cookie_id VARCHAR(255) NOT NULL DEFAULT '',
|
||||
filter_status VARCHAR(64) NOT NULL DEFAULT '',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'queued',
|
||||
result_json LONGTEXT NOT NULL,
|
||||
error_message TEXT NOT NULL,
|
||||
worker_token VARCHAR(128) NOT NULL DEFAULT '',
|
||||
lease_expires_at BIGINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_order_refresh_jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
INDEX idx_order_refresh_jobs_user (user_id, created_at, id),
|
||||
INDEX idx_order_refresh_jobs_lease (status, lease_expires_at)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS order_refresh_jobs;
|
||||
@@ -1,14 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS security_audit_logs (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
user_id BIGINT NOT NULL,
|
||||
action VARCHAR(128) NOT NULL,
|
||||
resource VARCHAR(255) NOT NULL,
|
||||
keys_json TEXT NOT NULL,
|
||||
outcome VARCHAR(32) NOT NULL DEFAULT 'accepted',
|
||||
created_at BIGINT NOT NULL,
|
||||
INDEX idx_security_audit_logs_user_created (user_id, created_at, id)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS security_audit_logs;
|
||||
@@ -1,6 +0,0 @@
|
||||
-- +goose Up
|
||||
-- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。
|
||||
ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
|
||||
@@ -1,10 +0,0 @@
|
||||
-- +goose Up
|
||||
-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。
|
||||
-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。
|
||||
ALTER TABLE notification_outbox ADD COLUMN idempotency_key VARCHAR(255) NULL;
|
||||
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
|
||||
ON notification_outbox(channel_id, idempotency_key);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX idx_notification_outbox_channel_idempotency ON notification_outbox;
|
||||
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
|
||||
@@ -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;
|
||||
@@ -1,17 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS order_reconciliations (
|
||||
id TEXT PRIMARY KEY,
|
||||
order_id TEXT NOT NULL,
|
||||
cookie_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending
|
||||
ON order_reconciliations(status, created_at, id);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS order_reconciliations;
|
||||
@@ -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.
|
||||
@@ -1,5 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS idx_orders_cursor;
|
||||
@@ -0,0 +1,60 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS order_reconciliations (
|
||||
id TEXT PRIMARY KEY,
|
||||
order_id TEXT NOT NULL,
|
||||
cookie_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending
|
||||
ON order_reconciliations(status, created_at, id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
cookie_id TEXT NOT NULL DEFAULT '',
|
||||
filter_status TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'queued',
|
||||
result_json TEXT NOT NULL DEFAULT '{}',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
worker_token TEXT NOT NULL DEFAULT '',
|
||||
lease_expires_at BIGINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS security_audit_logs (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
action VARCHAR(128) NOT NULL,
|
||||
resource VARCHAR(255) NOT NULL,
|
||||
keys_json TEXT NOT NULL DEFAULT '[]',
|
||||
outcome VARCHAR(32) NOT NULL DEFAULT 'accepted',
|
||||
created_at BIGINT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created
|
||||
ON security_audit_logs(user_id, created_at DESC, id DESC);
|
||||
|
||||
ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL;
|
||||
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
|
||||
ON notification_outbox(channel_id, idempotency_key);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency;
|
||||
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
|
||||
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
|
||||
DROP TABLE IF EXISTS security_audit_logs;
|
||||
DROP INDEX IF EXISTS idx_order_refresh_jobs_lease;
|
||||
DROP INDEX IF EXISTS idx_order_refresh_jobs_user;
|
||||
DROP TABLE IF EXISTS order_refresh_jobs;
|
||||
DROP INDEX IF EXISTS idx_orders_cursor;
|
||||
DROP TABLE IF EXISTS order_reconciliations;
|
||||
@@ -1,21 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
cookie_id TEXT NOT NULL DEFAULT '',
|
||||
filter_status TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'queued',
|
||||
result_json TEXT NOT NULL DEFAULT '{}',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
worker_token TEXT NOT NULL DEFAULT '',
|
||||
lease_expires_at BIGINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS idx_order_refresh_jobs_lease;
|
||||
DROP INDEX IF EXISTS idx_order_refresh_jobs_user;
|
||||
DROP TABLE IF EXISTS order_refresh_jobs;
|
||||
@@ -1,16 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS security_audit_logs (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
action VARCHAR(128) NOT NULL,
|
||||
resource VARCHAR(255) NOT NULL,
|
||||
keys_json TEXT NOT NULL DEFAULT '[]',
|
||||
outcome VARCHAR(32) NOT NULL DEFAULT 'accepted',
|
||||
created_at BIGINT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created
|
||||
ON security_audit_logs(user_id, created_at DESC, id DESC);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS security_audit_logs;
|
||||
@@ -1,6 +0,0 @@
|
||||
-- +goose Up
|
||||
-- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。
|
||||
ALTER TABLE notification_outbox ADD COLUMN uncertain_at BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
|
||||
@@ -1,10 +0,0 @@
|
||||
-- +goose Up
|
||||
-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。
|
||||
-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。
|
||||
ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL;
|
||||
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
|
||||
ON notification_outbox(channel_id, idempotency_key);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency;
|
||||
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
|
||||
@@ -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;
|
||||
@@ -1,17 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS order_reconciliations (
|
||||
id TEXT PRIMARY KEY,
|
||||
order_id TEXT NOT NULL,
|
||||
cookie_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending
|
||||
ON order_reconciliations(status, created_at, id);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS order_reconciliations;
|
||||
@@ -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.
|
||||
@@ -1,5 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS idx_orders_cursor;
|
||||
@@ -0,0 +1,60 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS order_reconciliations (
|
||||
id TEXT PRIMARY KEY,
|
||||
order_id TEXT NOT NULL,
|
||||
cookie_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_reconciliations_pending
|
||||
ON order_reconciliations(status, created_at, id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_orders_cursor ON orders(cookie_id, deleted_at, created_at DESC, order_id DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
cookie_id TEXT NOT NULL DEFAULT '',
|
||||
filter_status TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'queued',
|
||||
result_json TEXT NOT NULL DEFAULT '{}',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
worker_token TEXT NOT NULL DEFAULT '',
|
||||
lease_expires_at INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS security_audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
resource TEXT NOT NULL,
|
||||
keys_json TEXT NOT NULL DEFAULT '[]',
|
||||
outcome TEXT NOT NULL DEFAULT 'accepted',
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created
|
||||
ON security_audit_logs(user_id, created_at DESC, id DESC);
|
||||
|
||||
ALTER TABLE notification_outbox ADD COLUMN uncertain_at INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL;
|
||||
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
|
||||
ON notification_outbox(channel_id, idempotency_key);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency;
|
||||
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
|
||||
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
|
||||
DROP TABLE IF EXISTS security_audit_logs;
|
||||
DROP INDEX IF EXISTS idx_order_refresh_jobs_lease;
|
||||
DROP INDEX IF EXISTS idx_order_refresh_jobs_user;
|
||||
DROP TABLE IF EXISTS order_refresh_jobs;
|
||||
DROP INDEX IF EXISTS idx_orders_cursor;
|
||||
DROP TABLE IF EXISTS order_reconciliations;
|
||||
@@ -1,21 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
cookie_id TEXT NOT NULL DEFAULT '',
|
||||
filter_status TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'queued',
|
||||
result_json TEXT NOT NULL DEFAULT '{}',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
worker_token TEXT NOT NULL DEFAULT '',
|
||||
lease_expires_at INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS idx_order_refresh_jobs_lease;
|
||||
DROP INDEX IF EXISTS idx_order_refresh_jobs_user;
|
||||
DROP TABLE IF EXISTS order_refresh_jobs;
|
||||
@@ -1,16 +0,0 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE IF NOT EXISTS security_audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
resource TEXT NOT NULL,
|
||||
keys_json TEXT NOT NULL DEFAULT '[]',
|
||||
outcome TEXT NOT NULL DEFAULT 'accepted',
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_security_audit_logs_user_created
|
||||
ON security_audit_logs(user_id, created_at DESC, id DESC);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS security_audit_logs;
|
||||
@@ -1,6 +0,0 @@
|
||||
-- +goose Up
|
||||
-- uncertain_at 记录外部发送成功但本地确认失败的隔离时间,避免租约过期后自动重复发送。
|
||||
ALTER TABLE notification_outbox ADD COLUMN uncertain_at INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE notification_outbox DROP COLUMN uncertain_at;
|
||||
@@ -1,10 +0,0 @@
|
||||
-- +goose Up
|
||||
-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。
|
||||
-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。
|
||||
ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL;
|
||||
CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency
|
||||
ON notification_outbox(channel_id, idempotency_key);
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency;
|
||||
ALTER TABLE notification_outbox DROP COLUMN idempotency_key;
|
||||
@@ -1222,7 +1222,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
}
|
||||
// i 表示本次回滚操作序号。
|
||||
for i := 0; version >= 14; i++ {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
if // err 保存当前方言迁移回滚错误,失败时保留步骤号诊断。
|
||||
err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration down #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -1285,6 +1285,8 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
{"account_task_runs", "run_key"},
|
||||
{"chat_sessions", "unread_count"},
|
||||
{"chat_messages", "message_key"},
|
||||
{"chat_messages", "read_status"},
|
||||
{"chat_messages", "read_at"},
|
||||
} {
|
||||
if !columnExistsForDialect(t, tg.store.DB, tg.dialect, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
|
||||
@@ -68,3 +68,32 @@ func (w *WSMessageStore) DeleteBefore(ctx context.Context, cookieID string, cuto
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
// FindInboundParsedJSONContaining 返回最近的已解密入站诊断帧,供旧版聊天消息标识迁移使用。
|
||||
func (w *WSMessageStore) FindInboundParsedJSONContaining(ctx context.Context, cookieID, fragment string, limit int) ([]string, error) {
|
||||
// safeLimit 限制诊断查询行数,避免单次已读操作读取过多历史帧。
|
||||
safeLimit := limit
|
||||
if safeLimit <= 0 || safeLimit > 100 {
|
||||
safeLimit = 20
|
||||
}
|
||||
// rows、err 保存匹配的诊断帧游标及数据库查询错误。
|
||||
rows, err := w.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 ?`, cookieID, "%"+fragment+"%", safeLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
// values 保存按时间倒序读取的已解密诊断 JSON。
|
||||
values := make([]string, 0, safeLimit)
|
||||
for rows.Next() {
|
||||
// value 保存当前诊断帧的解析 JSON。
|
||||
var value string
|
||||
// scanErr 保存当前诊断帧字段扫描错误。
|
||||
if scanErr := rows.Scan(&value); scanErr != nil {
|
||||
return nil, scanErr
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
@@ -85,7 +85,25 @@ type Handler interface {
|
||||
OnAccountAlert(ctx context.Context, cookieID, level, title, body string)
|
||||
}
|
||||
|
||||
// accountEventHandler 保存账号EventHandler,供当前处理流程使用
|
||||
// MessageReadHandler 是可选的聊天已读回执端口,旧 Handler 实现不必承担该能力。
|
||||
type MessageReadHandler interface {
|
||||
// HandleMessageRead 接收已解析且不包含凭证的平台已读事件。
|
||||
HandleMessageRead(context.Context, MessageReadEvent) error
|
||||
}
|
||||
|
||||
// MessageReadEvent 是平台出站消息已读状态的非敏感事件载体。
|
||||
type MessageReadEvent struct {
|
||||
// AccountID 是当前运行时账号标识。
|
||||
AccountID string
|
||||
// ChatID 是平台会话标识。
|
||||
ChatID string
|
||||
// MessageID 是平台 PNM 消息标识。
|
||||
MessageID string
|
||||
// ReadAt 是平台或本机记录的 Unix 毫秒已读时间。
|
||||
ReadAt int64
|
||||
}
|
||||
|
||||
// accountEventHandler 保存账号事件扩展端口,供可选通知器识别类型化告警。
|
||||
type accountEventHandler interface {
|
||||
OnAccountEvent(ctx context.Context, cookieID, eventType, level, title, body string)
|
||||
}
|
||||
@@ -129,6 +147,7 @@ type ChatMessage struct {
|
||||
SenderUserID string
|
||||
SenderName string
|
||||
Text string
|
||||
MessageID string
|
||||
ItemID string
|
||||
Raw map[string]any // 解密后的完整消息
|
||||
}
|
||||
@@ -838,6 +857,26 @@ func (a *Account) SendText(ctx context.Context, chatID, toUserID, text string) e
|
||||
return a.outgoing.sendText(ctx, chatID, toUserID, text)
|
||||
}
|
||||
|
||||
// MarkChatRead 向已连接的 WebSocket 上报会话消息已读状态,调用方负责用户所有权校验。
|
||||
func (a *Account) MarkChatRead(ctx context.Context, chatID string, messageIDs []map[string]any) error {
|
||||
// conn、err 保存当前连接快照及不可发送时的生命周期错误。
|
||||
conn, _, err := a.outgoing.currentSenderState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// readCtx、cancel 为平台上报设置固定超时,取消责任在本方法返回时释放。
|
||||
readCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
// reader、ok 保存连接是否支持可选的已读上报能力。
|
||||
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 {
|
||||
return a.outgoing.sendImage(ctx, chatID, toUserID, imageURL, cardID)
|
||||
|
||||
+200
-7
@@ -3,8 +3,12 @@ package engine
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
// dispatch 是 ws.ReceiveLoop 的回调,对每条解密后的消息做:
|
||||
@@ -19,6 +23,107 @@ func (a *Account) handleMessage(decrypted map[string]any) {
|
||||
a.messageDispatcher.handleMessage(decrypted)
|
||||
}
|
||||
|
||||
// extractMessageReadEvent 从解密 WebSocket 事件中提取出站消息已读回执。
|
||||
func extractMessageReadEvent(v map[string]any) (MessageReadEvent, bool) {
|
||||
// 40103 解密后不会保留外层 objectType,只剩下固定的紧凑字段:
|
||||
// 1=PNM 消息 ID、2=状态(2=已读)、4=会话 ID、6=事件时间。
|
||||
// 不能只在解密后的 map 里继续寻找 "bizType":40103,否则真实回执
|
||||
// 会被当成普通消息静默丢弃。
|
||||
// messageID 保存紧凑回执或嵌套事件中的平台 PNM 消息 ID。
|
||||
messageID := strings.TrimSpace(toString(v["1"]))
|
||||
// ids 保存批量回执携带的 PNM ID 列表;ok 表示字段 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 保存紧凑回执携带的会话 ID,旧信封缺失时回退字段 3。
|
||||
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
|
||||
}
|
||||
// found 标记已定位 40103 信封;ev 累积其会话和消息标识;walk 递归读取兼容嵌套结构。
|
||||
var found bool
|
||||
// ev 保存从嵌套兼容回执中提取的平台会话与消息标识。
|
||||
var ev MessageReadEvent
|
||||
// walk 解析对象、数组或 JSON 字符串形式的嵌套事件,命中后停止后续遍历。
|
||||
var walk func(any)
|
||||
walk = func(x any) {
|
||||
if found {
|
||||
return
|
||||
}
|
||||
// m 保存当前遍历节点被识别出的具体 JSON 数据类型。
|
||||
switch m := x.(type) {
|
||||
case map[string]any:
|
||||
// k 为当前字段名;val 为其原始 JSON 值,用来定位回执事件类型。
|
||||
for k, val := range m {
|
||||
// lk 是小写化字段名,兼容平台信封的不同字段命名。
|
||||
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
|
||||
}
|
||||
// child 为当前对象中的嵌套值,继续搜索未解包的回执信封。
|
||||
for _, child := range m {
|
||||
walk(child)
|
||||
}
|
||||
case []any:
|
||||
// child 为当前批量信封中的一个候选事件。
|
||||
for _, child := range m {
|
||||
walk(child)
|
||||
}
|
||||
case string:
|
||||
// 部分同步信封将事件体编码为转义 JSON 字符串,而非已解码对象。
|
||||
// decoded 保存反序列化后的事件体,兼容字符串包装的同步消息。
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(m), &decoded) == nil {
|
||||
walk(decoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(v)
|
||||
if !found || ev.MessageID == "" {
|
||||
return MessageReadEvent{}, false
|
||||
}
|
||||
return ev, true
|
||||
}
|
||||
|
||||
// extractNestedString 在嵌套信封中按大小写无关键名查找第一个非空字符串。
|
||||
func extractNestedString(m map[string]any, keys ...string) string {
|
||||
// k 是当前字段名;v 是字段原值,用于大小写无关地匹配候选键。
|
||||
for k, v := range m {
|
||||
// want 为调用方允许的目标字段名。
|
||||
for _, want := range keys {
|
||||
if strings.EqualFold(k, want) && strings.TrimSpace(toString(v)) != "" {
|
||||
return strings.TrimSpace(toString(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
// v 为当前对象中的嵌套值,继续查询其中的兼容子信封。
|
||||
for _, v := range m {
|
||||
// child 为可继续递归解析的对象;ok 表示当前值是否是对象结构。
|
||||
if child, ok := v.(map[string]any); ok {
|
||||
// s 保存子信封中找到的第一个非空目标字段值。
|
||||
if s := extractNestedString(child, keys...); s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// markAndCheckDedup 提取消息 ID,检查 1 小时内是否已处理;未处理则标记。
|
||||
// 返回 true 表示应继续处理。移植自 _schedule_debounced_reply 的去重段。
|
||||
// markAndCheckDedup 负责markAndCheckDedup相关处理。
|
||||
@@ -38,16 +143,24 @@ func (a *Account) scheduleDebouncedReply(chat ChatMessage) {
|
||||
a.messageDispatcher.scheduleDebouncedReply(chat)
|
||||
}
|
||||
|
||||
// extractMessageID 从 message["1"]["10"]["bizTag"] 或 extJson 中提取 messageId。
|
||||
// 移植自 _extract_message_id。
|
||||
// extractMessageID 负责extract消息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 保存m1、ok,供当前处理流程使用
|
||||
m1, ok := decrypted["1"].(map[string]any)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
// m10、ok 保存m10、ok,供当前处理流程使用
|
||||
// id 保存实时消息最可靠的 PNM ID,存在时不可用推送关联 ID 覆盖。
|
||||
if id := strings.TrimSpace(toString(m1["3"])); id != "" && id != "<nil>" {
|
||||
return id
|
||||
}
|
||||
// m10、ok 保存消息展示扩展及其是否存在,用于兼容旧消息关联 ID。
|
||||
m10, ok := m1["10"].(map[string]any)
|
||||
if !ok {
|
||||
return ""
|
||||
@@ -66,6 +179,55 @@ func extractMessageID(decrypted map[string]any) string {
|
||||
return id
|
||||
}
|
||||
}
|
||||
// reminderURL 保存提醒链接,旧消息会将推送关联 ID 编码在其查询参数中。
|
||||
if reminderURL, _ := m10["reminderUrl"].(string); reminderURL != "" {
|
||||
// parsed 保存已解析的提醒链接;err 表示 URL 格式不合法时的解析失败。
|
||||
if parsed, err := url.Parse(reminderURL); err == nil {
|
||||
// id 保存 reminderUrl 查询参数中的兼容消息关联 ID。
|
||||
if id := strings.TrimSpace(parsed.Query().Get("messageId")); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
return findMessageID(decrypted)
|
||||
}
|
||||
|
||||
// findMessageID 递归解析兼容消息信封中可能存在的关联消息 ID。
|
||||
func findMessageID(value any) string {
|
||||
// x 保存当前待搜索节点的具体值,按对象、数组和 JSON 字符串分别处理。
|
||||
switch x := value.(type) {
|
||||
case map[string]any:
|
||||
// key 是对象字段名;child 是字段值,用于先检查本层关联 ID。
|
||||
for key, child := range x {
|
||||
if strings.EqualFold(key, "messageId") || strings.EqualFold(key, "message_id") {
|
||||
// id 保存当前字段提供的非空关联消息 ID。
|
||||
if id := strings.TrimSpace(fmt.Sprint(child)); id != "" && id != "<nil>" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
// child 为本层嵌套字段值,递归兼容更深层信封。
|
||||
for _, child := range x {
|
||||
// id 保存子节点中首先发现的关联消息 ID。
|
||||
if id := findMessageID(child); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
// child 为批量消息中的一个候选事件或子信封。
|
||||
for _, child := range x {
|
||||
// id 保存数组成员中首先发现的关联消息 ID。
|
||||
if id := findMessageID(child); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
case string:
|
||||
// decoded 保存从 JSON 字符串解码后的兼容嵌套结构。
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(x), &decoded) == nil {
|
||||
return findMessageID(decoded)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -110,9 +272,14 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
|
||||
if i := strings.Index(chatID, "@"); i >= 0 {
|
||||
chatID = chatID[:i]
|
||||
}
|
||||
// senderUserID 保存sender用户ID,供当前处理流程使用
|
||||
senderUserID, _ := m10["senderUserId"].(string)
|
||||
// senderName 保存sender名称,供当前处理流程使用
|
||||
// senderUserID 保存经兼容字段归一后的发送者身份。
|
||||
senderUserID := extractChatSenderUserIDFromMaps(m1, m10)
|
||||
if isSelfUserID(senderUserID, protocol.TransCookies(cookieStr)["unb"]) {
|
||||
// 官方客户端会通过同一 WebSocket 回显本账号发出的消息;它仅表示投递观察,
|
||||
// 并非买家新输入,绝不能进入自动回复链。
|
||||
return nil
|
||||
}
|
||||
// senderName 保存发送者展示名称,字段缺失时由提醒标题补齐。
|
||||
senderName, _ := m10["senderNick"].(string)
|
||||
if strings.TrimSpace(senderName) == "" {
|
||||
senderName, _ = m10["reminderTitle"].(string)
|
||||
@@ -128,11 +295,37 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
|
||||
SenderUserID: senderUserID,
|
||||
SenderName: senderName,
|
||||
Text: reminder,
|
||||
MessageID: extractMessageID(decrypted),
|
||||
ItemID: itemID,
|
||||
Raw: decrypted,
|
||||
}
|
||||
}
|
||||
|
||||
// extractChatSenderUserIDFromMaps 优先读取展示扩展,并兼容紧凑信封中的发送者账号 ID。
|
||||
func extractChatSenderUserIDFromMaps(m1, m10 map[string]any) string {
|
||||
if m10 != nil {
|
||||
// sender 保存标准 senderUserId 的去空白结果。
|
||||
if sender := strings.TrimSpace(toString(m10["senderUserId"])); sender != "" {
|
||||
return sender
|
||||
}
|
||||
}
|
||||
// 部分回显消息缺少 10.senderUserId,但仍在紧凑 1.1 信封中保留发送者身份。
|
||||
// sender 保存紧凑信封中的发送者对象;ok 表示该兼容字段是否存在。
|
||||
if sender, ok := m1["1"].(map[string]any); ok {
|
||||
return strings.TrimSpace(toString(sender["1"]))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// isSelfUserID 比较发送者与当前账号身份,忽略 IM 协议后缀以过滤官方客户端回显。
|
||||
func isSelfUserID(senderUserID, selfUserID string) bool {
|
||||
// sender 是归一化后的消息发送者身份。
|
||||
sender := strings.TrimSuffix(strings.TrimSpace(senderUserID), "@goofish")
|
||||
// self 是归一化后的当前账号身份。
|
||||
self := strings.TrimSuffix(strings.TrimSpace(selfUserID), "@goofish")
|
||||
return sender != "" && self != "" && sender == self
|
||||
}
|
||||
|
||||
// isNonUserChatNotice 判断闲鱼 IM 中不应进入自动回复的系统提示或交易卡片。
|
||||
// 典型样本:
|
||||
// - contentType=14:“有蚂蚁森林能量可领”“不想宝贝被砍价?设置不砍价回复”“退款成功”
|
||||
|
||||
@@ -146,6 +146,24 @@ func TestHandleMessage_DedupSkipsRepeat(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMessage_IgnoresOwnWebSocketEcho 验证当前账号的 WS 回显不会触发自动回复。
|
||||
func TestHandleMessage_IgnoresOwnWebSocketEcho(t *testing.T) {
|
||||
// acc 是待测账号;h 记录业务处理调用;cleanup 释放测试数据库和运行时资源。
|
||||
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 保存acc、h、cleanup,供当前处理流程使用
|
||||
@@ -584,3 +602,22 @@ func plainChatMessage(t *testing.T, text, senderUserID, chatID string) map[strin
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// TestExtractMessageReadEvent40103 验证紧凑和批量 40103 已读事件均能生成规范回执。
|
||||
func TestExtractMessageReadEvent40103(t *testing.T) {
|
||||
// event 是单条紧凑回执的解析结果;ok 表示该输入已被识别为已读事件。
|
||||
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 复用为该回执的事件识别结果。
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -124,7 +124,20 @@ func TestExtractChatMessageUsesReminderTitleAsNickname(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractChatMessage_FiltersRefundTradeCard 负责TestExtract聊天消息FiltersRefundTrade卡密相关处理。
|
||||
// TestExtractChatMessageIgnoresOwnWebSocketEcho 验证账号自身的 WebSocket 回显不会进入回复链。
|
||||
func TestExtractChatMessageIgnoresOwnWebSocketEcho(t *testing.T) {
|
||||
// decrypted 模拟账号自身发送后由同一 WebSocket 回传的解密聊天信封。
|
||||
decrypted := map[string]any{"1": map[string]any{
|
||||
"2": "chat-1@goofish",
|
||||
"10": map[string]any{"reminderContent": "我在官方客户端发送的消息", "senderUserId": "self-1", "senderNick": "我"},
|
||||
}}
|
||||
// chat 是提取结果;账号自身的回显必须被过滤,因此应为 nil。
|
||||
if chat := extractChatMessage(decrypted, "account-1", "unb=self-1;"); chat != nil {
|
||||
t.Fatalf("账号自身发送的 WS 回显不应进入自动回复链: %+v", chat)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractChatMessage_FiltersRefundTradeCard 验证退款交易卡不会被识别为用户聊天。
|
||||
func TestExtractChatMessage_FiltersRefundTradeCard(t *testing.T) {
|
||||
// decrypted 保存decrypted,供当前处理流程使用
|
||||
decrypted := mustRefundTradeCard(t)
|
||||
|
||||
@@ -157,6 +157,21 @@ func (d *messageDispatcher) handleMessage(decrypted map[string]any) {
|
||||
|
||||
// handleMessageContext 将系统事件和聊天消息分别交给对应业务链。
|
||||
func (d *messageDispatcher) handleMessageContext(ctx context.Context, decrypted map[string]any) {
|
||||
// receipt、ok 保存解析出的平台已读回执及是否命中已读事件格式。
|
||||
if receipt, ok := extractMessageReadEvent(decrypted); ok {
|
||||
receipt.AccountID = d.cookieID
|
||||
// handler 保存当前可选处理器;旧集成不实现回执端口时保持兼容。
|
||||
if handler := d.currentHandler(); handler != nil {
|
||||
// reader 是可消费已读回执的可选端口;supported 表示当前集成实现了该端口。
|
||||
if reader, supported := handler.(MessageReadHandler); supported {
|
||||
// err 保存回执持久化错误;失败不应中断 WebSocket 接收循环。
|
||||
if err := reader.HandleMessageRead(ctx, receipt); err != nil {
|
||||
d.logger.Warn("处理聊天已读回执失败", "err", err, "message_id", receipt.MessageID)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
// 系统卡片和平台通知优先进入自动化中心,永远不进入 AI 回复范围。
|
||||
if task := automation.ExtractTaskFromWS(d.cookieID, d.currentCookie(), decrypted); task != nil {
|
||||
if // handler 保存handler,供当前处理流程使用
|
||||
|
||||
@@ -262,18 +262,19 @@ func TestParseMessageIDFromJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractMessageID 优先 bizTag,其次 extJson,无则空。
|
||||
// TestExtractMessageID 优先实时消息的 PNM ID,其次兼容 bizTag/extJson,无则空。
|
||||
func TestExtractMessageID(t *testing.T) {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
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 保存got,供当前处理流程使用
|
||||
got := extractMessageID(map[string]any{
|
||||
|
||||
@@ -366,10 +366,8 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
panic(itemCatalogMutationErr)
|
||||
}
|
||||
// itemPublishPort 是单商品与批量发布共享的平台凭证适配器。
|
||||
itemPublishPort := server.itemDependencies.NewItemPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) {
|
||||
if sessionRecovery != nil {
|
||||
sessionRecovery(ctx, cookieID, err)
|
||||
}
|
||||
itemPublishPort := server.itemDependencies.NewItemPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) bool {
|
||||
return sessionRecovery != nil && sessionRecovery(ctx, cookieID, err)
|
||||
})
|
||||
// itemCategoryRecommendation 复用商品发布端口承载类目推荐和响应会话写回。
|
||||
itemCategoryRecommendation, itemCategoryRecommendationErr := itemapp.NewCategoryRecommendationService(itemPublishPort)
|
||||
|
||||
@@ -64,6 +64,9 @@ func (s *Server) listCards(w http.ResponseWriter, r *http.Request) {
|
||||
// cards、err 保存应用服务返回的用户卡券列表及查询错误。
|
||||
cards, err := s.cardsApplication().List(r.Context(), session.UserID)
|
||||
if err != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Error("查询卡密失败", "user_id", session.UserID, "err", err)
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -147,3 +147,43 @@ func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFindChatPlatformMessageID 验证历史推送关联 ID 只在同一会话内映射为 PNM 已读 ID。
|
||||
func TestFindChatPlatformMessageID(t *testing.T) {
|
||||
// raw 模拟持久化的解密 WS 消息,包含推送关联 ID 与平台 PNM ID。
|
||||
raw := map[string]any{
|
||||
"1": map[string]any{
|
||||
"2": "64725235816@goofish",
|
||||
"3": "4263141580162.PNM",
|
||||
"10": map[string]any{
|
||||
"extJson": `{"messageId":"f87f8f6dabca4eff940863ef72a393f7"}`,
|
||||
},
|
||||
},
|
||||
}
|
||||
// got 保存同会话匹配后可向平台上报的 PNM ID。
|
||||
if got := findChatPlatformMessageID(raw, "64725235816", "f87f8f6dabca4eff940863ef72a393f7"); got != "4263141580162.PNM" {
|
||||
t.Fatalf("platform message id=%q", got)
|
||||
}
|
||||
// got 保存跨会话查询结果,必须为空以禁止错误标记其他会话已读。
|
||||
if got := findChatPlatformMessageID(raw, "other-chat", "f87f8f6dabca4eff940863ef72a393f7"); got != "" {
|
||||
t.Fatalf("跨会话错误匹配: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveChatReadMessageIDsMigratesLegacyID 验证历史关联 ID 会转换为平台接受的 PNM ID。
|
||||
func TestResolveChatReadMessageIDsMigratesLegacyID(t *testing.T) {
|
||||
// srv 提供待测解析路径;store 写入历史 WS 消息;cleanup 释放测试服务器和数据库。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// raw 是保存到数据库的解密信封 JSON,含旧关联 ID 及其对应的 PNM ID。
|
||||
raw := `{"1":{"2":"64725235816@goofish","3":"4263141580162.PNM","10":{"extJson":"{\"messageId\":\"f87f8f6dabca4eff940863ef72a393f7\"}"}}}`
|
||||
// err 保存写入历史 WS 消息失败的原因,写入失败会使后续解析夹具无效。
|
||||
if err := store.WSMessages.Add(context.Background(), db.WSMessage{CookieID: "acc1", Direction: "in", ParsedJSON: raw, ParseStatus: "decrypted"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// got 是兼容解析后的上报参数,旧关联 ID 必须被替换为 PNM ID。
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -284,8 +285,9 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
|
||||
// input 保存input,供当前处理流程使用
|
||||
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, "请求格式错误")
|
||||
@@ -295,17 +297,90 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
// sess 保存当前认证用户,用于应用层归属隔离。
|
||||
// sess 保存当前认证用户,用于本地未读状态归属隔离。
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
slog.Info("收到聊天已读请求", "account", input.AccountID, "chat_id", input.ChatID, "message_count", len(input.MessageIDs))
|
||||
if len(input.MessageIDs) == 0 {
|
||||
// page 保存应用层返回的本地消息页,只含非敏感字段。
|
||||
page, listErr := s.chatApplication().ListStoredMessages(r.Context(), sess.UserID, input.AccountID, input.ChatID, 0, 200)
|
||||
if listErr == nil {
|
||||
// message 是当前用于补全平台已读消息标识的入站消息。
|
||||
for _, message := range page.Messages {
|
||||
if message.Direction == "incoming" && message.MessageType != "system" {
|
||||
input.MessageIDs = append(input.MessageIDs, map[string]any{"messageId": message.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)
|
||||
if // err 保存应用层已读状态更新错误。
|
||||
err := s.chatApplication().MarkRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新已读状态失败")
|
||||
return
|
||||
}
|
||||
if s.Manager != nil {
|
||||
// sender、ok 保存当前账号运行时及其在线状态。
|
||||
if sender, ok := s.Manager.GetInstance(input.AccountID); ok {
|
||||
// reader、ok 保存运行时是否支持平台已读上报。
|
||||
if reader, ok := sender.(interface {
|
||||
MarkChatRead(context.Context, string, []map[string]any) error
|
||||
}); ok {
|
||||
// err 保存平台已读上报失败,失败不影响本地状态已落库。
|
||||
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, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
// chatWebSocket 负责聊天WebSocket相关处理。
|
||||
// resolveChatReadMessageIDs 将旧版关联标识交给应用服务解析,并移除无效或重复的已读项。
|
||||
func (s *Server) resolveChatReadMessageIDs(ctx context.Context, accountID, chatID string, messageIDs []map[string]any) []map[string]any {
|
||||
// resolved 保存可安全提交给平台的去重消息标识列表。
|
||||
resolved := make([]map[string]any, 0, len(messageIDs))
|
||||
// seen 保存已加入结果的平台 PNM 标识,避免重复上报。
|
||||
seen := make(map[string]struct{}, len(messageIDs))
|
||||
// item 是当前待转换的已读消息参数。
|
||||
for _, item := range messageIDs {
|
||||
// rawID 保存请求携带的原始消息标识。
|
||||
rawID, ok := item["messageId"].(string)
|
||||
if !ok || strings.TrimSpace(rawID) == "" {
|
||||
continue
|
||||
}
|
||||
// id 保存应用层解析后的平台消息标识。
|
||||
id := s.chatApplication().ResolveReadMessageID(ctx, accountID, chatID, rawID)
|
||||
if !strings.HasSuffix(id, ".PNM") {
|
||||
slog.Warn("未找到旧聊天消息对应的 PNM,跳过已读上报", "account", accountID, "chat_id", chatID, "message_id", rawID)
|
||||
continue
|
||||
}
|
||||
// exists 表示该平台消息标识是否已经加入本次上报请求。
|
||||
if _, exists := seen[id]; exists {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
// copyItem 保存保留其他平台参数、只替换消息标识的请求副本。
|
||||
copyItem := make(map[string]any, len(item)+1)
|
||||
// key、value 保存当前平台参数名及其原始值。
|
||||
for key, value := range item {
|
||||
copyItem[key] = value
|
||||
}
|
||||
copyItem["messageId"] = id
|
||||
resolved = append(resolved, copyItem)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
// findChatPlatformMessageID 保留既有包内测试入口,实际解析由聊天应用服务拥有。
|
||||
func findChatPlatformMessageID(value any, chatID, legacyID string) string {
|
||||
return chatapp.FindPlatformMessageID(value, chatID, legacyID)
|
||||
}
|
||||
|
||||
// chatWebSocket 将应用层聊天事件转发到当前认证用户的 WebSocket 连接。
|
||||
func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 保存sess,供当前处理流程使用
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
|
||||
@@ -111,7 +111,6 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
selectedLocation = &location
|
||||
}
|
||||
// outcome、callErr 保存outcome、callErr,供当前处理流程使用
|
||||
// applicationLocation 是 HTTP DTO 转换后的应用发货地模型。
|
||||
var applicationLocation *itemapp.Location
|
||||
if selectedLocation != nil {
|
||||
@@ -154,8 +153,6 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusConflict, callErr.Error())
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusBadGateway, callErr.Error())
|
||||
return
|
||||
}
|
||||
if res == nil || strings.TrimSpace(res.ItemID) == "" {
|
||||
writeErrCode(w, http.StatusBadGateway, "publish_result_missing_item_id", "平台返回发布成功,但缺少商品 ID,无法确认发布结果", "")
|
||||
|
||||
@@ -84,7 +84,7 @@ type itemDependencyFactory interface {
|
||||
// NewItemBatchPublishPort 创建批量远端发布端口。
|
||||
NewItemBatchPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error), adapter.ReadPublishImageFile, adapter.DownloadPublishImageURL) *adapter.ItemBatchPublishPort
|
||||
// NewItemPublishPort 创建单商品发布端口。
|
||||
NewItemPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error)) *adapter.ItemPublishPort
|
||||
NewItemPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error) bool) *adapter.ItemPublishPort
|
||||
// NewItemPublishRepository 创建单商品发布结果仓储。
|
||||
NewItemPublishRepository() *adapter.ItemPublishRepository
|
||||
// NewItemCatalogRepository 创建商品目录仓储。
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
import{r as n,j as e,b as ie,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,p as ae,a as ce,d as Pe}from"./index-CFzx5gQT.js";import{c as Le,o as ke}from"./contract-COFcZjyb.js";import{X as de,n as ze,L as J,o as Ge,p as Ie,q as Te,r as $e,s as te,t as De,K as We,u as Ve,v as Je,e as Ke,w as ue,f as He,U as Ee,x as Xe,k as _e,Q as ve,R as Ye,y as Ze,z as Fe,F as Ne,H as es}from"./icons-vendor-CvzvbbIV.js";const ss=(s,t)=>{const r=s.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",t),a.toString()}catch{return r}},ts=async s=>{const t=await X("/api/v1/accounts/details",void 0,s),r=Le(t,["data","accounts","details"]),a=Date.now().toString();return r.map(l=>({id:l.id,cookie_configured:l.has_cookie===!0,enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password_configured:void 0,show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:ss(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},as=async s=>{const t=await X("/api/v1/accounts/runtime-status",void 0,s);return ke(t,["statuses","data","result"])||{}},rs=async s=>ce("/api/v1/qr-login/generate",void 0,{...s,timeoutMs:(s==null?void 0:s.timeoutMs)??13e4}),ns=async(s,t)=>X(`/api/v1/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),ls=async(s,t)=>ce(`/api/v1/qr-login/complete-verification/${s}`,{target_account_id:t||""}),os=async(s,t)=>ae(`/api/v1/accounts/${s}/status`,{enabled:t}),is=async s=>Pe(`/api/v1/accounts/${s}`),cs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/pause-duration`,{pause_duration:t},r),ds=async(s,t,r)=>ae(`/api/v1/accounts/${s}/settings`,t,r),us=async(s,t)=>X(`/api/v1/accounts/${s}/long-login`,void 0,t),xs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/long-login`,{enabled:t},r),ms=async(s,t)=>ce("/api/v1/password-login",s,t),bs=async(s,t)=>X(`/api/v1/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),hs=async(s,t)=>Pe(`/api/v1/password-login/cancel/${s}`,void 0,t),gs=async s=>ce(`/api/v1/accounts/${s}/refresh-profile`,{}),ps=async s=>{const t=await X("/api/v1/settings/ai-reply",void 0,s);return ke(t,["settings","data","result"])||{}},fs=async(s,t)=>X(`/api/v1/settings/ai-reply/${s}`,void 0,t),ys=async(s,t,r)=>{const a={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return ae(`/api/v1/settings/ai-reply/${s}`,a,r)},js=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ws=async s=>{const t=await X("/api/v1/notifications/channels",void 0,s);return{success:!0,data:Le(t,["data","channels","items"]).map(a=>{let l;try{l=typeof a.config=="string"?JSON.parse(a.config):a.config}catch{l={}}const c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:l,event_types:js(a.event_types),enabled:a.enabled,created_at:a.created_at,updated_at:a.updated_at}})}},_s=async(s,t)=>{const r=await X(`/api/v1/notifications/accounts/${s}/bindings`,void 0,t),a=ke(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},Ce=async(s,t)=>X(`/api/v1/account-tasks/${s}`,void 0,t),Se=async(s,t,r)=>ae(`/api/v1/account-tasks/${s}`,t,r),vs=async(s,t,r)=>ce(`/api/v1/account-tasks/${s}/run`,{task_type:t},{timeoutMs:12e4,...r}),Re=s=>({account_id:s.id,auto_rate_enabled:s.auto_rate_enabled===!0,rate_content:s.rate_content||"不错的买家,交易愉快",auto_polish_enabled:s.auto_polish_enabled===!0,polish_time:s.polish_time||"03:00",last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}),Y=(s,t,r)=>s===t&&!r.aborted,je=(s,t)=>s instanceof Error?s.message:t,we=s=>s instanceof Error&&s.message==="请求已取消",Ae=(s,t)=>!s&&t==="",Ns=({account:s,onSaved:t})=>{const[r,a]=n.useState(()=>Re(s)),[l,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var v;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;return L.current=j,a(Re(s)),A(null),h(""),d(!1),m(""),g(null),c(!0),Ce(s.id,{signal:j.signal}).then(R=>{Y(p.current,S,j.siLine truncated
|
||||
import{r as n,j as e,b as ie,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,p as ae,a as ce,d as Pe}from"./index-hByDAHGj.js";import{c as Le,o as ke}from"./contract-COFcZjyb.js";import{X as de,n as ze,L as J,o as Ge,p as Ie,q as Te,r as $e,s as te,t as De,K as We,u as Ve,v as Je,e as Ke,w as ue,f as He,U as Ee,x as Xe,k as _e,Q as ve,R as Ye,y as Ze,z as Fe,F as Ne,H as es}from"./icons-vendor-CvzvbbIV.js";const ss=(s,t)=>{const r=s.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",t),a.toString()}catch{return r}},ts=async s=>{const t=await X("/api/v1/accounts/details",void 0,s),r=Le(t,["data","accounts","details"]),a=Date.now().toString();return r.map(l=>({id:l.id,cookie_configured:l.has_cookie===!0,enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password_configured:void 0,show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:ss(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},as=async s=>{const t=await X("/api/v1/accounts/runtime-status",void 0,s);return ke(t,["statuses","data","result"])||{}},rs=async s=>ce("/api/v1/qr-login/generate",void 0,{...s,timeoutMs:(s==null?void 0:s.timeoutMs)??13e4}),ns=async(s,t)=>X(`/api/v1/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),ls=async(s,t)=>ce(`/api/v1/qr-login/complete-verification/${s}`,{target_account_id:t||""}),os=async(s,t)=>ae(`/api/v1/accounts/${s}/status`,{enabled:t}),is=async s=>Pe(`/api/v1/accounts/${s}`),cs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/pause-duration`,{pause_duration:t},r),ds=async(s,t,r)=>ae(`/api/v1/accounts/${s}/settings`,t,r),us=async(s,t)=>X(`/api/v1/accounts/${s}/long-login`,void 0,t),xs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/long-login`,{enabled:t},r),ms=async(s,t)=>ce("/api/v1/password-login",s,t),bs=async(s,t)=>X(`/api/v1/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),hs=async(s,t)=>Pe(`/api/v1/password-login/cancel/${s}`,void 0,t),gs=async s=>ce(`/api/v1/accounts/${s}/refresh-profile`,{}),ps=async s=>{const t=await X("/api/v1/settings/ai-reply",void 0,s);return ke(t,["settings","data","result"])||{}},fs=async(s,t)=>X(`/api/v1/settings/ai-reply/${s}`,void 0,t),ys=async(s,t,r)=>{const a={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return ae(`/api/v1/settings/ai-reply/${s}`,a,r)},js=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ws=async s=>{const t=await X("/api/v1/notifications/channels",void 0,s);return{success:!0,data:Le(t,["data","channels","items"]).map(a=>{let l;try{l=typeof a.config=="string"?JSON.parse(a.config):a.config}catch{l={}}const c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:l,event_types:js(a.event_types),enabled:a.enabled,created_at:a.created_at,updated_at:a.updated_at}})}},_s=async(s,t)=>{const r=await X(`/api/v1/notifications/accounts/${s}/bindings`,void 0,t),a=ke(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},Ce=async(s,t)=>X(`/api/v1/account-tasks/${s}`,void 0,t),Se=async(s,t,r)=>ae(`/api/v1/account-tasks/${s}`,t,r),vs=async(s,t,r)=>ce(`/api/v1/account-tasks/${s}/run`,{task_type:t},{timeoutMs:12e4,...r}),Re=s=>({account_id:s.id,auto_rate_enabled:s.auto_rate_enabled===!0,rate_content:s.rate_content||"不错的买家,交易愉快",auto_polish_enabled:s.auto_polish_enabled===!0,polish_time:s.polish_time||"03:00",last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}),Y=(s,t,r)=>s===t&&!r.aborted,je=(s,t)=>s instanceof Error?s.message:t,we=s=>s instanceof Error&&s.message==="请求已取消",Ae=(s,t)=>!s&&t==="",Ns=({account:s,onSaved:t})=>{const[r,a]=n.useState(()=>Re(s)),[l,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var v;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;return L.current=j,a(Re(s)),A(null),h(""),d(!1),m(""),g(null),c(!0),Ce(s.id,{signal:j.signal}).then(R=>{Y(p.current,S,j.siLine 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(He,{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:l,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:r,children:"取消"}),e.jsxs("button",{onClick:(()=>void c()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:r,children:[r?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx($e,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},Rs=(s,t)=>{if(!s||!t)return!1;const r=Date.parse(s),a=Date.parse(t);return Number.isFinite(r)&&Number.isFinite(a)&&a<r},As=(s,t)=>s.map(r=>{const a=t[r.id];return!a||Rs(r.runtime_updated_at,a.updated_at)?r:{...r,runtime_state:a.state,runtime_message:a.message||"",runtime_connected:a.connected,runtime_updated_at:a.updated_at}}),qs=s=>{if(!s.enabled||s.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(s.runtime_state){case"online":return{label:"在线",badge:"bg-green-100 text-green-700",dot:"bg-green-500"};case"starting":case"connecting":return{label:"连接中",badge:"bg-blue-100 text-blue-700",dot:"bg-blue-500"};case"reconnecting":return{label:"重连中",badge:"bg-amber-100 text-amber-700",dot:"bg-amber-500"};case"auth_expired":return{label:"登录已失效",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"verification_required":return{label:"需要验证",badge:"bg-orange-100 text-orange-700",dot:"bg-orange-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},Ps=Oe.memo(function({account:t,refreshing:r,deleting:a,onRefreshProfile:l,onReauthorize:c,onEdit:i,onAI:d,onTasks:b,onToggle:m,onDelete:f}){const h=qs(t),u=t.runtime_state==="auth_expired"||t.runtime_state==="verification_required";return e.jsx("div",{className:"ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-5 sm:gap-8",children:[e.jsxs("div",{className:"relative",children:[t.avatar_url?e.jsx("img",{src:t.avatar_url,alt:t.nickname||"账号头像",className:"w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"}):e.jsx("div",{className:"w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center",children:e.jsx(Ee,{className:"w-9 h-9"})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${h.dot}`,children:t.runtime_state==="online"&&e.jsx(te,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:t.nickname||t.remark||`账号 ${t.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${h.badge}`,children:h.label}),t.ai_enabled&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-purple-100 text-purple-700 text-xs font-bold flex items-center gap-1",children:[e.jsx(ue,{className:"w-3 h-3"})," AI"]}),t.auto_rate_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700",children:[e.jsx(Xe,{className:"h-3 w-3"})," 自动评价"]}),t.auto_polish_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700",children:[e.jsx(Ie,{className:"h-3 w-3"})," 每日擦亮"]}),t.auto_confirm&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700",children:[e.jsx(te,{className:"h-3 w-3"})," 自动确认发货"]}),t.profile_error&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1",title:t.profile_error,children:[e.jsx(_e,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between
Line truncated
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import{b as z,j as e,r as i}from"./react-vendor-C_od1ZSF.js";import{X as G,W as Z,J as D,Y as ee,L as U,N as V,C as H,_ as te,$ as W,a0 as X,a1 as ae,I as se,a2 as le,V as ne,F as re,P as oe,r as ie}from"./icons-vendor-CvzvbbIV.js";import{g as ce,p as de,d as xe,a as Y,b as pe}from"./index-CFzx5gQT.js";import{c as me}from"./contract-COFcZjyb.js";const he=({dataCards:l,downloadCardTemplate:n,...a})=>{var x;const u=s=>{var h;a.setBatchFile(((h=s.target.files)==null?void 0:h[0])||null)},m=s=>{a.setAppendContent(s.target.value)},_=s=>{a.setAppendTargetId(s.target.value)},f=()=>a.closeBatchModal(),j=()=>a.setBatchTab("create"),d=()=>a.setBatchTab("append"),A=()=>void a.handleRetryBatchCreate(),c=()=>void a.handleRetryBatchAppend(),y=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,N=s=>e.jsxs("option",{value:String(s.id),children:[s.name,"(ID: ",s.id,")"]},s.id),b=()=>void a.handleBatchCreate(),r=()=>void a.handleBatchAppend();return a.showBatchModal?z.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:f,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{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:j,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Z,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:d,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(D,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),a.batchTab==="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:n,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 transition-colors",children:[e.jsx(ee,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 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 cursor-pointer transition-colors",children:[e.jsx(D,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=a.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(s=>!s.success).map(s=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",s.row_no," 行「",s.name,"」:",s.error]},s.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:a.appendTargetId,onChange:_,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:l.map(N)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{vaLine truncated
|
||||
import{b as z,j as e,r as i}from"./react-vendor-C_od1ZSF.js";import{X as G,W as Z,J as D,Y as ee,L as U,N as V,C as H,_ as te,$ as W,a0 as X,a1 as ae,I as se,a2 as le,V as ne,F as re,P as oe,r as ie}from"./icons-vendor-CvzvbbIV.js";import{g as ce,p as de,d as xe,a as Y,b as pe}from"./index-hByDAHGj.js";import{c as me}from"./contract-COFcZjyb.js";const he=({dataCards:l,downloadCardTemplate:n,...a})=>{var x;const u=s=>{var h;a.setBatchFile(((h=s.target.files)==null?void 0:h[0])||null)},m=s=>{a.setAppendContent(s.target.value)},_=s=>{a.setAppendTargetId(s.target.value)},f=()=>a.closeBatchModal(),j=()=>a.setBatchTab("create"),d=()=>a.setBatchTab("append"),A=()=>void a.handleRetryBatchCreate(),c=()=>void a.handleRetryBatchAppend(),y=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,N=s=>e.jsxs("option",{value:String(s.id),children:[s.name,"(ID: ",s.id,")"]},s.id),b=()=>void a.handleBatchCreate(),r=()=>void a.handleBatchAppend();return a.showBatchModal?z.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:f,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{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:j,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Z,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:d,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(D,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),a.batchTab==="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:n,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 transition-colors",children:[e.jsx(ee,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 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 cursor-pointer transition-colors",children:[e.jsx(D,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=a.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(s=>!s.success).map(s=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",s.row_no," 行「",s.name,"」:",s.error]},s.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:a.appendTargetId,onChange:_,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:l.map(N)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{vaLine 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.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:c,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.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:f,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:b,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(U,{className:"w-4 h-4 animate-spin"}):e.jsx(D,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:r,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||l.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(U,{className:"w-4 h-4 animate-spin"}):e.jsx(V,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ue=({type:l})=>{switch(l){case"text":return e.jsx(X,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(W,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(te,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(H,{className:"w-5 h-5 text-gray-500"})}},be=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},K=l=>({...l,api_config:l.api_config?JSON.stringify(l.api_config):""}),ge=async l=>{const n=await ce("/api/v1/cards",void 0,l);return me(n,["cards","data","items"]).map(be)},ye=async l=>Y("/api/v1/cards",K(l)),J=async(l,n)=>de(`/api/v1/cards/${l}`,K(n)),fe=async l=>xe(`/api/v1/cards/${l}`),je=async(l,n)=>{const a=new FormData;return a.append("file",l),pe("/api/v1/cards/batch",a,n)},Ne=async(l,n,a)=>Y(`/api/v1/cards/${l}/append-data`,{content:n},a),ve=(l,n,a)=>{const u=a.trim().toLocaleLowerCase();return l.filter(m=>(!n||m.type===n)&&(!u||m.name.toLocaleLowerCase().includes(u)))},Q=l=>l.split(`
|
||||
`).map(n=>n.trim()).filter(Boolean),we=(l,n,a)=>!!(l&&Q(n).length>0&&!a),F=(l,n,a,u)=>l===n&&a===u,Ce=()=>{const[l,n]=i.useState([]),[a,u]=i.useState(!0),m=i.useRef(0),_=i.useRef(null),f=i.useCallback(async()=>{var A;const j=++m.current;(A=_.current)==null||A.abort();const d=new AbortController;_.current=d,u(!0);try{const c=await ge({signal:d.signal});if(j!==m.current)return;n(c)}catch(c){j===m.current&&!d.signal.aborted&&console.error("加载卡密库存失败:",c)}finally{j===m.current&&u(!1)}},[]);return i.useEffect(()=>(f(),()=>{var d;m.current+=1,(d=_.current)==null||d.abort()}),[f]),{cards:l,setCards:n,loading:a,loadCards:f}},_e=l=>{const n=l.dataCards,a=l.loadCards,[u,m]=i.useState(!1),[_,f]=i.useState("create"),[j,d]=i.useState(null),[A,c]=i.useState(null),[y,N]=i.useState(!1),[b,r]=i.useState(""),[x,s]=i.useState(""),[h,E]=i.useState(null),[M,R]=i.useState(""),v=i.useRef(0),T=i.useRef(null),P=i.useRef("");i.useEffect(()=>(()=>{var p;v.current+=1,(p=T.current)==null||p.abort()}),[]);const $=i.useMemo(()=>Q(x),[x]),o=i.useCallback(()=>{var p;f("create"),d(null),c(null),r((p=n[0])!=null&&p.id?String(n[0].id):""),s(""),E(null),R(""),m(!0)},[n]),t=i.useCallback(()=>{var p;v.current+=1,(p=T.current)==null||p.abort(),N(!1),m(!1)},[]),g=i.useCallback(async()=>{var w;if(!j||y)return;const p=++v.current;(w=T.current)==null||w.abort();const B=new AbortController;T.current=B,N(!0),c(null);try{const I=await je(j,{signal:B.signal});if(!F(p,v.current,"",""))return;c(I),I.created>0&&await a()}catch(I){if(!F(p,v.current,"",""))return;c({error:(I==null?void 0:I.message)||"上传失败"})}finally{F(p,v.current,"","")&&N(!1)}},[y,j,a]),k=i.useCallback(async()=>{var I;if(!we(b,x,y))return;const p=b,B=++v.current;P.current=p,(I=T.current)==null||I.abort();const w=new AbortController;T.current=w,N(!0),E(null),R("");try{const O=await Ne(p,x,{signal:w.signal});if(!F(B,v.current,p,b))return;E({added:O.added}),s(""),await a()}catch(O){if(!F(B,v.current,p,b))return;R((O==null?void 0:O.message)||"追加失败")}finally{F(B,v.current,p,b)&&N(!1)}},[x,b,y,a]),S=i.useCallback(async()=>{await g()},[g]),C=i.useCallback(async()=>{P.current&&b!==P.current||await k()},[b,k]);return{showBatchModal:u,setShowBatchModal:m,batchTab:_,setBatchTab:f,batchFile:j,setBatchFile:d,batchResult:A,batchBusy:y,appendTargetId:b,setAppendTargetId:r,appendContent:x,setAppendContent:s,appendResult:h,appendError:M,appendPreview:$,openBatchModal:o,closeBatchModal:t,handleBatchCreate:g,handleBatchAppend:k,handleRetryBatchCreate:S,handleRetryBatchAppend:C}},q=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),L=(l,n)=>l instanceof Error?l.message:n,ke=({cards:l,loadCards:n})=>{const[a,u]=i.useState(!1),[m,_]=i.useState(!1),[f,j]=i.useState(null),[d,A]=i.useState({}),[c,y]=i.useState(q),[N,b]=i.useState(""),[r,x]=i.useState(""),s=i.useMemo(()=>l.filter(o=>o.type==="data"),[l]),h=i.useMemo(()=>ve(l,N,r),[l,r,N]),E=i.useCallback(o=>{var t,g,k,S,C;j(o),A({id:o.id,name:o.name||"",type:o.type||"text",api_url:((t=o.api_config)==null?void 0:t.url)||"",api_method:((g=o.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=o.api_config)==null?void 0:k.timeout)||10,api_headers:((S=o.api_config)==null?void 0:S.headers)||"",api_params:((C=o.api_config)==null?void 0:C.params)||"",text_content:o.text_content||"",data_content:o.data_content||"",image_url:o.image_url||"",delay_seconds:o.delay_seconds||0,description:o.description||"",enabled:o.enabled}),u(!0)},[]),M=i.useCallback(async()=>{var o,t,g,k,S,C,p,B;if(f){if(!((o=d.name)!=null&&o.trim())){alert("请输入卡密名称");return}if(!d.type){alert("请选择卡密类型");return}try{const w={name:d.name.trim(),type:d.type,description:(t=d.description)==null?void 0:t.trim(),delay_seconds:d.delay_seconds||0,enabled:d.enabled??!0};d.type==="api"?w.api_config={url:((g=d.api_url)==null?void 0:g.trim())||"",method:d.api_method||"GET",timeout:d.api_timeout||10,headers:((k=d.api_headers)==null?void 0:k.trim())||void 0,params:((S=d.api_params)==null?void 0:S.trim())||void 0}:d.type==="text"?w.text_content=((C=d.text_content)==null?void 0:C.trim())||"":d.type==="data"?w.data_content=((p=d.data_content)==null?void 0:p.trim())||"":d.type==="image"&&(w.image_url=((B=d.image_url)==null?void 0:B.trim())||""),await J(f.id,w),u(!1),await n()}catch(w){console.error("更新卡密失败:",w),alert(L(w,"更新失败,请重试"))}}},[d,n,f]),R=i.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await fe(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(L(t,"删除失败,请重试"))}},[n]),v=i.useCallback(async()=>{if(!c.name.trim()){alert("请输入卡密名称");return}if(!c.content.trim()){alert(c.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const o={name:c.name.trim(),type:c.type,description:c.description.trim(),enabled:c.enabled,delay_seconds:c.delay_seconds};c.type==="text"&&(
Line truncated
|
||||
@@ -1 +0,0 @@
|
||||
import{j as e,c as $0,r as i}from"./react-vendor-C_od1ZSF.js";import{g as b0,a as F0,b as ee}from"./index-CFzx5gQT.js";import{o as J0}from"./contract-COFcZjyb.js";import{L as r0,ak as te,al as se,M as L0,I as ae,R as ie,ad as I0,k as ne,am as re,s as ce,an as le,ao as oe,ah as pe}from"./icons-vendor-CvzvbbIV.js";const B0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp
Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{j as e,c as ee,r as i}from"./react-vendor-C_od1ZSF.js";import{g as b0,a as J0,b as te}from"./index-hByDAHGj.js";import{o as B0}from"./contract-COFcZjyb.js";import{L as r0,ak as se,al as ae,M as L0,I as ie,R as ne,ad as I0,k as re,am as ce,s as le,an as oe,ao as pe,ah as me}from"./icons-vendor-CvzvbbIV.js";const Q0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp
Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{r as c,j as e}from"./react-vendor-C_od1ZSF.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{g as q}from"./index-CFzx5gQT.js";import{c as de,o as ge}from"./contract-COFcZjyb.js";import{j as xe,k as he,l as te,D as pe,c as be,P as fe,m as se,E as ye,T as je}from"./icons-vendor-CvzvbbIV.js";import{R as E,B as ve,X as ae,Y as re,T as F,a as Ne,C as U,A as we,b as _e,c as ke,P as ne,d as le,L as De}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},Ce=t=>{const a={};return t.forEach(s=>{a[s.item_id]=s.item_title||s.item_id}),a},$e=t=>{var a;return((a=t.daily_stats)==null?void 0:a.map(s=>({name:s.date.slice(5),amount:s.amount,orders:s.order_count,avgAmount:s.order_count>0?(s.amount/s.order_count).toFixed(2):0})))||[]},Re=(t,a)=>(t.item_stats||[]).map(s=>{const l=a[s.item_id]||s.item_id;return{name:l.length>12?`${l.substring(0,12)}...`:l,sales:s.order_count}}).sort((s,l)=>l.sales-s.sales).slice(0,10),Le=(t,a,s)=>{const l=t.revenue_stats.total_orders||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>10?`${o.substring(0,10)}...`:o,value:n.order_count,percent:l>0?n.order_count/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,6).map((n,o)=>({...n,color:s[o%s.length]}))},Ae=(t,a,s)=>{const l=t.revenue_stats.total_amount||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>12?`${o.substring(0,12)}...`:o,value:n.total_amount,orderCount:n.order_count,percentage:l>0?n.total_amount/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,5).map((n,o)=>({...n,color:s[o%s.length],percentage:n.percentage.toFixed(1)}))},Oe=(t,a)=>{if(!t||!a)return null;const s=t.revenue_stats.total_amount,l=a.revenue_stats.total_amount;if(l===0)return s>0?"+100%":"0%";const n=(s-l)/l*100;return`${n>=0?"+":""}${n.toFixed(1)}%`},Te=t=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[t.range]||"所选范围",ze=t=>Math.max(...t.map(a=>a.sales),1),P=(t,a,s)=>t===a&&!s.aborted,oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Pe=async t=>q("/api/v1/analytics/dashboard",void 0,t),We=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return de(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Ee=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=ge(s,["data","result"])||{},o=de(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.status||b.order_status),order_status:oe(b.order_status),quantity:Number(b.quantity||1)}));return{orders:o,total:Number(l.total??o.length),truncated:l.truncated===!0}},ce=t=>t instanceof Error&&t.message==="请求已取消",G=(t,a)=>t instanceof Error?t.message:a,Fe=t=>{const{range:a,customStartDate:s,customEndDate:l,customRangeVersion:n}=t,[o,b]=c.useState(null),[_,I]=c.useState(null),[K,v]=c.useState({overview:"idle",range:"idle",error:""}),[d,T]=c.useState(0),R=c.useRef(0),S=c.useRef(0),L=c.useMemo(()=>({range:a,customStartDate:s,customEndDate:l}),[l,s,a]),D=c.useCallback(()=>T(u=>u+1),[]);c.useEffect(()=>{const u=++S.current,h=new AbortController;return v(m=>({...m,overview:"loading",error:""})),Promise.all([Pe({signal:h.signal}),We(void 0,{signal:h.signal})]).then(([m,g])=>{P(S.current,u,h.signal)&&(b({stats:m,items:g,itemNames:Ce(g)}),v(p=>({...p,overview:"success"})))}).catch(m=>{!P(S.current,u,h.signal)||ce(m)||v(g=>({...g,overview:"error",error:G(m,"概览加载失败")}))}),(()=>h.abort())},[d]),c.useEffect(()=>{let u;try{u=ue(a,new Date,s,l)}catch(p){v(w=>({...w,range:"error",error:G(p,"日期范围无效")}));return}const h=Se(u),m=++R.current,g=new AbortController;return v(p=>({...p,range:"loading",error:""})),Promise.all([ie({start_date:u.startDate,end_date:u.endDate},{signLine truncated
|
||||
import{r as c,j as e}from"./react-vendor-C_od1ZSF.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{g as q}from"./index-hByDAHGj.js";import{c as de,o as ge}from"./contract-COFcZjyb.js";import{j as xe,k as he,l as te,D as pe,c as be,P as fe,m as se,E as ye,T as je}from"./icons-vendor-CvzvbbIV.js";import{R as E,B as ve,X as ae,Y as re,T as F,a as Ne,C as U,A as we,b as _e,c as ke,P as ne,d as le,L as De}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},Ce=t=>{const a={};return t.forEach(s=>{a[s.item_id]=s.item_title||s.item_id}),a},$e=t=>{var a;return((a=t.daily_stats)==null?void 0:a.map(s=>({name:s.date.slice(5),amount:s.amount,orders:s.order_count,avgAmount:s.order_count>0?(s.amount/s.order_count).toFixed(2):0})))||[]},Re=(t,a)=>(t.item_stats||[]).map(s=>{const l=a[s.item_id]||s.item_id;return{name:l.length>12?`${l.substring(0,12)}...`:l,sales:s.order_count}}).sort((s,l)=>l.sales-s.sales).slice(0,10),Le=(t,a,s)=>{const l=t.revenue_stats.total_orders||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>10?`${o.substring(0,10)}...`:o,value:n.order_count,percent:l>0?n.order_count/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,6).map((n,o)=>({...n,color:s[o%s.length]}))},Ae=(t,a,s)=>{const l=t.revenue_stats.total_amount||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>12?`${o.substring(0,12)}...`:o,value:n.total_amount,orderCount:n.order_count,percentage:l>0?n.total_amount/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,5).map((n,o)=>({...n,color:s[o%s.length],percentage:n.percentage.toFixed(1)}))},Oe=(t,a)=>{if(!t||!a)return null;const s=t.revenue_stats.total_amount,l=a.revenue_stats.total_amount;if(l===0)return s>0?"+100%":"0%";const n=(s-l)/l*100;return`${n>=0?"+":""}${n.toFixed(1)}%`},Te=t=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[t.range]||"所选范围",ze=t=>Math.max(...t.map(a=>a.sales),1),P=(t,a,s)=>t===a&&!s.aborted,oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Pe=async t=>q("/api/v1/analytics/dashboard",void 0,t),We=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return de(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Ee=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=ge(s,["data","result"])||{},o=de(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.status||b.order_status),order_status:oe(b.order_status),quantity:Number(b.quantity||1)}));return{orders:o,total:Number(l.total??o.length),truncated:l.truncated===!0}},ce=t=>t instanceof Error&&t.message==="请求已取消",G=(t,a)=>t instanceof Error?t.message:a,Fe=t=>{const{range:a,customStartDate:s,customEndDate:l,customRangeVersion:n}=t,[o,b]=c.useState(null),[_,I]=c.useState(null),[K,v]=c.useState({overview:"idle",range:"idle",error:""}),[d,T]=c.useState(0),R=c.useRef(0),S=c.useRef(0),L=c.useMemo(()=>({range:a,customStartDate:s,customEndDate:l}),[l,s,a]),D=c.useCallback(()=>T(u=>u+1),[]);c.useEffect(()=>{const u=++S.current,h=new AbortController;return v(m=>({...m,overview:"loading",error:""})),Promise.all([Pe({signal:h.signal}),We(void 0,{signal:h.signal})]).then(([m,g])=>{P(S.current,u,h.signal)&&(b({stats:m,items:g,itemNames:Ce(g)}),v(p=>({...p,overview:"success"})))}).catch(m=>{!P(S.current,u,h.signal)||ce(m)||v(g=>({...g,overview:"error",error:G(m,"概览加载失败")}))}),(()=>h.abort())},[d]),c.useEffect(()=>{let u;try{u=ue(a,new Date,s,l)}catch(p){v(w=>({...w,range:"error",error:G(p,"日期范围无效")}));return}const h=Se(u),m=++R.current,g=new AbortController;return v(p=>({...p,range:"loading",error:""})),Promise.all([ie({start_date:u.startDate,end_date:u.endDate},{signLine truncated
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
import{r as l,j as e,b as ge}from"./react-vendor-C_od1ZSF.js";import{g as de,a as te,b as Ge,d as Ve,p as ot}from"./index-CFzx5gQT.js";import{c as We}from"./contract-COFcZjyb.js";import{a3 as xt,U as Ee,R as we,N as Re,a4 as _e,a5 as be,V as mt,F as ht,B as ut,a6 as $e,a7 as pt,a8 as gt,A as bt,d as yt,X as re,r as ft,a9 as De,I as qe}from"./icons-vendor-CvzvbbIV.js";const Ue="ydisks-amap-js-api",jt="c9b68d4ce9a2a97f22a4a439404488ca";let ce=null;const Nt=()=>jt,vt=()=>window.AMap?Promise.resolve(window.AMap):ce||(ce=new Promise((s,a)=>{const x=document.getElementById(Ue),o=x||document.createElement("script"),d=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(P)},g=()=>{window.AMap?(d(),s(window.AMap)):(d(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},P=window.setTimeout(()=>{d(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=g,o.id=Ue,o.async=!0,o.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Nt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,o.onerror=()=>{d(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},x||document.head.appendChild(o)}).catch(s=>{throw ce=null,s}),ce),ye=s=>Number.isFinite(s)&&s!==0,wt=s=>{var d,g;const a=Number((d=s.location)==null?void 0:d.lng),x=Number((g=s.location)==null?void 0:g.lat),o={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:a,latitude:x,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!o.division_id||!o.province||!o.city||!o.poi_id||!o.poi_name||!ye(a)||!ye(x)||a<-180||a>180||x<-90||x>90?null:o},_t=async(s,a)=>{if(!ye(s)||!ye(a)||s<-180||s>180||a<-90||a>90)throw new Error("经纬度无效");const x=await vt();return new Promise((o,d)=>{new x.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,a],1e3,(P,f)=>{var w;if(P!=="complete"){if(P==="no_data"){o([]);return}d(new Error("高德地图附近地址查询失败,请稍后重试"));return}const L=(((w=f==null?void 0:f.poiList)==null?void 0:w.pois)||[]).map(wt).filter(T=>T!==null);o(L)})})},kt=async s=>de("/api/v1/accounts/details",void 0,s),ze=async()=>de("/api/v1/automation-rules"),ke=s=>s===!0||s===1||s==="1",Oe=async(s,a)=>{const x=await de("/api/v1/items",void 0,a);return We(x,["items","data","results"]).map(d=>({...d,id:d.id||`${d.cookie_id}-${d.item_id}`,is_multi_spec:ke(d.is_multi_spec),is_multi_qty_ship:ke(d.is_multi_qty_ship??d.multi_quantity_delivery),multi_quantity_delivery:ke(d.multi_quantity_delivery??d.is_multi_qty_ship)}))},Ct=async s=>te("/api/v1/items/get-all-from-account",{cookie_id:s}),It=async(s,a)=>Ve(`/api/v1/items/${s}/${a}`),St=async(s,a)=>te(`/api/v1/items/${s}`,a),Pt=async s=>{const a=new FormData;a.set("cookie_id",s.cookie_id),a.set("title",s.title),a.set("description",s.description),a.set("price",s.price),a.set("original_price",s.original_price||""),a.set("quantity",String(s.quantity)),a.set("postage_mode",s.postage_mode),a.set("postage",s.postage||""),s.location&&a.set("location",JSON.stringify(s.location));for(const x of s.images)a.append("images",x);return Ge("/api/v1/items/publish",a)},Bt=async(s,a)=>te("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:a}),Ft=async s=>{const a=new FormData;return a.set("file",s.file),s.imagesZip&&a.set("images_zip",s.imagesZip),s.defaultCookieId&&a.set("default_cookie_id",s.defaultCookieId),a.set("fallback_category_id",s.fallbackCategory.catId),a.set("fallback_category_name",s.fallbackCategory.catName),a.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),a.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&a.set("location",JSON.stringify(s.location)),Ge("/api/v1/items/publish-batches/preview",a)},Lt=async s=>te("/api/v1/items/publish-batches",{preview_id:s}),ee=async s=>de(`/api/v1/items/publish-batches/${s}`),Ye=async(s=20)=>{const a=await de("/api/v1/items/publish-batches",{limit:s});return We(a,["batches","data","items"])},At=async s=>Ve(`/api/v1/items/publish-batches/${s}`),Mt=async s=>te(`/api/v1/items/publish-batches/${s}/cancel`,{}),Et=async s=>te(`/api/v1/items/publish-batches/${s}/retry-failed`,{}),Rt=async(s,a,x)=>ot(`/api/v1/items/${s}/${a}`,x),$t=s=>s.find(a=>a.status==="running"||a.status==="canceling"),Ie=s=>s==="running"||s==="canceling",Dt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),qt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!Ie(s.status)),Ut=(s,a)=>s===a,Te=s=>{switch(s){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 s||"-"}},Ke=s=>{switch(s){case"success":case"completed":retLine truncated
|
||||
import{r as l,j as e,b as ge}from"./react-vendor-C_od1ZSF.js";import{g as de,a as te,b as Ge,d as Ve,p as ot}from"./index-hByDAHGj.js";import{c as We}from"./contract-COFcZjyb.js";import{a3 as xt,U as Ee,R as we,N as Re,a4 as _e,a5 as be,V as mt,F as ht,B as ut,a6 as $e,a7 as pt,a8 as gt,A as bt,d as yt,X as re,r as ft,a9 as De,I as qe}from"./icons-vendor-CvzvbbIV.js";const Ue="ydisks-amap-js-api",jt="c9b68d4ce9a2a97f22a4a439404488ca";let ce=null;const Nt=()=>jt,vt=()=>window.AMap?Promise.resolve(window.AMap):ce||(ce=new Promise((s,a)=>{const x=document.getElementById(Ue),o=x||document.createElement("script"),d=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(P)},g=()=>{window.AMap?(d(),s(window.AMap)):(d(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},P=window.setTimeout(()=>{d(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=g,o.id=Ue,o.async=!0,o.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Nt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,o.onerror=()=>{d(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},x||document.head.appendChild(o)}).catch(s=>{throw ce=null,s}),ce),ye=s=>Number.isFinite(s)&&s!==0,wt=s=>{var d,g;const a=Number((d=s.location)==null?void 0:d.lng),x=Number((g=s.location)==null?void 0:g.lat),o={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:a,latitude:x,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!o.division_id||!o.province||!o.city||!o.poi_id||!o.poi_name||!ye(a)||!ye(x)||a<-180||a>180||x<-90||x>90?null:o},_t=async(s,a)=>{if(!ye(s)||!ye(a)||s<-180||s>180||a<-90||a>90)throw new Error("经纬度无效");const x=await vt();return new Promise((o,d)=>{new x.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,a],1e3,(P,f)=>{var w;if(P!=="complete"){if(P==="no_data"){o([]);return}d(new Error("高德地图附近地址查询失败,请稍后重试"));return}const L=(((w=f==null?void 0:f.poiList)==null?void 0:w.pois)||[]).map(wt).filter(T=>T!==null);o(L)})})},kt=async s=>de("/api/v1/accounts/details",void 0,s),ze=async()=>de("/api/v1/automation-rules"),ke=s=>s===!0||s===1||s==="1",Oe=async(s,a)=>{const x=await de("/api/v1/items",void 0,a);return We(x,["items","data","results"]).map(d=>({...d,id:d.id||`${d.cookie_id}-${d.item_id}`,is_multi_spec:ke(d.is_multi_spec),is_multi_qty_ship:ke(d.is_multi_qty_ship??d.multi_quantity_delivery),multi_quantity_delivery:ke(d.multi_quantity_delivery??d.is_multi_qty_ship)}))},Ct=async s=>te("/api/v1/items/get-all-from-account",{cookie_id:s}),It=async(s,a)=>Ve(`/api/v1/items/${s}/${a}`),St=async(s,a)=>te(`/api/v1/items/${s}`,a),Pt=async s=>{const a=new FormData;a.set("cookie_id",s.cookie_id),a.set("title",s.title),a.set("description",s.description),a.set("price",s.price),a.set("original_price",s.original_price||""),a.set("quantity",String(s.quantity)),a.set("postage_mode",s.postage_mode),a.set("postage",s.postage||""),s.location&&a.set("location",JSON.stringify(s.location));for(const x of s.images)a.append("images",x);return Ge("/api/v1/items/publish",a)},Bt=async(s,a)=>te("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:a}),Ft=async s=>{const a=new FormData;return a.set("file",s.file),s.imagesZip&&a.set("images_zip",s.imagesZip),s.defaultCookieId&&a.set("default_cookie_id",s.defaultCookieId),a.set("fallback_category_id",s.fallbackCategory.catId),a.set("fallback_category_name",s.fallbackCategory.catName),a.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),a.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&a.set("location",JSON.stringify(s.location)),Ge("/api/v1/items/publish-batches/preview",a)},Lt=async s=>te("/api/v1/items/publish-batches",{preview_id:s}),ee=async s=>de(`/api/v1/items/publish-batches/${s}`),Ye=async(s=20)=>{const a=await de("/api/v1/items/publish-batches",{limit:s});return We(a,["batches","data","items"])},At=async s=>Ve(`/api/v1/items/publish-batches/${s}`),Mt=async s=>te(`/api/v1/items/publish-batches/${s}/cancel`,{}),Et=async s=>te(`/api/v1/items/publish-batches/${s}/retry-failed`,{}),Rt=async(s,a,x)=>ot(`/api/v1/items/${s}/${a}`,x),$t=s=>s.find(a=>a.status==="running"||a.status==="canceling"),Ie=s=>s==="running"||s==="canceling",Dt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),qt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!Ie(s.status)),Ut=(s,a)=>s===a,Te=s=>{switch(s){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 s||"-"}},Ke=s=>{switch(s){case"success":case"completed":retLine truncated
|
||||
`),F=new Blob(["\uFEFF"+C],{type:"text/csv;charset=utf-8"}),xe=URL.createObjectURL(F),X=document.createElement("a");X.href=xe,X.download="批量铺货模板.csv",document.body.appendChild(X),X.click(),X.remove(),URL.revokeObjectURL(xe)},[]),S=l.useCallback(()=>{A(i=>({...i,cookie_id:s||i.cookie_id})),y(!0)},[s]),z=l.useCallback(()=>{M(i=>({...i,cookie_id:s||i.cookie_id})),c(!0)},[s]),fe=l.useCallback(async i=>{if(!(i?s:u.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");I(!0),navigator.geolocation.getCurrentPosition(async C=>{try{const F=await _t(C.coords.longitude,C.coords.latitude);if(!F.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");i?(P(F),f(F[0])):(V(F),q(F[0]))}catch(F){alert(Ce(F,"获取发货地失败"))}finally{I(!1)}},C=>{I(!1),alert(C.code===C.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},[u.cookie_id,s,f,P]);return{selectedAccount:s,setSelectedAccount:a,loading:L,publishing:T,showEditModal:J,setShowEditModal:R,showAddModal:G,setShowAddModal:y,showPublishModal:N,setShowPublishModal:c,locationLoading:_,publishLocations:$,setPublishLocations:V,publishLocation:D,setPublishLocation:q,selectedItem:B,editForm:p,setEditForm:k,addForm:m,setAddForm:A,publishForm:u,setPublishForm:M,publishImagePreviews:se,handleSync:Y,handleEdit:H,handleSaveEdit:Q,handleDelete:ae,handleAddItem:oe,handlePublishItem:r,downloadPublishTemplate:h,openAddModal:S,openPublishModal:z,locateForPublish:fe}},Tt=({phase:s})=>{const a=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:a.map(([x,o])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${s===x?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:o},x))})},Kt=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},Wt=({onConfigureDelivery:s})=>{const[a,x]=l.useState([]),[o,d]=l.useState([]),[g,P]=l.useState([]),[f,L]=l.useState(""),[w,T]=l.useState(""),K=l.useCallback(async()=>{const t=await Oe();x(t)},[]),J=l.useCallback(async()=>{d(await ze())},[]),R=zt({selectedAccount:f,loadItems:K,loadShippingRules:J}),{showBatchModal:G,setShowBatchModal:y,batchLoading:N,batchPhase:c,batchFile:_,setBatchFile:I,batchImagesZip:$,setBatchImagesZip:V,batchCategoryKeyword:D,setBatchCategoryKeyword:q,batchCategoryLoading:B,batchFallbackCategory:U,setBatchFallbackCategory:p,batchPreview:k,batchDetail:m,recentBatch:A,setRecentBatch:u,batchLocations:M,batchLocation:se,setBatchLocations:W,setBatchLocation:Y,openBatchModal:H,handleRecommendBatchCategory:Q,openRecentBatchResult:ae,handlePreviewBatch:oe,handleStartBatch:r,handleCancelBatch:h,abandonBatchPreview:S,closeBatchModal:z,handleRetryBatchFailed:fe}=R,i=Ot({selectedAccount:f,setSelectedAccount:L,setItems:x,loadItems:K,loadShippingRules:J,onConfigureDelivery:s,setBatchLocations:W,setBatchLocation:Y}),{loading:j,publishing:C,showEditModal:F,setShowEditModal:xe,showAddModal:X,setShowAddModal:je,showPublishModal:Ne,setShowPublishModal:He,locationLoading:me,publishLocations:he,setPublishLocations:Xe,publishLocation:Qe,setPublishLocation:Se,selectedItem:Pe,editForm:Z,setEditForm:ue,addForm:E,setAddForm:le,publishForm:b,setPublishForm:O,publishImagePreviews:Be,handleSync:et,handleEdit:tt,handleSaveEdit:st,handleDelete:at,handleAddItem:lt,handlePublishItem:it,downloadPublishTemplate:nt,openAddModal:rt,openPublishModal:ct,locateForPublish:Fe}=i;l.useEffect(()=>{Promise.all([kt(),Oe(),ze(),Ye(20)]).then(([t,n,v,ne])=>{P(t),x(n),d(v);const pe=ne.find(ve=>["running","canceling"].includes(ve.status))||ne.find(ve=>ve.status!=="preview");u(pe||null)}).catch(t=>console.error("加载商品配置失败:",t))},[]);const dt=t=>o.filter(n=>n.cookie_id===t.cookie_id&&n.item_id===t.item_id).length>0?o.filter(n=>n.cookie_id===t.cookie_id&&n.item_id===t.item_id):o.filter(n=>n.cookie_id===t.cookie_id&&!n.item_id),Le=l.useMemo(()=>new Map(g.map(t=>[t.id,t])),[g]),Ae=l.useMemo(()=>w?a.filter(t=>t.cookie_id===w):a,[w,a]),ie=t=>{const n=Le.get(t),v=(n==null?void 0:n.remark)||(n==null?void 0:n.nickname);return v?`${v} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Me=t=>{const n=Le.get(t);return(n==null?void 0:n.remark)||(n==null?void 0:n.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:[
Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,b as _e,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as Ne,x as K,e as W,L as I,y as ve,F as ke,s as Q,X as te,u as ae,v as ne,r as we,R as Se,N as Ce}from"./icons-vendor-CvzvbbIV.js";import{g as re,p as le,a as oe,d as Te}from"./index-CFzx5gQT.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],G=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ie=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?G(s.use_custom_smtp,!1):a}},ce=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=G(a.smtp_use_tls,!0),a.smtp_use_ssl=G(a.smtp_use_ssl,!1),a},de=s=>{const t=ie(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},B={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Ne,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",Line truncated
|
||||
import{j as e,b as _e,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as Ne,x as K,e as W,L as I,y as ve,F as ke,s as Q,X as te,u as ae,v as ne,r as we,R as Se,N as Ce}from"./icons-vendor-CvzvbbIV.js";import{g as re,p as le,a as oe,d as Te}from"./index-hByDAHGj.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],G=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ie=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?G(s.use_custom_smtp,!1):a}},ce=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=G(a.smtp_use_tls,!0),a.smtp_use_ssl=G(a.smtp_use_ssl,!1),a},de=s=>{const t=ie(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},B={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Ne,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,b as J,r as a}from"./react-vendor-C_od1ZSF.js";import{U as te,I as re,X as W,J as ne,R as H,N as ie,O as Y,m as Z,E as ce,v as oe,V as de,F as xe,h as me,g as ue,r as he}from"./icons-vendor-CvzvbbIV.js";import{g as X,b as ae,a as K,p as ge,d as pe}from"./index-CFzx5gQT.js";import{o as be,c as ye}from"./contract-COFcZjyb.js";import{f as ee}from"./dateTime-DDi7rqpW.js";const fe=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},c=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:c.map(ve)}},ve=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},Ne=s=>(s==null?void 0:s.results.filter(we))||[],we=s=>!s.success,_e=(s,t)=>s!==null&&!t,ke=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Ce=(s,t)=>s instanceof Error&&s.message?s.message:t,Se=({filter:s,onFilterChange:t,accountFilter:c,onAccountFilterChange:h,accounts:g,accountName:m,searchText:u,onSearchChange:p})=>{const b=r=>t(r.currentTarget.dataset.status||"all"),_=r=>h(r.target.value),y=r=>p(r.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:fe.map(r=>e.jsx("button",{"data-status":r.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===r.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:r.label},r.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(te,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:c,onChange:_,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),g.map(r=>e.jsx("option",{value:r.id,children:m(r.id)},r.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(re,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Ee=s=>{const t=m=>{var u;s.setImportFile(((u=m.target.files)==null?void 0:u[0])||null)},c=()=>s.closeImportModal(),h=()=>void s.handleImportOrders(),g=()=>void s.handleRetryImport();return s.showImportModal?J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:c,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:g,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResultLine truncated
|
||||
import{j as e,b as J,r as a}from"./react-vendor-C_od1ZSF.js";import{U as te,I as re,X as W,J as ne,R as H,N as ie,O as Y,m as Z,E as ce,v as oe,V as de,F as xe,h as me,g as ue,r as he}from"./icons-vendor-CvzvbbIV.js";import{g as X,b as ae,a as K,p as ge,d as pe}from"./index-hByDAHGj.js";import{o as be,c as ye}from"./contract-COFcZjyb.js";import{f as ee}from"./dateTime-DDi7rqpW.js";const fe=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},c=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:c.map(ve)}},ve=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},Ne=s=>(s==null?void 0:s.results.filter(we))||[],we=s=>!s.success,_e=(s,t)=>s!==null&&!t,ke=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Ce=(s,t)=>s instanceof Error&&s.message?s.message:t,Se=({filter:s,onFilterChange:t,accountFilter:c,onAccountFilterChange:h,accounts:g,accountName:m,searchText:u,onSearchChange:p})=>{const b=r=>t(r.currentTarget.dataset.status||"all"),_=r=>h(r.target.value),y=r=>p(r.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:fe.map(r=>e.jsx("button",{"data-status":r.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===r.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:r.label},r.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(te,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:c,onChange:_,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),g.map(r=>e.jsx("option",{value:r.id,children:m(r.id)},r.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(re,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Ee=s=>{const t=m=>{var u;s.setImportFile(((u=m.target.files)==null?void 0:u[0])||null)},c=()=>s.closeImportModal(),h=()=>void s.handleImportOrders(),g=()=>void s.handleRetryImport();return s.showImportModal?J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:c,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:g,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResultLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,r as o,b as De}from"./react-vendor-C_od1ZSF.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,x as wt,w as et,I as kt,a1 as Ct,X as ke,V as ze,F as Ce,h as St,g as Rt,a6 as At,ag as $t,r as tt,ah as Mt}from"./icons-vendor-CvzvbbIV.js";import{g as Z,p as Ge,a as fe,d as Ke}from"./index-CFzx5gQT.js";import{o as Ae,c as Ue}from"./contract-COFcZjyb.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Ft=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Dt=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ue(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSizeLine truncated
|
||||
import{j as e,r as o,b as De}from"./react-vendor-C_od1ZSF.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,x as wt,w as et,I as kt,a1 as Ct,X as ke,V as ze,F as Ce,h as St,g as Rt,a6 as At,ag as $t,r as tt,ah as Mt}from"./icons-vendor-CvzvbbIV.js";import{g as Z,p as Ge,a as fe,d as Ke}from"./index-hByDAHGj.js";import{o as Ae,c as Ue}from"./contract-COFcZjyb.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Ft=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Dt=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ue(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSizeLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-CFzx5gQT.js";import{f as ue,R as se,aa as pe,p as me,u as R,v as O,ab as he,s as ge,S as te,ac as ae,ad as ye,r as fe}from"./icons-vendor-CvzvbbIV.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),je=s=>{if("values"in s||"secrets"in s)return s;const a={},o={};for(const[d,h]of Object.entries(s))if(h!=null){if(oe.has(d)){o[d]=h===""?{action:"clear"}:{action:"replace",value:String(h)};continue}a[d]=h}return Object.keys(o).length>0?{values:a,secrets:o}:a},ve=s=>{const a={...s};for(const o of oe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},_e=async(s,a)=>le("/api/v1/session/credentials",s,a),Ne=async s=>{const a=await re("/api/v1/settings/system",void 0,s),o=a.data||a.settings||a;return ve(o)},Se=async(s,a)=>le("/api/v1/settings/system",je(s),a),ke=async(s,a="",o)=>{const d=await xe("/api/v1/settings/ai-models",{base_url:s,api_key:a},o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>re("/api/v1/session",void 0,s),Ee=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ae=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,o)=>s===a&&!o.aborted,D=s=>s instanceof Error&&s.message==="请求已取消",K=(s,a)=>s instanceof Error?s.message:a,Ie=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,a)=>({type:s,text:a}),Me=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[h,p]=r.useState(""),[S,A]=r.useState(!1),[P,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[M,x]=r.useState(""),[$,v]=r.useState(!1),[U,q]=r.useState(!1),[z,u]=r.useState(!1),[b,F]=r.useState(!1),[G,V]=r.useState(!1),[Y,_]=r.useState(!1),[L,y]=r.useState(null),[t,X]=r.useState(()=>Ie()),[ce,J]=r.useState("idle"),Z=r.useRef(null),ee=r.useRef(null),m=r.useRef(0),W=r.useRef(null);ee.current=s;const E=r.useCallback(()=>{var c;(c=W.current)==null||c.abort();const n=new AbortController;return W.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),B=r.useCallback(async(n,c=!1,l)=>{const i=n||ee.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await ke(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Q=>Q&&{...Q,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||D(N))return;w([]),v(!1),x(K(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),H=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),J("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{f(m.current,c,n.signal)&&(a(l),i.username&&X(g=>({...g,new_username:i.username||""})),B(l,!1,n.signal),J("success"))}).catch(l=>{!f(m.current,c,n.signal)||D(l)||(a(null),p(K(l,"加载配置失败")),J("error"))}).finally(()=>{f(m.current,c,n.signal)&&d(!1)})},[E,B]);r.useEffect(()=>(H(),(()=>{var n;return(n=W.current)==null?void 0:n.abort()})),[H]),r.useEffect(()=>{const n=c=>{var l;(l=Z.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Se(Ee(s),{signal:n.signal}),!f(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(m.current,c,n.signal)||D(l))return;k(K(l,"保存配置失败"))}finally{f(m.current,c,n.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async n=>{n.preventDefault(),y(null);const c=Ae(t);if(c){y(T("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(m.current,i,l.signal))return;if(!g.success){y(T("error",g.message||"登录凭据更新失败"));return}y(T("success",g.message||"登录凭据已更新")),window.setTimeout(()=>windLine truncated
|
||||
import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-hByDAHGj.js";import{f as ue,R as se,aa as pe,p as me,u as R,v as O,ab as he,s as ge,S as te,ac as ae,ad as ye,r as fe}from"./icons-vendor-CvzvbbIV.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),je=s=>{if("values"in s||"secrets"in s)return s;const a={},o={};for(const[d,h]of Object.entries(s))if(h!=null){if(oe.has(d)){o[d]=h===""?{action:"clear"}:{action:"replace",value:String(h)};continue}a[d]=h}return Object.keys(o).length>0?{values:a,secrets:o}:a},ve=s=>{const a={...s};for(const o of oe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},_e=async(s,a)=>le("/api/v1/session/credentials",s,a),Ne=async s=>{const a=await re("/api/v1/settings/system",void 0,s),o=a.data||a.settings||a;return ve(o)},Se=async(s,a)=>le("/api/v1/settings/system",je(s),a),ke=async(s,a="",o)=>{const d=await xe("/api/v1/settings/ai-models",{base_url:s,api_key:a},o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>re("/api/v1/session",void 0,s),Ee=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ae=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,o)=>s===a&&!o.aborted,D=s=>s instanceof Error&&s.message==="请求已取消",K=(s,a)=>s instanceof Error?s.message:a,Ie=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,a)=>({type:s,text:a}),Me=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[h,p]=r.useState(""),[S,A]=r.useState(!1),[P,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[M,x]=r.useState(""),[$,v]=r.useState(!1),[U,q]=r.useState(!1),[z,u]=r.useState(!1),[b,F]=r.useState(!1),[G,V]=r.useState(!1),[Y,_]=r.useState(!1),[L,y]=r.useState(null),[t,X]=r.useState(()=>Ie()),[ce,J]=r.useState("idle"),Z=r.useRef(null),ee=r.useRef(null),m=r.useRef(0),W=r.useRef(null);ee.current=s;const E=r.useCallback(()=>{var c;(c=W.current)==null||c.abort();const n=new AbortController;return W.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),B=r.useCallback(async(n,c=!1,l)=>{const i=n||ee.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await ke(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Q=>Q&&{...Q,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||D(N))return;w([]),v(!1),x(K(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),H=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),J("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{f(m.current,c,n.signal)&&(a(l),i.username&&X(g=>({...g,new_username:i.username||""})),B(l,!1,n.signal),J("success"))}).catch(l=>{!f(m.current,c,n.signal)||D(l)||(a(null),p(K(l,"加载配置失败")),J("error"))}).finally(()=>{f(m.current,c,n.signal)&&d(!1)})},[E,B]);r.useEffect(()=>(H(),(()=>{var n;return(n=W.current)==null?void 0:n.abort()})),[H]),r.useEffect(()=>{const n=c=>{var l;(l=Z.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Se(Ee(s),{signal:n.signal}),!f(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(m.current,c,n.signal)||D(l))return;k(K(l,"保存配置失败"))}finally{f(m.current,c,n.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async n=>{n.preventDefault(),y(null);const c=Ae(t);if(c){y(T("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(m.current,i,l.signal))return;if(!g.success){y(T("error",g.message||"登录凭据更新失败"));return}y(T("success",g.message||"登录凭据已更新")),window.setTimeout(()=>windLine truncated
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-RK26q9J7.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/contract-COFcZjyb.js","assets/icons-vendor-CvzvbbIV.js","assets/charts-vendor-BxxJOyEX.js","assets/vendor-D-Edl3pr.js","assets/AccountList-fhDk6BDY.js","assets/OrderList-CSGFKOqw.js","assets/CardList-D-c7QNTB.js","assets/ItemList-FcKS3Z5e.js","assets/Settings-fa7In0jk.js","assets/Rules-D79nNK3r.js","assets/Notifications-BJQ8JgFo.js","assets/Chat-By_xPFNH.js"])))=>i.map(i=>d[i]);
|
||||
import{c as S,j as e,r as c,d as H}from"./react-vendor-C_od1ZSF.js";import{L as T,a as P,S as J,U as Y,A as K,b as Q,c as W,M as X,C as ee,B as te,d as se,Z as ne,e as re,f as ae,G as k,g as oe,h as ie,i as le}from"./icons-vendor-CvzvbbIV.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))d(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&d(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function d(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ce extends S.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:e.jsxs("section",{className:"max-w-md text-center",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),e.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const de=3e4,ue=10*6e4;let N=!1;const I=()=>{N||typeof window>"u"||(N=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{N=!1}))},he=t=>{if(!t)return"";const n=new URLSearchParams;for(const[d,r]of Object.entries(t))r!=null&&n.set(d,String(r));const s=n.toString();return s?`?${s}`:""},L=async(t,n,s={})=>{var o;const d=he(s.params),r=`${n}${d}`,i=$(s.signal,s.timeoutMs??de);let a;try{a=await fetch(r,{method:t,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(m){throw i.signal.aborted?new Error((o=s.signal)!=null&&o.aborted?"请求已取消":"请求超时,请稍后重试"):m}finally{i.cleanup()}const h=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&I();const m=h?await a.json().catch(()=>{}):await a.text().catch(()=>{}),f=z(m,a.status);throw new Error(f)}return h?await a.json():await a.text()},D=async(t,n,s)=>L("GET",t,{params:n,...s}),_=async(t,n,s)=>L("POST",t,{body:n,...s}),Ve=async(t,n,s)=>L("PUT",t,{body:n,...s}),Ue=async(t,n,s)=>L("DELETE",t,{params:n,...s}),Ge=async(t,n,s={})=>{var h;const d=$(s.signal,s.timeoutMs??ue);let r;try{r=await fetch(t,{method:"POST",credentials:"include",signal:d.signal,body:n})}catch(o){throw d.signal.aborted?new Error((h=s.signal)!=null&&h.aborted?"请求已取消":"上传超时,请稍后重试"):o}finally{d.cleanup()}const l=(r.headers.get("content-type")||"").includes("application/json")?await r.json().catch(()=>{}):await r.text().catch(()=>{});if(!r.ok){r.status===401&&I();const o=z(l,r.status),m=new Error(o);throw m.payload=l,m}return l},$=(t,n)=>{const s=new AbortController,d=()=>s.abort(t==null?void 0:t.reason);t!=null&&t.aborted?d():t==null||t.addEventListener("abort",d,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),t==null||t.removeEventListener("abort",d)}}},me=t=>{if(typeof t!="object"||t===null)return!1;const n=t;return typeof n.code=="string"&&typeof n.message=="string"},z=(t,n)=>typeof t=="string"?t:me(t)?t.message:`请求失败: ${n}`,fe=async t=>_("/api/v1/session/login",t,{skipAuthLogout:!0}),xe=async t=>_("/api/v1/session/initialize",{password:t},{skipAuthLogout:!0}),pe=async t=>D("/api/v1/session",void 0,t),ge=async()=>_("/api/v1/session/logout",{}),M=c.createContext(void 0),be=({children:t})=>{const[n,s]=c.useState(!1),[d,r]=c.useState(!1),[i,a]=c.useState(!0),[l,h]=c.useState(!1),o=()=>{s(!1),r(!1)};c.useEffect(()=>{const b=new AbortController;let g=!0;pe({signal:b.signal}).then(p=>{if(g){if((p==null?void 0:p.initialized)===!1){h(!0),o();return}h(!1),p!=null&&p.authenticated?(s(!0),r(p.is_admin===!0)):o()}}).catch(p=>{!g||p instanceof DOMException&&p.name==="AbortError"||(h(!1),o())}).finally(()=>{g&&a(!1)});const u=()=>o();return window.addEventListener("auth:logout",u),(()=>{g=!1,b.abort(),window.removeEventListener("auth:logout",u)})},[]);const m=async b=>{const g=await fe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},f=async b=>{const g=await xe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},x=async()=>{try{await ge()}finally{o()}};return e.jsx(M.Provider,{value:{checkingAuth:i,isLoggedIn:n,isAdmin:d,needsInit:l,signIn:m,initialize:f,signOut:Line truncated
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-MmgsZAic.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/contract-COFcZjyb.js","assets/icons-vendor-CvzvbbIV.js","assets/charts-vendor-BxxJOyEX.js","assets/vendor-D-Edl3pr.js","assets/AccountList-Bb-tGjAS.js","assets/OrderList-BAnpJSM4.js","assets/CardList-D43xNKm6.js","assets/ItemList-BHJwErgP.js","assets/Settings-DUEkZoEv.js","assets/Rules-BplaKbZv.js","assets/Notifications-Dvclt-gX.js","assets/Chat-DSkOtUaB.js"])))=>i.map(i=>d[i]);
|
||||
import{c as S,j as e,r as c,d as H}from"./react-vendor-C_od1ZSF.js";import{L as T,a as P,S as J,U as Y,A as K,b as Q,c as W,M as X,C as ee,B as te,d as se,Z as ne,e as re,f as ae,G as k,g as oe,h as ie,i as le}from"./icons-vendor-CvzvbbIV.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))d(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&d(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function d(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ce extends S.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:e.jsxs("section",{className:"max-w-md text-center",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),e.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const de=3e4,ue=10*6e4;let N=!1;const I=()=>{N||typeof window>"u"||(N=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{N=!1}))},he=t=>{if(!t)return"";const n=new URLSearchParams;for(const[d,r]of Object.entries(t))r!=null&&n.set(d,String(r));const s=n.toString();return s?`?${s}`:""},L=async(t,n,s={})=>{var o;const d=he(s.params),r=`${n}${d}`,i=$(s.signal,s.timeoutMs??de);let a;try{a=await fetch(r,{method:t,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(m){throw i.signal.aborted?new Error((o=s.signal)!=null&&o.aborted?"请求已取消":"请求超时,请稍后重试"):m}finally{i.cleanup()}const h=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&I();const m=h?await a.json().catch(()=>{}):await a.text().catch(()=>{}),f=z(m,a.status);throw new Error(f)}return h?await a.json():await a.text()},D=async(t,n,s)=>L("GET",t,{params:n,...s}),_=async(t,n,s)=>L("POST",t,{body:n,...s}),Ve=async(t,n,s)=>L("PUT",t,{body:n,...s}),Ue=async(t,n,s)=>L("DELETE",t,{params:n,...s}),Ge=async(t,n,s={})=>{var h;const d=$(s.signal,s.timeoutMs??ue);let r;try{r=await fetch(t,{method:"POST",credentials:"include",signal:d.signal,body:n})}catch(o){throw d.signal.aborted?new Error((h=s.signal)!=null&&h.aborted?"请求已取消":"上传超时,请稍后重试"):o}finally{d.cleanup()}const l=(r.headers.get("content-type")||"").includes("application/json")?await r.json().catch(()=>{}):await r.text().catch(()=>{});if(!r.ok){r.status===401&&I();const o=z(l,r.status),m=new Error(o);throw m.payload=l,m}return l},$=(t,n)=>{const s=new AbortController,d=()=>s.abort(t==null?void 0:t.reason);t!=null&&t.aborted?d():t==null||t.addEventListener("abort",d,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),t==null||t.removeEventListener("abort",d)}}},me=t=>{if(typeof t!="object"||t===null)return!1;const n=t;return typeof n.code=="string"&&typeof n.message=="string"},z=(t,n)=>typeof t=="string"?t:me(t)?t.message:`请求失败: ${n}`,fe=async t=>_("/api/v1/session/login",t,{skipAuthLogout:!0}),xe=async t=>_("/api/v1/session/initialize",{password:t},{skipAuthLogout:!0}),pe=async t=>D("/api/v1/session",void 0,t),ge=async()=>_("/api/v1/session/logout",{}),M=c.createContext(void 0),be=({children:t})=>{const[n,s]=c.useState(!1),[d,r]=c.useState(!1),[i,a]=c.useState(!0),[l,h]=c.useState(!1),o=()=>{s(!1),r(!1)};c.useEffect(()=>{const b=new AbortController;let g=!0;pe({signal:b.signal}).then(p=>{if(g){if((p==null?void 0:p.initialized)===!1){h(!0),o();return}h(!1),p!=null&&p.authenticated?(s(!0),r(p.is_admin===!0)):o()}}).catch(p=>{!g||p instanceof DOMException&&p.name==="AbortError"||(h(!1),o())}).finally(()=>{g&&a(!1)});const u=()=>o();return window.addEventListener("auth:logout",u),(()=>{g=!1,b.abort(),window.removeEventListener("auth:logout",u)})},[]);const m=async b=>{const g=await fe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},f=async b=>{const g=await xe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},x=async()=>{try{await ge()}finally{o()}};return e.jsx(M.Provider,{value:{checkingAuth:i,isLoggedIn:n,isAdmin:d,needsInit:l,signIn:m,initialize:f,signOut: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-CFzx5gQT.js"></script>
|
||||
<script type="module" crossorigin src="/static/assets/index-hByDAHGj.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-CvzvbbIV.js">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-ZQ7msDu9.css">
|
||||
|
||||
@@ -904,6 +904,33 @@ func (c *Conn) SendText(ctx context.Context, myID, cid, toID, text string) error
|
||||
return c.sendChatContent(ctx, myID, cid, toID, content)
|
||||
}
|
||||
|
||||
// MarkChatRead 将当前会话的 PNM 消息 ID 上报为已读。
|
||||
// ctx 控制远端请求生命周期;cid 仅用于本地可观测日志;messageIDs 为待上报消息对象。
|
||||
// 返回值仅报告远端调用失败,平台拒绝会被记录为告警以保留既有调用兼容性。
|
||||
func (c *Conn) MarkChatRead(ctx context.Context, cid string, messageIDs []map[string]any) error {
|
||||
// ids 是剔除空值后的 PNM ID 列表,按平台 MessageStatusService 的参数格式发送。
|
||||
ids := make([]string, 0, len(messageIDs))
|
||||
// item 为调用方传入的一条待读消息对象,可能缺少平台消息 ID。
|
||||
for _, item := range messageIDs {
|
||||
// id 是当前对象中可上报的非空 PNM 消息 ID。
|
||||
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)
|
||||
// response 保存平台响应;err 表示请求或传输失败。服务只接受一个 string 列表参数。
|
||||
response, err := c.request(ctx, "/r/MessageStatus/read", map[string]any{}, []any{ids}, regResponseTimeout)
|
||||
if err == nil {
|
||||
// code 是平台业务状态码;ok 表示响应中的状态码可被规范解析。
|
||||
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