feat: 增加windows发送能力

抽离功能到设置页面
抽离文字转语音功能
This commit is contained in:
电摇小子 committed 2026-08-31 02:44:24 +08:00
1 parent 698251796f
commit 5acfa14475
33 files changed
+2226 -905

No files matched your search

@@ -37,13 +37,14 @@ export class PersonalWechatCapabilityService {
message:
status === 'unsupported'
? '微信消息发送目前仅支持 macOS'
: status === 'needs_binding' || status === 'unconfigured'
? '请先绑定个人微信'
: status === 'needs_verification'
? '请先完成微信消息能力检测'
: status === 'ready'
? '个人微信已准备好发送日报'
: senderStatus.message || senderStatus.error || '个人微信发送能力异常',
: senderStatus.message ||
(status === 'needs_binding' || status === 'unconfigured'
? '请先绑定个人微信'
: status === 'needs_verification'
? '请先完成微信消息能力检测'
: status === 'ready'
? '个人微信已准备好发送日报'
: senderStatus.error || '个人微信发送能力异常'),
...(senderStatus.error ? { error: senderStatus.error } : {})
}
}
@@ -52,6 +53,12 @@ export class PersonalWechatCapabilityService {
senderStatus: PersonalWechatSenderStatus,
canSendImage: boolean
): PersonalWechatSendCapabilityState {
if (senderStatus.platform === 'win32') {
if (senderStatus.canSend) return 'ready'
if (!senderStatus.endpoint) return 'unconfigured'
if (senderStatus.state === 'error' && senderStatus.endpointReady) return 'error'
return 'needs_verification'
}
if (senderStatus.platform !== 'darwin' || senderStatus.state === 'unsupported_platform') {
return 'unsupported'
}
@@ -1,9 +1,9 @@
import { app } from 'electron'
import { execFile, spawn, type ChildProcess } from 'child_process'
import { createHash, randomUUID } from 'crypto'
import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
import { createHash, randomBytes, randomUUID } from 'crypto'
import { existsSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'fs'
import { createConnection } from 'net'
import { homedir } from 'os'
import { homedir, tmpdir } from 'os'
import { delimiter, dirname, join, sep } from 'path'
import ffmpegStaticPath from 'ffmpeg-static'
import { promisify } from 'util'
@@ -15,7 +15,7 @@ import type {
} from '../../shared/personal-wechat'
import { isPackagedRuntime } from '../runtime-mode'
import { loadSettings, updateSettings } from './settings-store'
import { SilkAudioDecoder } from '../voice-pipeline/audio-decoder'
import { SilkAudioDecoder, SilkAudioEncoder } from '../voice-pipeline/audio-decoder'
import {
validateVoicePcm,
validateVoiceSilkMetadata,
@@ -26,6 +26,7 @@ import { appLogger } from '../app-logger'
const execFileAsync = promisify(execFile)
const DEFAULT_HOST = '127.0.0.1:58080'
const WINDOWS_LOOPBACK_HOST = '127.0.0.1'
const START_TIMEOUT_MS = 20_000
const REQUEST_TIMEOUT_MS = 20_000
const STOP_TIMEOUT_MS = 3_000
@@ -41,6 +42,22 @@ const WECHAT_FILES_ROOT = join(
'Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files'
)
export function normalizeWindowsWechatPort(value: unknown): string | null {
const text = String(value ?? '').trim()
if (!/^\d{1,5}$/.test(text)) return null
const port = Number(text)
if (!Number.isInteger(port) || port < 1 || port > 65_535) return null
return String(port)
}
function windowsHookHost(port?: unknown): string | null {
const configuredPort =
port === undefined
? normalizeWindowsWechatPort(loadSettings().windowsWechatPort)
: normalizeWindowsWechatPort(port)
return configuredPort ? `${WINDOWS_LOOPBACK_HOST}:${configuredPort}` : null
}
export interface RuntimeLayout {
root: string
executable: string
@@ -128,7 +145,7 @@ export function parsePersonalWechatHookLog(log: string): {
baseAddress = text.match(/WeChat core module base:\s*(0x[0-9a-f]+)/i)?.[1]
} else if (text.includes('triggerX0 或 triggerX1Payload 尚未初始化')) {
readiness = 'initializing'
error = '微信底层 Hook 尚未就绪,消息没有发出'
error = '微信发送能力尚未就绪,消息没有发出'
} else if (text.includes('捕获到 StartTask 调用')) {
readiness = 'ready'
textHookReady = true
@@ -496,6 +513,71 @@ async function prepareVoiceFile(filePath: string): Promise<Buffer> {
return createWavBuffer(decoded.pcm, decoded.sampleRate, decoded.channels)
}
async function detectVoiceDurationMs(filePath: string): Promise<number | undefined> {
const data = readFileSync(filePath)
if (data.subarray(0, 10).equals(Buffer.from('\x02#!SILK_V3'))) {
const decoded = await new SilkAudioDecoder().decode({
data,
codec: 'silk',
sourceHash: createHash('sha256').update(data).digest('hex')
})
const samples = decoded.channels > 0 ? decoded.pcm.length / 2 / decoded.channels : 0
if (samples > 0 && decoded.sampleRate > 0) {
return Math.round((samples / decoded.sampleRate) * 1000)
}
}
const ffmpegPath = String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked')
if (!ffmpegPath || !existsSync(ffmpegPath)) return undefined
let output = ''
try {
const result = await execFileAsync(ffmpegPath, ['-i', filePath, '-f', 'null', '-'], {
maxBuffer: 2 * 1024 * 1024
})
output = `${result.stdout || ''}\n${result.stderr || ''}`
} catch (error) {
output = `${(error as { stdout?: string }).stdout || ''}\n${(error as { stderr?: string }).stderr || ''}`
}
const match = output.match(/Duration:\s*(\d+):(\d{2}):(\d+(?:\.\d+)?)/i)
if (match) {
const seconds = Number(match[1]) * 3600 + Number(match[2]) * 60 + Number(match[3])
if (Number.isFinite(seconds) && seconds > 0) return Math.round(seconds * 1000)
}
return undefined
}
async function prepareWindowsVoiceFile(filePath: string): Promise<{
filePath: string
durationMs?: number
temporary: boolean
}> {
const source = readFileSync(filePath)
if (source.subarray(0, 10).equals(Buffer.from('\x02#!SILK_V3'))) {
return { filePath, durationMs: await detectVoiceDurationMs(filePath), temporary: false }
}
const ffmpegPath = String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked')
if (!ffmpegPath || !existsSync(ffmpegPath)) {
throw new Error('Windows 语音发送需要可用的 FFmpeg 才能转换为 SILK')
}
const result = await execFileAsync(
ffmpegPath,
['-v', 'error', '-i', filePath, '-ar', '24000', '-ac', '1', '-f', 's16le', 'pipe:1'],
{ encoding: 'buffer', maxBuffer: MAX_VOICE_BYTES }
)
const pcm = Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.from(result.stdout || '')
if (!pcm.length) throw new Error('语音转换失败:没有得到 PCM 音频数据')
const encoded = await new SilkAudioEncoder().encode(pcm, 24_000)
if (!encoded.data.length) throw new Error('语音转换失败:没有得到 SILK 数据')
const convertedPath = join(tmpdir(), `tracememo-voice-${randomBytes(8).toString('hex')}.silk`)
writeFileSync(convertedPath, encoded.data)
return {
filePath: convertedPath,
...(encoded.durationMs > 0 ? { durationMs: encoded.durationMs } : {}),
temporary: true
}
}
async function readWechatVersion(): Promise<string> {
const { stdout } = await execFileAsync('/usr/libexec/PlistBuddy', [
'-c',
@@ -639,6 +721,119 @@ async function requestWithTimeout(
}
}
type WindowsHookResponse = Record<string, unknown>
export function parseWindowsHookResponse(
responseText: string,
requireSuccessRet = false
): WindowsHookResponse {
const normalized = responseText.trim()
if (!normalized) throw new Error('Windows 微信发送能力返回空响应')
let parsed: unknown
try {
parsed = JSON.parse(normalized)
} catch {
throw new Error(`Windows 微信发送能力返回无效 JSON:${normalized.slice(0, 200)}`)
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('Windows 微信发送能力返回格式无效')
}
const response = parsed as WindowsHookResponse
if (requireSuccessRet && response.ret !== 0) {
const detail = response.retmsg ?? response.msg
throw new Error(
detail ? String(detail) : `Windows 微信发送能力返回失败:ret=${String(response.ret)}`
)
}
return response
}
export function parseWindowsLoginStatus(response: WindowsHookResponse): boolean {
return response.status === true
}
export function buildWindowsWechatRequest(
request: PersonalWechatSendRequest,
options: { filePath?: string; durationMs?: number } = {}
): {
endpoint: string
body: Record<string, unknown>
} {
const target = String(request.to || '').trim()
if (request.type === 'text') {
return {
endpoint: '/SendMsg',
body: { toWxid: target, type: 'text', msg: request.text.trim() }
}
}
if (request.type === 'image') {
return {
endpoint: '/SendMsg',
body: { toWxid: target, type: 'image', msg: String(request.filePath || '').trim() }
}
}
const fromId = String(request.fromId || '').trim()
const filePath = String(options.filePath || request.filePath || '').trim()
const durationMs = options.durationMs ?? request.durationMs
return {
endpoint: '/SendMsg',
body: {
toWxid: target,
type: 'voice',
msg: filePath,
...(fromId ? { fromWxid: fromId } : {}),
...(durationMs !== undefined ? { duration: durationMs } : {})
}
}
}
function windowsStatusBase(host = windowsHookHost() || ''): PersonalWechatSenderStatus {
return {
state: 'checking',
platform: process.platform,
arch: process.arch,
sipDisabled: true,
wechatRunning: false,
runtimeReady: false,
endpoint: host,
endpointReady: false,
attachReady: false,
baseAddressReady: false,
textHookInstalled: false,
textHookReady: false,
imageHookInstalled: false,
imageHookReady: false,
messageListenerReady: false,
canSend: false,
canSendText: false,
canSendImage: false,
canSendVoice: false,
message: '正在检查 Windows 微信消息接口'
}
}
async function requestWindowsHook(
endpoint: string,
body: Record<string, unknown>,
timeoutMs = REQUEST_TIMEOUT_MS,
method: 'GET' | 'POST' = 'POST',
host = windowsHookHost()
): Promise<WindowsHookResponse> {
if (!host) throw new Error('尚未配置微信发送能力端口')
const init: RequestInit = {
method,
headers: { 'Content-Type': 'application/json' }
}
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}`)
return parseWindowsHookResponse(responseText, method === 'POST')
}
export class PersonalWechatSendService {
private child: ChildProcess | null = null
private startPromise: Promise<PersonalWechatSenderStatus> | null = null
@@ -657,6 +852,7 @@ export class PersonalWechatSendService {
}
async getStatus(): Promise<PersonalWechatSenderStatus> {
if (process.platform === 'win32') return this.getWindowsStatus()
const preflight = await this.preflight()
const [endpointReady, oneBot] = await Promise.all([
this.isEndpointOnline(),
@@ -699,7 +895,7 @@ export class PersonalWechatSendService {
canSend: false,
canSendText: false,
canSendImage: false,
message: '微信发送 Hook 初始化失败,请点击“绑定微信”',
message: '微信发送能力初始化失败,请尝试重新绑定',
...(hook.error ? { error: hook.error } : {})
}
}
@@ -725,11 +921,27 @@ export class PersonalWechatSendService {
}
}
async checkWindowsStatus(port?: string): Promise<PersonalWechatSenderStatus> {
if (process.platform !== 'win32') return this.getStatus()
const normalizedPort = normalizeWindowsWechatPort(port)
if (!normalizedPort) {
const base = windowsStatusBase()
return {
...base,
state: 'error',
message: '请输入 1 到 65535 之间的微信发送能力端口',
error: '端口格式无效或为空'
}
}
return this.getWindowsStatus(normalizedPort)
}
getLatestVoiceDiagnostic(): PersonalWechatVoiceDiagnostic | null {
return latestVoiceDiagnostic ? { ...latestVoiceDiagnostic } : null
}
async send(request: PersonalWechatSendRequest): Promise<PersonalWechatSendResult> {
if (process.platform === 'win32') return this.sendWindows(request)
const requestId = randomUUID()
if (request.type !== 'voice') return this.sendInternal(request, requestId)
@@ -846,7 +1058,7 @@ export class PersonalWechatSendService {
request.type === 'text'
? '请先在微信中给任意好友手动发送一条文字,再重新检测'
: request.type === 'voice'
? '语音复用媒体上传 Hook,请先在微信中手动发送一张普通图片,再重新检测'
? '语音复用媒体上传能力,请先在微信中手动发送一张普通图片,再重新检测'
: '请先在微信中给任意好友手动发送一张普通图片,再重新检测'
return { success: false, status, error: status.error || guidance }
}
@@ -954,6 +1166,7 @@ export class PersonalWechatSendService {
}
async rebind(): Promise<PersonalWechatSenderStatus> {
if (process.platform === 'win32') return this.getWindowsStatus()
const preflight = await this.preflight()
if (!preflight.runtime || !preflight.status.configPath || !preflight.status.wechatPid) {
return preflight.status
@@ -995,6 +1208,7 @@ export class PersonalWechatSendService {
}
async terminate(force = false): Promise<void> {
if (process.platform === 'win32') return
if (this.keepOneBotProcess && !force) {
this.child = null
this.startPromise = null
@@ -1022,6 +1236,150 @@ export class PersonalWechatSendService {
return this.startPromise
}
private async getWindowsStatus(port?: string): Promise<PersonalWechatSenderStatus> {
const host = windowsHookHost(port)
const base = windowsStatusBase(host || '')
if (!host) {
return {
...base,
state: 'error',
message: '尚未配置微信发送能力端口',
error: '请先输入端口并检测后保存'
}
}
try {
const result = await requestWindowsHook('/getLoginInfo', {}, 3_000, 'GET', host)
const loggedIn = parseWindowsLoginStatus(result)
const connected = {
wechatRunning: true,
runtimeReady: true,
endpointReady: true,
attachReady: true,
baseAddressReady: true,
textHookInstalled: false,
textHookReady: false,
imageHookInstalled: false,
imageHookReady: false,
messageListenerReady: false
}
if (!loggedIn) {
return {
...base,
...connected,
state: 'hook_not_ready',
message: 'Windows 微信发送能力已连接,但微信尚未登录',
error: 'getLoginInfo 返回 status=false,登录后才能发送消息'
}
}
return {
...base,
...connected,
state: 'online' as const,
canSend: true,
canSendText: true,
canSendImage: true,
canSendVoice: true,
message: 'Windows 微信发送能力已连接,可以发送消息'
}
} catch (error) {
return {
...base,
state: 'wechat_not_running',
message: '未检测到 Windows 微信发送能力,请先启动并登录微信',
error: error instanceof Error ? error.message : String(error)
}
}
}
private async sendWindows(request: PersonalWechatSendRequest): Promise<PersonalWechatSendResult> {
const to = String(request?.to || '').trim()
if (!to) {
const status = await this.getWindowsStatus()
return { success: false, status, error: '接收者不能为空' }
}
if (request.type === 'text') {
const text = String(request.text || '').trim()
if (!text) {
const status = await this.getWindowsStatus()
return { success: false, status, error: '文字内容不能为空' }
}
if (text.length > 2_000) {
const status = await this.getWindowsStatus()
return { success: false, status, error: '文字内容不能超过 2000 个字符' }
}
request = { ...request, to, text }
} else {
const filePath = String(request.filePath || '').trim()
if (!filePath || !existsSync(filePath)) {
const status = await this.getWindowsStatus()
return {
success: false,
status,
error: `请选择有效的${request.type === 'voice' ? '语音' : '图片'}文件`
}
}
const size = statSync(filePath).size
if (size <= 0 || size > (request.type === 'voice' ? MAX_VOICE_BYTES : MAX_IMAGE_BYTES)) {
const status = await this.getWindowsStatus()
return {
success: false,
status,
error: `${request.type === 'voice' ? '语音' : '图片'}必须小于 20 MB`
}
}
request = { ...request, to, filePath }
}
const status = await this.getWindowsStatus()
if (!status.canSend) return { success: false, status, error: status.error || status.message }
let temporaryVoicePath: string | undefined
try {
if (request.type === 'text') {
const windowsRequest = buildWindowsWechatRequest(request)
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body)
} else if (request.type === 'voice') {
const fromId = String(request.fromId || '').trim()
if (!fromId) throw new Error('无法识别当前微信账号 wxid,无法发送语音')
const preparedVoice = await prepareWindowsVoiceFile(request.filePath)
temporaryVoicePath = preparedVoice.temporary ? preparedVoice.filePath : undefined
const requestedDuration = Number(request.durationMs)
const rawDuration =
Number.isFinite(requestedDuration) && requestedDuration > 0
? requestedDuration
: preparedVoice.durationMs
if (!rawDuration || !Number.isFinite(rawDuration)) {
throw new Error('无法计算语音时长,请重新生成或选择有效的 SILK 文件')
}
const durationMs = Math.max(1, Math.min(60_000, Math.round(rawDuration)))
const windowsRequest = buildWindowsWechatRequest(request, {
filePath: preparedVoice.filePath,
durationMs
})
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 60_000)
} else {
const windowsRequest = buildWindowsWechatRequest(request)
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 60_000)
}
return { success: true, status: await this.getWindowsStatus() }
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
return {
success: false,
status: { ...(await this.getWindowsStatus()), state: 'error', error: message },
error: `发送失败:${message}`
}
} finally {
if (temporaryVoicePath) {
try {
unlinkSync(temporaryVoicePath)
} catch {
}
}
}
}
private async startRuntime(): Promise<PersonalWechatSenderStatus> {
const preflight = await this.preflight()
if (!preflight.runtime || !preflight.status.configPath) {
@@ -1166,7 +1524,7 @@ export class PersonalWechatSendService {
wechatPid,
wechatVersion,
state: 'runtime_missing',
message: '个人微信发送组件尚未安装,请前往“设置 → 智能能力 → 文字转语音”下载'
message: '个人微信发送组件尚未安装,请前往“设置 → 智能能力 → 微信发送”下载'
}
}
}
@@ -1183,7 +1541,7 @@ export class PersonalWechatSendService {
runtimeReady: true,
executablePath: runtime.executable,
state: 'unsupported_version',
message: `当前微信版本 ${wechatVersion} 暂不支持,请前往文字转语音设置查看支持的版本`,
message: `当前微信版本 ${wechatVersion} 暂不支持,请前往微信发送设置查看支持的版本`,
error: `缺少 ${configPath}`
}
}
+3 -1
View File
@@ -41,6 +41,7 @@ export interface AppSettings {
ttsModel: TextToSpeechModel
/** Keep a running personal-WeChat OneBot process across app restarts. */
keepPersonalWechatProcess?: boolean
windowsWechatPort: string
}
function getDefaultDbRoot(): string {
@@ -123,7 +124,8 @@ const DEFAULT_SETTINGS: AppSettings = {
showStartupProgress: true,
ttsSelectedVoiceId: '',
ttsModel: 's2.1-pro-free',
keepPersonalWechatProcess: false
keepPersonalWechatProcess: false,
windowsWechatPort: ''
}
const SETTINGS_FILE = path.join(