feat: 定时日报支持Windows

This commit is contained in:
电摇小子 committed 2026-09-01 11:36:15 +08:00
1 parent f65dc4ac32
commit 25b72c3d76
15 files changed
+205 -41

No files matched your search

@@ -36,7 +36,7 @@ export class PersonalWechatCapabilityService {
senderStatus,
message:
status === 'unsupported'
? '微信消息发送目前仅支持 macOS'
? '微信消息发送目前仅支持 macOS 和 Windows'
: senderStatus.message ||
(status === 'needs_binding' || status === 'unconfigured'
? '请先绑定个人微信'
@@ -1,10 +1,19 @@
import { app } from 'electron'
import { execFile, spawn, type ChildProcess } from 'child_process'
import { createHash, randomBytes, randomUUID } from 'crypto'
import { existsSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'fs'
import {
copyFileSync,
existsSync,
mkdirSync,
readFileSync,
readdirSync,
statSync,
unlinkSync,
writeFileSync
} from 'fs'
import { createConnection } from 'net'
import { homedir, tmpdir } from 'os'
import { delimiter, dirname, join, sep } from 'path'
import { delimiter, dirname, extname, join, sep } from 'path'
import ffmpegStaticPath from 'ffmpeg-static'
import { promisify } from 'util'
import type {
@@ -42,6 +51,12 @@ const WECHAT_FILES_ROOT = join(
'Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files'
)
const ASCII_PATH_PATTERN = /^[\x20-\x7e]+$/
function isAsciiPath(value: string): boolean {
return ASCII_PATH_PATTERN.test(value)
}
export function normalizeWindowsWechatPort(value: unknown): string | null {
const text = String(value ?? '').trim()
if (!/^\d{1,5}$/.test(text)) return null
@@ -591,6 +606,59 @@ async function prepareWindowsVoiceFile(filePath: string): Promise<{
}
}
function windowsImageTempRoot(): string {
const candidates = [
process.platform === 'win32' && process.env['PUBLIC']
? join(process.env['PUBLIC'], 'TraceMemo', 'temp')
: undefined,
process.platform === 'win32' && process.env['ProgramData']
? join(process.env['ProgramData'], 'TraceMemo', 'temp')
: undefined,
process.platform === 'win32' ? join('C:', 'Users', 'Public', 'TraceMemo', 'temp') : undefined,
tmpdir(),
process.env['TEMP'],
process.env['TMP']
]
for (const candidate of candidates) {
const normalized = String(candidate || '').trim()
if (!normalized || !isAsciiPath(normalized)) continue
try {
mkdirSync(normalized, { recursive: true })
return normalized
} catch {
//
}
}
throw new Error('无法创建 Windows 图片临时目录')
}
export function prepareWindowsImageFile(filePath: string): {
filePath: string
temporary: boolean
} {
const normalized = String(filePath || '').trim()
if (isAsciiPath(normalized)) return { filePath: normalized, temporary: false }
const extension = extname(normalized).toLowerCase()
const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.png'
const temporaryPath = join(
windowsImageTempRoot(),
`tm-img-${randomBytes(8).toString('hex')}${safeExtension}`
)
if (!isAsciiPath(temporaryPath)) throw new Error('Windows 图片临时路径必须只包含 ASCII 字符')
try {
copyFileSync(normalized, temporaryPath)
} catch (error) {
try {
unlinkSync(temporaryPath)
} catch {
// A partially copied file is best-effort cleanup only.
}
throw error
}
return { filePath: temporaryPath, temporary: true }
}
async function readWechatVersion(): Promise<string> {
const { stdout } = await execFileAsync('/usr/libexec/PlistBuddy', [
'-c',
@@ -736,6 +804,17 @@ async function requestWithTimeout(
type WindowsHookResponse = Record<string, unknown>
export class WindowsHookHttpError extends Error {
constructor(
readonly status: number,
readonly responseBody: string
) {
const detail = responseBody.trim()
super(detail ? `HTTP ${status}: ${detail.slice(0, 1_000)}` : `HTTP ${status}`)
this.name = 'WindowsHookHttpError'
}
}
export function parseWindowsHookResponse(
responseText: string,
requireSuccessRet = false
@@ -843,7 +922,7 @@ async function requestWindowsHook(
if (method !== 'GET') init.body = JSON.stringify(body)
const response = await requestWithTimeout(`http://${host}${endpoint}`, init, timeoutMs)
const responseText = await response.text()
if (!response.ok) throw new Error(responseText || `HTTP ${response.status}`)
if (!response.ok) throw new WindowsHookHttpError(response.status, responseText)
return parseWindowsHookResponse(responseText, method === 'POST')
}
@@ -1354,11 +1433,20 @@ export class PersonalWechatSendService {
const status = await this.getWindowsStatus()
if (!status.canSend) return { success: false, status, error: status.error || status.message }
let temporaryImagePath: string | undefined
let temporaryVoicePath: string | undefined
try {
if (request.type === 'text') {
const windowsRequest = buildWindowsWechatRequest(request)
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body)
} else if (request.type === 'image') {
const preparedImage = prepareWindowsImageFile(request.filePath)
temporaryImagePath = preparedImage.temporary ? preparedImage.filePath : undefined
const windowsRequest = buildWindowsWechatRequest({
...request,
filePath: preparedImage.filePath
})
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 60_000)
} else if (request.type === 'voice') {
const fromId = String(request.fromId || '').trim()
if (!fromId) throw new Error('无法识别当前微信账号 wxid,无法发送语音')
@@ -1391,6 +1479,13 @@ export class PersonalWechatSendService {
error: `发送失败:${message}`
}
} finally {
if (temporaryImagePath) {
try {
unlinkSync(temporaryImagePath)
} catch {
// Temporary files are best-effort cleanup only.
}
}
if (temporaryVoicePath) {
try {
unlinkSync(temporaryVoicePath)
@@ -301,14 +301,15 @@ export class ScheduledReportApiService {
private applyPlatformCapability(
capability: PersonalWechatSendCapability
): PersonalWechatSendCapability {
if ((this.deps.platform || process.platform) === 'darwin') return capability
const platform = this.deps.platform || process.platform
if (platform === 'darwin' || platform === 'win32') return capability
return {
...capability,
supported: false,
ready: false,
status: 'unsupported',
capabilities: { text: false, image: false, voice: false },
message: '微信消息发送目前仅支持 macOS'
message: '微信消息发送目前仅支持 macOS 和 Windows'
}
}
@@ -344,7 +344,7 @@ export class ScheduledReportService {
}
private creationError(capability: PersonalWechatSendCapability): string {
if (capability.status === 'unsupported') return '微信消息发送目前仅支持 macOS'
if (capability.status === 'unsupported') return '微信消息发送目前仅支持 macOS 和 Windows'
if (capability.status === 'needs_binding' || capability.status === 'unconfigured')
return '请先绑定个人微信'
if (capability.status === 'needs_verification') return '请先完成微信消息能力检测'
+7 -7
View File
@@ -39,7 +39,7 @@ import { isRelevantMessageMonitorEvent, parseWcdbMonitorEvent } from './utils/me
import { enrichQuotedMessages } from './utils/quoted-messages'
import type { SelectableReportTemplateId } from '../../shared/report-templates'
import { switchGeneratedReportTemplate } from './utils/report-template-switch'
import { runtimePlatform } from './utils/runtime-environment'
import { runtimePlatform, supportsPersonalWechatSend } from './utils/runtime-environment'
import { useToast } from './components/ui'
import { AppUpdatePrompt } from './features/app-update/AppUpdatePrompt'
import { GroupExitMonitorWorkspace } from './features/group-exit-monitor/GroupExitMonitorWorkspace'
@@ -1783,24 +1783,24 @@ function App(): React.ReactElement {
type="button"
role="tab"
aria-selected={reportSection === 'scheduled'}
aria-disabled={runtimePlatform !== 'darwin'}
className={`${reportSection === 'scheduled' ? 'active' : ''} ${runtimePlatform !== 'darwin' ? 'unsupported' : ''}`}
aria-disabled={!supportsPersonalWechatSend}
className={`${reportSection === 'scheduled' ? 'active' : ''} ${!supportsPersonalWechatSend ? 'unsupported' : ''}`}
onClick={() => {
if (runtimePlatform !== 'darwin') {
toast({ description: '定时日报目前仅支持 macOS。', duration: 3200 })
if (!supportsPersonalWechatSend) {
toast({ description: '定时日报目前仅支持 macOS 和 Windows。', duration: 3200 })
return
}
setReportSection('scheduled')
}}
>
定时日报{runtimePlatform !== 'darwin' && <small>仅 macOS</small>}
定时日报{!supportsPersonalWechatSend && <small>仅 macOS / Windows</small>}
</button>
</div>
<div className="report-workspace-body">
{reportSection === 'scheduled' ? (
<ScheduledReportsWorkspace
contacts={contacts}
platformSupported={runtimePlatform === 'darwin'}
platformSupported={supportsPersonalWechatSend}
onOpenWechatSettings={openWechatSendSettings}
onOpenModelSettings={openModelSettings}
onNotice={(message, variant) =>
@@ -115,7 +115,7 @@ export function ChatHeader({
) : (
<Tooltip>
<TooltipTrigger asChild>
<span tabIndex={0} aria-label="仅支持 macOS">
<span tabIndex={0} aria-label="仅支持 macOS 和 Windows">
<Button
variant="outline"
size="sm"
@@ -129,7 +129,7 @@ export function ChatHeader({
</Button>
</span>
</TooltipTrigger>
<TooltipContent>仅支持 macOS</TooltipContent>
<TooltipContent>仅支持 macOS 和 Windows</TooltipContent>
</Tooltip>
)}
<Button
@@ -80,7 +80,7 @@ export function ReportViewer({
const title = useMemo(() => (report ? `${report.contactName} 群聊日报` : 'AI 日报'), [report])
const sendToGroupHint = !personalWechatSendSupported
? '仅支持 macOS'
? '仅支持 macOS 和 Windows'
: !sendTarget
? '未找到这份日报对应的群聊'
: !report?.pngPath
@@ -106,7 +106,7 @@ const capabilityCopy = (capability: PersonalWechatSendCapability | null): string
case 'ready':
return '✓ 微信发送能力已就绪'
case 'unsupported':
return '微信消息发送目前仅支持 macOS'
return '微信消息发送目前仅支持 macOS 和 Windows'
case 'needs_binding':
case 'unconfigured':
return '请先绑定个人微信'
@@ -127,7 +127,7 @@ const readableError = (error?: string): string => {
const value = String(error || '')
if (value.includes('wechat_not_ready') || value.includes('仅支持 macOS')) {
if (value.includes('unsupported') || value.includes('仅支持'))
return '微信消息发送目前仅支持 macOS'
return '微信消息发送目前仅支持 macOS 和 Windows'
if (value.includes('needs_binding') || value.includes('unconfigured')) return '请先绑定个人微信'
if (value.includes('needs_verification')) return '请先完成微信消息能力检测'
return '微信发送能力不可用,请检查微信连接。'
@@ -576,7 +576,7 @@ export function ScheduledReportsWorkspace({
status: 'unsupported',
capabilities: { text: false, image: false, voice: false },
senderStatus: {} as PersonalWechatSendCapability['senderStatus'],
message: '微信消息发送目前仅支持 macOS'
message: '定时日报目前仅支持 macOS 和 Windows'
})
setTasks([])
setExecutions([])
@@ -367,7 +367,7 @@ export function PersonalWechatSendPage({
<strong className="mt-1 block text-base">{pageMessage}</strong>
<p className="mt-2 text-sm text-muted-foreground">
{pageStatus === 'unsupported' && !isWindows
? '微信消息发送目前仅支持 macOS。'
? '微信消息发送目前仅支持 macOS 和 Windows。'
: isWindows
? 'Windows 通过本机微信发送接口工作,请先配置并检测接口端口。'
: '档案中的文字、图片和语音发送,以及定时日报发送,都会使用这项能力。'}