From 49e2dab2a6fcc88082ad69a07282e8187d1ea48d Mon Sep 17 00:00:00 2001 From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:49:41 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20windows=E5=90=8C=E6=AD=A5mac=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E5=8F=91=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 - .../services/personal-wechat-send-service.ts | 94 +++++++++++++++++-- src/renderer/src/components/ChatWindow.tsx | 3 +- .../chat/PersonalWechatWindowsSendDialog.tsx | 79 ++++++++++++---- .../unit/personal-wechat-send-service.test.ts | 40 +++++++- 5 files changed, 188 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 9c69f35..21699b6 100644 --- a/README.md +++ b/README.md @@ -212,9 +212,6 @@ TraceMemo 在早期适配微信 4.x 时,曾参考 **[WeFlow](https://github.co - **[chatlog](https://github.com/sjzar/chatlog)** - 提供了数据处理方面的参考。 -- **[wechat_chatter](https://github.com/yincongcyincong/wechat_chatter)** - - 提供了发送方面的参考。 - 感谢所有开源作者,也感谢所有帮助 TraceMemo 发现问题、提出建议和持续使用它的人。 --- diff --git a/src/main/services/personal-wechat-send-service.ts b/src/main/services/personal-wechat-send-service.ts index 8c87cc3..573d202 100644 --- a/src/main/services/personal-wechat-send-service.ts +++ b/src/main/services/personal-wechat-send-service.ts @@ -291,6 +291,54 @@ export function prepareWindowsImageFile(filePath: string): { return prepareWindowsMediaFile(filePath, { prefix: 'tm-img-', fallbackExtension: '.png' }) } +/** Windows 文件名里不允许出现的字符(控制字符由后面的 ASCII 过滤统一剔除)。 */ +const WINDOWS_INVALID_FILE_NAME_CHARS = /[<>:"/\\|?*]/g +/** 单段路径上限 255,给随机后缀与扩展名留出余量。 */ +const WINDOWS_TEMP_FILE_STEM_LIMIT = 80 + +/** 发送组件只认路径 basename 当显示名,改名或非 ASCII 路径都要走副本。 */ +export function prepareWindowsFileForSend( + filePath: string, + fileName?: string +): { filePath: string; temporary: boolean } { + const normalized = String(filePath || '').trim() + const sourceName = basename(normalized) + const requestedName = basename(String(fileName || '').trim() || sourceName) + if (isAsciiPath(normalized) && requestedName === sourceName) { + return { filePath: normalized, temporary: false } + } + + const extension = extname(requestedName).toLowerCase() + const safeExtension = /^\.[a-z0-9]{1,12}$/.test(extension) ? extension : '' + const asciiStem = basename(requestedName, extname(requestedName)) + .replace(WINDOWS_INVALID_FILE_NAME_CHARS, '_') + .replace(/[^\x20-\x7e]/g, '') + .replace(/^[.\s_]+|[.\s_]+$/g, '') + .slice(0, WINDOWS_TEMP_FILE_STEM_LIMIT) + + const root = windowsImageTempRoot() + // 同名副本不覆盖:上一笔发送可能还在读文件。 + let temporaryPath = join(root, `${asciiStem || 'tm-file'}${safeExtension}`) + if (!asciiStem || existsSync(temporaryPath)) { + temporaryPath = join( + root, + `${asciiStem || 'tm-file'}-${randomBytes(4).toString('hex')}${safeExtension}` + ) + } + if (!isAsciiPath(temporaryPath)) throw new Error('Windows 文件临时路径必须只包含 ASCII 字符') + try { + copyFileSync(normalized, temporaryPath) + } catch (error) { + try { + unlinkSync(temporaryPath) + } catch { + // 半拷贝残留只做尽力清理。 + } + throw error + } + return { filePath: temporaryPath, temporary: true } +} + function prepareMacWechatImageFile( filePath: string, senderWxid: string, @@ -663,6 +711,9 @@ const WINDOWS_TEMP_IMAGE_GRACE_MS = 0 /** 视频上传在 send_message 返回后才开始,删早了接收端只能拿到空文件。 */ const WINDOWS_TEMP_VIDEO_GRACE_MS = 10 * 60 * 1000 +/** 文件副本保留窗口:`/SendMsg` 返回时微信还在读,删早了接收端拿到空文件。 */ +const WINDOWS_TEMP_FILE_GRACE_MS = 10 * 60 * 1000 + // unref: 不让清理定时器拖住进程退出 function scheduleTempFileCleanup(target: string, delayMs: number): void { const timer = setTimeout(() => { @@ -814,6 +865,7 @@ export class PersonalWechatSendService { canSendImage: true, canSendVoice: true, canSendVideo: true, + canSendFile: true, message: 'Windows 微信发送能力已连接,可以发送消息' } } catch (error) { @@ -1220,18 +1272,23 @@ export class PersonalWechatSendService { } request = { ...request, to, text } } else { - if (request.type === 'file') { - const status = await this.getWindowsStatus() - return { success: false, status, error: 'Windows 端暂不支持文件发送' } - } const filePath = String(request.filePath || '').trim() - const label = request.type === 'voice' ? '语音' : request.type === 'video' ? '视频' : '图片' + const label = + request.type === 'voice' + ? '语音' + : request.type === 'video' + ? '视频' + : request.type === 'file' + ? '文件' + : '图片' const limit = request.type === 'voice' ? MAX_VOICE_BYTES : request.type === 'video' ? MAX_VIDEO_BYTES - : MAX_IMAGE_BYTES + : request.type === 'file' + ? MAX_FILE_BYTES + : MAX_IMAGE_BYTES if (!filePath || !existsSync(filePath)) { const status = await this.getWindowsStatus() return { success: false, status, error: `请选择有效的${label}文件` } @@ -1254,6 +1311,7 @@ export class PersonalWechatSendService { let temporaryImagePath: string | undefined let temporaryVideoPath: string | undefined let temporaryVoicePath: string | undefined + let temporaryFilePath: string | undefined try { if (request.type === 'text') { const windowsRequest = buildWindowsWechatRequest(request) @@ -1290,6 +1348,20 @@ export class PersonalWechatSendService { filePath: preparedVideo.filePath }) await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 180_000) + } else if (request.type === 'file') { + const preparedFile = prepareWindowsFileForSend(request.filePath, request.fileName) + temporaryFilePath = preparedFile.temporary ? preparedFile.filePath : undefined + logSendDiagnostic('file-prepared', { + sourceBytes: safeFileSize(request.filePath), + usedTempCopy: preparedFile.temporary, + copiedBytes: safeFileSize(preparedFile.filePath) + }) + const windowsRequest = buildWindowsWechatRequest({ + ...request, + filePath: preparedFile.filePath + }) + // 文件构造 appmsg 后还要走 CDN 上传,超时阈值按视频档给。 + await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 180_000) } else if (request.type === 'voice') { const fromId = String(request.fromId || '').trim() if (!fromId) throw new Error('无法识别当前微信账号 wxid,无法发送语音') @@ -1315,7 +1387,12 @@ export class PersonalWechatSendService { } return { success: true, status: await this.getWindowsStatus() } } catch (error) { - const message = error instanceof Error ? error.message : String(error) + const raw = error instanceof Error ? error.message : String(error) + // 老版发送组件不认 type=file,只会回校验错误 → 换成可操作的文案。 + const message = + request.type === 'file' && /type must be/i.test(raw) + ? '当前微信发送组件不支持文件发送,请升级发送组件后重试' + : raw return { success: false, status: { ...(await this.getWindowsStatus()), state: 'error', error: message }, @@ -1344,6 +1421,9 @@ export class PersonalWechatSendService { if (temporaryVideoPath) { scheduleTempFileCleanup(temporaryVideoPath, WINDOWS_TEMP_VIDEO_GRACE_MS) } + if (temporaryFilePath) { + scheduleTempFileCleanup(temporaryFilePath, WINDOWS_TEMP_FILE_GRACE_MS) + } if (temporaryVoicePath) { try { unlinkSync(temporaryVoicePath) diff --git a/src/renderer/src/components/ChatWindow.tsx b/src/renderer/src/components/ChatWindow.tsx index 3b5bb88..2ce7328 100644 --- a/src/renderer/src/components/ChatWindow.tsx +++ b/src/renderer/src/components/ChatWindow.tsx @@ -9,7 +9,6 @@ import { MessageList } from './chat/MessageList' import { PersonalWechatSendDialog } from './chat/PersonalWechatSendDialog' import { mergeGroupExitEvents } from '../../../shared/group-exit-event-message' import { useGroupExitEvents } from '../hooks/useGroupExitEvents' -import { isMac } from '../utils/runtime-environment' interface ChatWindowProps { contact: Contact | null @@ -194,7 +193,7 @@ const ChatWindow: React.FC = ({ onContentFilterChange={onContentFilterChange || (() => undefined)} onRefresh={onRefresh} onTestSend={() => void handleOpenPersonalWechatSend()} - onSendFile={isMac ? () => void handleSendFile() : undefined} + onSendFile={() => void handleSendFile()} onOpenAiSettings={onCreateGroupReport || (() => undefined)} onOpenLocalIndexSettings={onOpenLocalIndexSettings} /> diff --git a/src/renderer/src/components/chat/PersonalWechatWindowsSendDialog.tsx b/src/renderer/src/components/chat/PersonalWechatWindowsSendDialog.tsx index da093ce..b6ec099 100644 --- a/src/renderer/src/components/chat/PersonalWechatWindowsSendDialog.tsx +++ b/src/renderer/src/components/chat/PersonalWechatWindowsSendDialog.tsx @@ -48,7 +48,7 @@ function statusLabel(status: PersonalWechatSenderStatus | null): string { } function statusText(value: string): string { - return value.replace(/Hook/gi, '微信发送能力').replace(/个人微信发送组件/g, '微信发送能力') + return value.replace(/个人微信发送组件/g, '微信发送能力') } function statusDescription(status: PersonalWechatSenderStatus | null): string { @@ -62,7 +62,8 @@ export function PersonalWechatWindowsSendDialog({ onClose, onOpenTextToSpeechSettings, onOpenPersonalWechatSettings, - initialImage = null + initialImage = null, + initialFile = null }: PersonalWechatSendDialogProps): React.ReactElement { const [status, setStatus] = useState(null) const [detecting, setDetecting] = useState(true) @@ -182,8 +183,43 @@ export function PersonalWechatWindowsSendDialog({ } } - const statusTone = useMemo(() => { - if (status?.state === 'online' && status.canSend) return 'ready' + const handleSendFile = async (): Promise => { + if (!initialFile || !status?.canSendFile || sendBusy) return + setSendBusy(true) + setSendError(null) + setSendSuccess(null) + try { + const response = await window.api.sendPersonalWechatMessage({ + type: 'file', + to: targetId, + isGroup: isGroupChat, + filePath: initialFile.path, + fileName: initialFile.name + } satisfies PersonalWechatSendRequest) + setStatus(response.status) + if (!response.success) { + setSendError(response.error || '文件发送失败') + return + } + setSendSuccess('文件发送成功') + setMessages((current) => [ + ...current, + { + id: `${Date.now()}-${Math.random()}`, + type: 'system', + text: initialFile.name, + fileName: initialFile.name, + outgoing: true + } + ]) + } catch (error) { + setSendError(error instanceof Error ? error.message : String(error)) + } finally { + setSendBusy(false) + } + } + + const statusTone = useMemo(() => { if (status?.state === 'online' && status.canSend) return 'ready' if (!status || status.state === 'checking' || status.state === 'starting') return 'checking' return 'blocked' }, [status]) @@ -205,22 +241,16 @@ export function PersonalWechatWindowsSendDialog({
实验性功能 - 文字转语音 + {initialFile ? '发送文件' : '文字转语音'}
- 向当前微信联系人或群聊发送文字转语音。 + {initialFile + ? '向当前微信联系人或群聊发送本地文件。' + : '向当前微信联系人或群聊发送文字转语音。'} -
- i -

- 请在其他设备确认发送结果 - 语音消息请切换到手机、平板等其他设备确认是否送达。 -

-
-
{isGroupChat ? '发送到群聊' : '发送给联系人'} {displayName} @@ -267,13 +297,28 @@ export function PersonalWechatWindowsSendDialog({ key={message.id} className={`personal-wechat-message-bubble ${message.outgoing ? 'is-outgoing' : ''}`} > - 语音 + + {message.type === 'voice' ? '语音' : '已发送'} + {message.text || message.fileName}
))} ) : null} - {initialImage && status.canSendImage ? ( + {initialFile ? ( + status.canSendFile ? ( +
+

已选择文件:{initialFile.name}

+ +
+ ) : ( +
+ 当前微信发送能力不支持文件发送,请升级发送组件后重试 +
+ ) + ) : initialImage && status.canSendImage ? (

已准备日报图片:{initialImage.name}

- ) : !initialImage ? ( + ) : !initialImage && !initialFile ? ( { expect(() => parseWindowsHookResponse('', true)).toThrow('空响应') }) - it('preserves the Windows Hook HTTP status and response body', () => { + it('preserves the Windows send HTTP status and response body', () => { const error = new WindowsHookHttpError(500, '{"ret":-9,"retmsg":"image failed"}') expect(error.message).toBe('HTTP 500: {"ret":-9,"retmsg":"image failed"}') expect(error.status).toBe(500) @@ -432,8 +433,43 @@ describe('Windows request', () => { }) }) - it('builds the unified voice request with sender wxid and duration', () => { + it('builds the unified file request with type=file', () => { expect( + buildWindowsWechatRequest({ + to: 'room@chatroom', + type: 'file', + filePath: 'C:\\Temp\\tm-report.pdf', + fileName: 'report.pdf', + isGroup: true + }) + ).toEqual({ + endpoint: '/SendMsg', + body: { toWxid: 'room@chatroom', type: 'file', msg: 'C:\\Temp\\tm-report.pdf' } + }) + }) + + it('copies non-ASCII file paths to an ASCII temporary name', () => { + const root = mkdtempSync(join(tmpdir(), 'tm-file-send-')) + const source = join(root, '季度报告.pdf') + writeFileSync(source, 'fixture-file') + const prepared = prepareWindowsFileForSend(source, '季度报告.pdf') + expect(prepared.temporary).toBe(true) + expect(prepared.filePath).toMatch(/^[\x20-\x7e]+$/) + expect(prepared.filePath.endsWith('.pdf')).toBe(true) + expect(readFileSync(prepared.filePath)).toEqual(readFileSync(source)) + if (prepared.temporary) unlinkSync(prepared.filePath) + rmSync(root, { recursive: true, force: true }) + }) + + it('keeps an ASCII file path unchanged when the name matches', () => { + const root = mkdtempSync(join(tmpdir(), 'tm-file-send-')) + const source = join(root, 'tm-report.pdf') + writeFileSync(source, 'fixture-file') + expect(prepareWindowsFileForSend(source)).toEqual({ filePath: source, temporary: false }) + rmSync(root, { recursive: true, force: true }) + }) + + it('builds the unified voice request with sender wxid and duration', () => { expect( buildWindowsWechatRequest( { to: 'wxid_fixture',