mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: windows同步mac增加发文件
This commit is contained in:
1 parent
e0e749510a
commit
49e2dab2a6
5 files changed
+188
-31
No files matched your search
@@ -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 发现问题、提出建议和持续使用它的人。
|
||||
|
||||
---
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<ChatWindowProps> = ({
|
||||
onContentFilterChange={onContentFilterChange || (() => undefined)}
|
||||
onRefresh={onRefresh}
|
||||
onTestSend={() => void handleOpenPersonalWechatSend()}
|
||||
onSendFile={isMac ? () => void handleSendFile() : undefined}
|
||||
onSendFile={() => void handleSendFile()}
|
||||
onOpenAiSettings={onCreateGroupReport || (() => undefined)}
|
||||
onOpenLocalIndexSettings={onOpenLocalIndexSettings}
|
||||
/>
|
||||
|
||||
@@ -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<PersonalWechatSenderStatus | null>(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<void> => {
|
||||
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({
|
||||
<div>
|
||||
<span className="text-[11px] font-bold tracking-normal text-primary">实验性功能</span>
|
||||
<DialogTitle className="mt-0.5 text-[19px] leading-[26px] tracking-normal">
|
||||
文字转语音
|
||||
{initialFile ? '发送文件' : '文字转语音'}
|
||||
</DialogTitle>
|
||||
</div>
|
||||
<DialogDescription className="sr-only">
|
||||
向当前微信联系人或群聊发送文字转语音。
|
||||
{initialFile
|
||||
? '向当前微信联系人或群聊发送本地文件。'
|
||||
: '向当前微信联系人或群聊发送文字转语音。'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="personal-wechat-send-device-note" role="note">
|
||||
<span aria-hidden>i</span>
|
||||
<p>
|
||||
<strong>请在其他设备确认发送结果</strong>
|
||||
语音消息请切换到手机、平板等其他设备确认是否送达。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="personal-wechat-send-target">
|
||||
<span>{isGroupChat ? '发送到群聊' : '发送给联系人'}</span>
|
||||
<strong>{displayName}</strong>
|
||||
@@ -267,13 +297,28 @@ export function PersonalWechatWindowsSendDialog({
|
||||
key={message.id}
|
||||
className={`personal-wechat-message-bubble ${message.outgoing ? 'is-outgoing' : ''}`}
|
||||
>
|
||||
<span className="personal-wechat-message-kind">语音</span>
|
||||
<span className="personal-wechat-message-kind">
|
||||
{message.type === 'voice' ? '语音' : '已发送'}
|
||||
</span>
|
||||
<span>{message.text || message.fileName}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{initialImage && status.canSendImage ? (
|
||||
{initialFile ? (
|
||||
status.canSendFile ? (
|
||||
<section className="personal-wechat-composer" aria-label="文件发送">
|
||||
<p>已选择文件:{initialFile.name}</p>
|
||||
<Button size="sm" onClick={() => void handleSendFile()} disabled={sendBusy}>
|
||||
{sendBusy ? '发送中…' : '发送文件'}
|
||||
</Button>
|
||||
</section>
|
||||
) : (
|
||||
<div className="personal-wechat-global-error" role="alert">
|
||||
当前微信发送能力不支持文件发送,请升级发送组件后重试
|
||||
</div>
|
||||
)
|
||||
) : initialImage && status.canSendImage ? (
|
||||
<section className="personal-wechat-composer" aria-label="日报图片发送">
|
||||
<p>已准备日报图片:{initialImage.name}</p>
|
||||
<ReportImagePostfixInput
|
||||
@@ -290,7 +335,7 @@ export function PersonalWechatWindowsSendDialog({
|
||||
{sendBusy ? '发送中…' : '发送日报图片'}
|
||||
</Button>
|
||||
</section>
|
||||
) : !initialImage ? (
|
||||
) : !initialImage && !initialFile ? (
|
||||
<PersonalWechatChatComposer
|
||||
status={status}
|
||||
targetId={targetId}
|
||||
|
||||
@@ -55,6 +55,7 @@ import {
|
||||
normalizeWindowsWechatPort,
|
||||
parseWindowsLoginStatus,
|
||||
parseWindowsHookResponse,
|
||||
prepareWindowsFileForSend,
|
||||
prepareWindowsImageFile,
|
||||
WindowsHookHttpError
|
||||
} from '../../src/main/services/personal-wechat-send-service'
|
||||
@@ -374,7 +375,7 @@ describe('Windows request', () => {
|
||||
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',
|
||||
|
||||
Reference in new issue
Block a user