mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 新增MAC微信发送消息 文字转语音 功能
This commit is contained in:
1 parent
9b7f5114bd
commit
4058a817dd
48 files changed
+7240
-22
No files matched your search
@@ -0,0 +1,364 @@
|
||||
import { createHash } from 'crypto'
|
||||
import { execFile } from 'child_process'
|
||||
import { app, net } from 'electron'
|
||||
import { existsSync, readFileSync, writeFileSync } from 'fs'
|
||||
import { chmod, copyFile, cp, mkdir, mkdtemp, open, rename, rm, stat } from 'fs/promises'
|
||||
import { tmpdir } from 'os'
|
||||
import { dirname, join } from 'path'
|
||||
import { promisify } from 'util'
|
||||
import type {
|
||||
PersonalWechatRuntimeDownloadResult,
|
||||
PersonalWechatRuntimeStatus
|
||||
} from '../../shared/personal-wechat-runtime'
|
||||
import { findPersonalWechatRuntime } from './personal-wechat-send-service'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const RUNTIME_VERSION = 'v0.0.18'
|
||||
const ARCHIVE_NAME = 'onebot_mac_arm64.tar.gz'
|
||||
const ARCHIVE_URL = `https://github.com/yincongcyincong/wechat_chatter/releases/download/${RUNTIME_VERSION}/${ARCHIVE_NAME}`
|
||||
const ARCHIVE_SIZE = 66_599_785
|
||||
const ARCHIVE_SHA256 = 'ee1e11bccef7cec1cf944cd8b2ac3fadaadb9376ba24cd823e3409143e107dab'
|
||||
|
||||
function patchPerSendPayload(scriptPath: string): void {
|
||||
let source = readFileSync(scriptPath, 'utf8')
|
||||
if (source.includes('var activeTriggerX1Payload = ptr(0);')) return
|
||||
|
||||
const declarations = 'var triggerX1Payload;\nvar triggerX0;'
|
||||
const patchedDeclarations =
|
||||
'var triggerX1Payload;\nvar activeTriggerX1Payload = ptr(0);\nvar triggerX0;'
|
||||
const originalSend = ` const payloadData = hexToByteArray(payloadHex);
|
||||
triggerX1Payload.writeByteArray(payloadData);
|
||||
triggerX1Payload.add(0x18).writePointer(info.cgiAddr);
|
||||
triggerX1Payload.add(0xb8).writePointer(triggerX1Payload.add(0xc0));
|
||||
triggerX1Payload.add(0x190).writePointer(triggerX1Payload.add(0x198));`
|
||||
const patchedSend = ` const payloadData = hexToByteArray(payloadHex);
|
||||
activeTriggerX1Payload = Memory.alloc(payloadData.length);
|
||||
activeTriggerX1Payload.writeByteArray(payloadData);
|
||||
activeTriggerX1Payload.add(0x18).writePointer(info.cgiAddr);
|
||||
activeTriggerX1Payload.add(0xb8).writePointer(activeTriggerX1Payload.add(0xc0));
|
||||
activeTriggerX1Payload.add(0x190).writePointer(activeTriggerX1Payload.add(0x198));`
|
||||
|
||||
if (!source.includes(declarations) || !source.includes(originalSend)) {
|
||||
throw new Error('下载的发送组件与当前应用不兼容')
|
||||
}
|
||||
source = source.replace(declarations, patchedDeclarations).replace(originalSend, patchedSend)
|
||||
source = source.replace(
|
||||
' MMStartTask(triggerX0, triggerX1Payload);',
|
||||
' MMStartTask(triggerX0, activeTriggerX1Payload);'
|
||||
)
|
||||
source = source.replace(
|
||||
' } catch (e) {\n console.error("[!] Error trigger " + msgType + " MMStartTask: " + e);',
|
||||
' } catch (e) {\n activeTriggerX1Payload = ptr(0);\n console.error("[!] Error trigger " + msgType + " MMStartTask: " + e);'
|
||||
)
|
||||
source = source.replace(
|
||||
'\t\t\t\tpendingSendMsgType = "";\n\t\t\t\treturn',
|
||||
'\t\t\t\tpendingSendMsgType = "";\n\t\t\t\tactiveTriggerX1Payload = ptr(0);\n\t\t\t\treturn'
|
||||
)
|
||||
writeFileSync(scriptPath, source)
|
||||
}
|
||||
|
||||
function patchImageHookReadiness(scriptPath: string): void {
|
||||
let source = readFileSync(scriptPath, 'utf8')
|
||||
if (
|
||||
source.includes('捕获到图片上传上下文,uploadGlobalX0') &&
|
||||
source.includes('图片上传 Hook Setup Complete')
|
||||
) {
|
||||
return
|
||||
}
|
||||
const original = `\t\t\tuploadGlobalX0 = this.context.x0;`
|
||||
const patched = `\t\t\tconst capturedUploadX0 = this.context.x0;
|
||||
\t\t\tif (uploadGlobalX0.equals(ptr(0)) && !capturedUploadX0.equals(ptr(0))) {
|
||||
\t\t\t\tconsole.log("[+] 捕获到图片上传上下文,uploadGlobalX0:" + capturedUploadX0);
|
||||
\t\t\t}
|
||||
\t\t\tuploadGlobalX0 = capturedUploadX0;`
|
||||
if (!source.includes(original)) throw new Error('下载的媒体组件与当前应用不兼容')
|
||||
source = source.replace(original, patched)
|
||||
source = source.replace(
|
||||
' })\n}\n\n\n\nfunction patchCdnOnComplete()',
|
||||
' })\n console.log("[+] 图片上传 Hook Setup Complete.");\n}\n\n\n\nfunction patchCdnOnComplete()'
|
||||
)
|
||||
writeFileSync(scriptPath, source)
|
||||
}
|
||||
|
||||
function patchWechatCoreModuleBase(scriptPath: string): void {
|
||||
let source = readFileSync(scriptPath, 'utf8')
|
||||
if (source.includes('WeChat core module base:')) return
|
||||
const initMarker = 'function initAddresses() {'
|
||||
const initIndex = source.indexOf(initMarker)
|
||||
if (initIndex < 0 || !source.startsWith('var targetPath = ')) {
|
||||
throw new Error('下载的微信版本配置与当前应用不兼容')
|
||||
}
|
||||
const patchedHeader = `var targetPath = "/Applications/WeChat.app/Contents/Resources/wechat.dylib";
|
||||
var module = Process.enumerateModules().find(function(m) {
|
||||
return m.path === targetPath || m.path.endsWith("/Contents/Resources/wechat.dylib");
|
||||
});
|
||||
if (!module) {
|
||||
throw new Error("[-] Cannot find WeChat core module: " + targetPath);
|
||||
}
|
||||
var moduleBase = module.base;
|
||||
var baseAddr = moduleBase;
|
||||
console.log("[+] WeChat core module base: " + baseAddr + " path=" + module.path);
|
||||
setImmediate(initAddresses);
|
||||
|
||||
`
|
||||
source = patchedHeader + source.slice(initIndex)
|
||||
writeFileSync(scriptPath, source)
|
||||
}
|
||||
|
||||
function addModifiedWorkNotice(scriptPath: string): void {
|
||||
let source = readFileSync(scriptPath, 'utf8')
|
||||
if (source.includes('TraceMemo wechat_chatter compatibility modifications')) return
|
||||
source = `/*
|
||||
* TraceMemo wechat_chatter compatibility modifications
|
||||
* Modified: 2026-08-17
|
||||
* Upstream: https://github.com/yincongcyincong/wechat_chatter
|
||||
* Runtime version: v0.0.18
|
||||
* License: GNU General Public License version 3 (GPL-3.0)
|
||||
* Changes: WeChat module discovery, per-send payload isolation, and image Hook readiness logging.
|
||||
* These modifications are not provided by the upstream author.
|
||||
*/
|
||||
|
||||
${source}`
|
||||
writeFileSync(scriptPath, source)
|
||||
}
|
||||
|
||||
export class PersonalWechatRuntimeManager {
|
||||
private downloadController: AbortController | null = null
|
||||
private downloadPromise: Promise<PersonalWechatRuntimeDownloadResult> | null = null
|
||||
private downloadedBytes = 0
|
||||
private lastProgressAt = 0
|
||||
private progressListener: ((status: PersonalWechatRuntimeStatus) => void) | null = null
|
||||
|
||||
get directory(): string {
|
||||
return join(app.getPath('userData'), 'connectors', 'wechat-personal', 'darwin-arm64')
|
||||
}
|
||||
|
||||
private get archivePath(): string {
|
||||
return join(
|
||||
app.getPath('userData'),
|
||||
'downloads',
|
||||
`wechat-chatter-${RUNTIME_VERSION}-${ARCHIVE_NAME}`
|
||||
)
|
||||
}
|
||||
|
||||
setProgressListener(listener: ((status: PersonalWechatRuntimeStatus) => void) | null): void {
|
||||
this.progressListener = listener
|
||||
}
|
||||
|
||||
async getStatus(): Promise<PersonalWechatRuntimeStatus> {
|
||||
if (!this.isSupported()) {
|
||||
return this.buildStatus(
|
||||
'unsupported',
|
||||
0,
|
||||
process.platform === 'win32'
|
||||
? 'Windows 暂不支持个人微信发送组件'
|
||||
: `当前系统暂不支持个人微信发送组件:${process.platform} ${process.arch}`
|
||||
)
|
||||
}
|
||||
if (this.downloadPromise) return this.buildStatus('downloading', this.downloadedBytes)
|
||||
|
||||
const runtime = findPersonalWechatRuntime()
|
||||
if (runtime) {
|
||||
return this.buildStatus('ready', ARCHIVE_SIZE, undefined, runtime.root)
|
||||
}
|
||||
|
||||
const hasPartialInstall = await this.hasPartialInstall()
|
||||
return this.buildStatus(
|
||||
hasPartialInstall ? 'invalid' : 'missing',
|
||||
0,
|
||||
hasPartialInstall ? '发送组件文件不完整,请重新下载' : undefined,
|
||||
hasPartialInstall ? this.directory : undefined
|
||||
)
|
||||
}
|
||||
|
||||
download(): Promise<PersonalWechatRuntimeDownloadResult> {
|
||||
if (!this.isSupported()) {
|
||||
return this.getStatus().then((status) => ({ success: false, status, error: status.error }))
|
||||
}
|
||||
if (this.downloadPromise) return this.downloadPromise
|
||||
this.downloadedBytes = 0
|
||||
this.downloadController = new AbortController()
|
||||
this.downloadPromise = this.runDownload(this.downloadController.signal).finally(() => {
|
||||
this.downloadPromise = null
|
||||
this.downloadController = null
|
||||
})
|
||||
return this.downloadPromise
|
||||
}
|
||||
|
||||
cancelDownload(): boolean {
|
||||
if (!this.downloadController) return false
|
||||
this.downloadController.abort()
|
||||
return true
|
||||
}
|
||||
|
||||
async remove(): Promise<PersonalWechatRuntimeStatus> {
|
||||
if (this.downloadPromise) return this.buildStatus('downloading', this.downloadedBytes)
|
||||
await Promise.all([
|
||||
rm(this.directory, { recursive: true, force: true }),
|
||||
rm(this.archivePath, { force: true }),
|
||||
rm(`${this.archivePath}.partial`, { force: true })
|
||||
])
|
||||
return this.getStatus()
|
||||
}
|
||||
|
||||
private async runDownload(signal: AbortSignal): Promise<PersonalWechatRuntimeDownloadResult> {
|
||||
const archive = this.archivePath
|
||||
const downloadsDirectory = dirname(archive)
|
||||
const partial = `${archive}.partial`
|
||||
let extractionDirectory = ''
|
||||
let stagedDirectory = ''
|
||||
try {
|
||||
await mkdir(downloadsDirectory, { recursive: true })
|
||||
await rm(partial, { force: true })
|
||||
const response = await net.fetch(ARCHIVE_URL, { signal })
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`发送组件下载失败:HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
const handle = await open(partial, 'w')
|
||||
const hash = createHash('sha256')
|
||||
try {
|
||||
const reader = response.body.getReader()
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
if (signal.aborted) throw new DOMException('Download cancelled', 'AbortError')
|
||||
const chunk = Buffer.from(value)
|
||||
await handle.write(chunk)
|
||||
hash.update(chunk)
|
||||
this.downloadedBytes += chunk.length
|
||||
this.reportProgress(this.buildStatus('downloading', this.downloadedBytes))
|
||||
}
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
|
||||
if (this.downloadedBytes !== ARCHIVE_SIZE || hash.digest('hex') !== ARCHIVE_SHA256) {
|
||||
throw new Error('发送组件校验失败,请重新下载')
|
||||
}
|
||||
await rm(archive, { force: true })
|
||||
await rename(partial, archive)
|
||||
|
||||
extractionDirectory = await mkdtemp(join(tmpdir(), 'wechat-chatter-extract-'))
|
||||
await execFileAsync('/usr/bin/tar', ['-xzf', archive, '-C', extractionDirectory])
|
||||
stagedDirectory = `${this.directory}.installing-${process.pid}`
|
||||
await rm(stagedDirectory, { recursive: true, force: true })
|
||||
await mkdir(dirname(stagedDirectory), { recursive: true })
|
||||
await mkdir(join(stagedDirectory, 'onebot'), { recursive: true })
|
||||
|
||||
const sourceOneBot = join(extractionDirectory, 'onebot')
|
||||
const sourceVersions = join(extractionDirectory, 'wechat_version')
|
||||
await Promise.all([
|
||||
cp(sourceVersions, join(stagedDirectory, 'wechat_version'), {
|
||||
recursive: true,
|
||||
force: true
|
||||
}),
|
||||
copyFile(join(sourceOneBot, 'onebot'), join(stagedDirectory, 'onebot', 'onebot')),
|
||||
copyFile(join(sourceOneBot, 'script.js'), join(stagedDirectory, 'onebot', 'script.js'))
|
||||
])
|
||||
|
||||
const executable = join(stagedDirectory, 'onebot', 'onebot')
|
||||
const script = join(stagedDirectory, 'onebot', 'script.js')
|
||||
patchWechatCoreModuleBase(script)
|
||||
patchPerSendPayload(script)
|
||||
patchImageHookReadiness(script)
|
||||
addModifiedWorkNotice(script)
|
||||
await chmod(executable, 0o755)
|
||||
|
||||
const pythonPackages = join(stagedDirectory, 'python')
|
||||
await mkdir(pythonPackages, { recursive: true })
|
||||
try {
|
||||
await execFileAsync('/usr/bin/env', [
|
||||
'python3',
|
||||
'-m',
|
||||
'pip',
|
||||
'install',
|
||||
'--disable-pip-version-check',
|
||||
'--no-compile',
|
||||
'--target',
|
||||
pythonPackages,
|
||||
'pilk==0.2.4'
|
||||
])
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
'[PersonalWechatRuntime] pilk 安装失败,将使用 OneBot 内置的 Go SILK 编码器:',
|
||||
error
|
||||
)
|
||||
}
|
||||
|
||||
for (const required of [
|
||||
executable,
|
||||
script,
|
||||
join(stagedDirectory, 'wechat_version', '4_1_11_53_mac.json')
|
||||
]) {
|
||||
if (!existsSync(required)) throw new Error('发送组件解压后文件不完整')
|
||||
}
|
||||
|
||||
await rm(this.directory, { recursive: true, force: true })
|
||||
await rename(stagedDirectory, this.directory)
|
||||
stagedDirectory = ''
|
||||
const status = this.buildStatus('ready', ARCHIVE_SIZE, undefined, this.directory)
|
||||
this.reportProgress(status, true)
|
||||
return { success: true, status }
|
||||
} catch (error) {
|
||||
const cancelled = signal.aborted
|
||||
const message = cancelled
|
||||
? '发送组件下载已取消'
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: String(error)
|
||||
await rm(partial, { force: true })
|
||||
const status = this.buildStatus(
|
||||
cancelled ? 'missing' : 'error',
|
||||
this.downloadedBytes,
|
||||
message
|
||||
)
|
||||
this.reportProgress(status, true)
|
||||
return { success: false, status, error: message }
|
||||
} finally {
|
||||
if (extractionDirectory) await rm(extractionDirectory, { recursive: true, force: true })
|
||||
if (stagedDirectory) await rm(stagedDirectory, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
private async hasPartialInstall(): Promise<boolean> {
|
||||
try {
|
||||
await stat(this.directory)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private isSupported(): boolean {
|
||||
return process.platform === 'darwin' && process.arch === 'arm64'
|
||||
}
|
||||
|
||||
private buildStatus(
|
||||
state: PersonalWechatRuntimeStatus['state'],
|
||||
downloadedBytes: number,
|
||||
error?: string,
|
||||
directory?: string
|
||||
): PersonalWechatRuntimeStatus {
|
||||
return {
|
||||
version: RUNTIME_VERSION,
|
||||
state,
|
||||
downloadedBytes,
|
||||
totalBytes: ARCHIVE_SIZE,
|
||||
progress: ARCHIVE_SIZE ? Math.min(1, downloadedBytes / ARCHIVE_SIZE) : 0,
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
supported: this.isSupported(),
|
||||
removable: directory === this.directory,
|
||||
...(directory ? { directory } : {}),
|
||||
...(error ? { error } : {})
|
||||
}
|
||||
}
|
||||
|
||||
private reportProgress(status: PersonalWechatRuntimeStatus, force = false): void {
|
||||
const now = Date.now()
|
||||
if (!force && now - this.lastProgressAt < 100) return
|
||||
this.lastProgressAt = now
|
||||
this.progressListener?.(status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,880 @@
|
||||
import { app } from 'electron'
|
||||
import { execFile, spawn, type ChildProcess } from 'child_process'
|
||||
import { createHash } from 'crypto'
|
||||
import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
|
||||
import { createConnection } from 'net'
|
||||
import { homedir } from 'os'
|
||||
import { delimiter, dirname, join, sep } from 'path'
|
||||
import ffmpegStaticPath from 'ffmpeg-static'
|
||||
import { promisify } from 'util'
|
||||
import type {
|
||||
PersonalWechatSendRequest,
|
||||
PersonalWechatSendResult,
|
||||
PersonalWechatSenderStatus
|
||||
} from '../../shared/personal-wechat'
|
||||
import { isPackagedRuntime } from '../runtime-mode'
|
||||
import { SilkAudioDecoder } from '../voice-pipeline/audio-decoder'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const DEFAULT_HOST = '127.0.0.1:58080'
|
||||
const START_TIMEOUT_MS = 20_000
|
||||
const REQUEST_TIMEOUT_MS = 20_000
|
||||
const STOP_TIMEOUT_MS = 3_000
|
||||
const MAX_IMAGE_BYTES = 20 * 1024 * 1024
|
||||
const MAX_VOICE_BYTES = 20 * 1024 * 1024
|
||||
const WECHAT_APP_PATH = '/Applications/WeChat.app'
|
||||
const WECHAT_FILES_ROOT = join(
|
||||
homedir(),
|
||||
'Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files'
|
||||
)
|
||||
|
||||
export interface RuntimeLayout {
|
||||
root: string
|
||||
executable: string
|
||||
workingDirectory: string
|
||||
configDirectory: string
|
||||
logPath: string
|
||||
}
|
||||
|
||||
export type PersonalWechatHookReadiness = 'unknown' | 'initializing' | 'ready' | 'failed'
|
||||
|
||||
export function parsePersonalWechatHookLog(log: string): {
|
||||
readiness: PersonalWechatHookReadiness
|
||||
attached: boolean
|
||||
baseAddress?: string
|
||||
textHookInstalled: boolean
|
||||
textHookReady: boolean
|
||||
imageHookInstalled: boolean
|
||||
imageHookReady: boolean
|
||||
messageListenerReady: boolean
|
||||
boundWechatPid?: number
|
||||
error?: string
|
||||
} {
|
||||
let readiness: PersonalWechatHookReadiness = 'unknown'
|
||||
let attached = false
|
||||
let baseAddress: string | undefined
|
||||
let textHookInstalled = false
|
||||
let textHookReady = false
|
||||
let imageHookInstalled = false
|
||||
let imageHookReady = false
|
||||
let messageListenerReady = false
|
||||
let boundWechatPid: number | undefined
|
||||
let error: string | undefined
|
||||
for (const line of log.split(/\r?\n/)) {
|
||||
if (!line.trim()) continue
|
||||
try {
|
||||
const entry = JSON.parse(line) as {
|
||||
payload?: string
|
||||
err?: string
|
||||
message?: string
|
||||
PID?: number
|
||||
type?: string
|
||||
result?: string | number
|
||||
}
|
||||
const text = `${entry.payload || ''} ${entry.err || ''} ${entry.message || ''}`
|
||||
// wechat_chatter writes the task receipt and its result as two separate
|
||||
// JSON log records: the first has type=send_image, while the next has
|
||||
// the result and the Chinese result message but no type field.
|
||||
if (
|
||||
(entry.type === 'send_image' || text.includes('发送图片任务执行结果')) &&
|
||||
String(entry.result) === '1'
|
||||
) {
|
||||
imageHookInstalled = true
|
||||
imageHookReady = true
|
||||
}
|
||||
if (
|
||||
(entry.type === 'image' || text.includes('上传图片任务执行结果')) &&
|
||||
String(entry.result) === '0'
|
||||
) {
|
||||
imageHookInstalled = true
|
||||
}
|
||||
if (text.includes('使用指定的微信进程 PID')) {
|
||||
readiness = 'unknown'
|
||||
attached = false
|
||||
baseAddress = undefined
|
||||
textHookInstalled = false
|
||||
textHookReady = false
|
||||
imageHookInstalled = false
|
||||
imageHookReady = false
|
||||
messageListenerReady = false
|
||||
boundWechatPid = Number(entry.PID) || undefined
|
||||
error = undefined
|
||||
} else if (
|
||||
text.includes("Cannot find 'req2buf' keyword") ||
|
||||
text.includes('Attach 失败') ||
|
||||
text.includes('unable to intercept function')
|
||||
) {
|
||||
readiness = 'failed'
|
||||
error = entry.err || entry.message
|
||||
} else if (text.includes('成功 Attach 微信进程')) {
|
||||
attached = true
|
||||
boundWechatPid = Number(entry.PID) || boundWechatPid
|
||||
} else if (text.includes('Base address from range:')) {
|
||||
baseAddress = text.match(/Base address from range:\s*(0x[0-9a-f]+)/i)?.[1]
|
||||
} else if (text.includes('WeChat core module base:')) {
|
||||
baseAddress = text.match(/WeChat core module base:\s*(0x[0-9a-f]+)/i)?.[1]
|
||||
} else if (text.includes('triggerX0 或 triggerX1Payload 尚未初始化')) {
|
||||
readiness = 'initializing'
|
||||
error = '微信底层 Hook 尚未就绪,消息没有发出'
|
||||
} else if (text.includes('捕获到 StartTask 调用')) {
|
||||
readiness = 'ready'
|
||||
textHookReady = true
|
||||
error = undefined
|
||||
} else if (text.includes('Dynamic Text Message Setup Complete')) {
|
||||
textHookInstalled = true
|
||||
if (readiness === 'unknown') readiness = 'initializing'
|
||||
} else if (text.includes('捕获到图片上传上下文')) {
|
||||
imageHookReady = true
|
||||
} else if (text.includes('图片上传 Hook Setup Complete')) {
|
||||
imageHookInstalled = true
|
||||
} else if (text.includes('HTTP 服务启动在')) {
|
||||
messageListenerReady = true
|
||||
} else if (text.includes('发送数据')) {
|
||||
messageListenerReady = true
|
||||
}
|
||||
} catch {
|
||||
// Ignore non-JSON or partially written log lines.
|
||||
}
|
||||
}
|
||||
return {
|
||||
readiness,
|
||||
attached,
|
||||
...(baseAddress ? { baseAddress } : {}),
|
||||
textHookInstalled,
|
||||
textHookReady,
|
||||
imageHookInstalled,
|
||||
imageHookReady,
|
||||
messageListenerReady,
|
||||
...(boundWechatPid ? { boundWechatPid } : {}),
|
||||
...(error ? { error } : {})
|
||||
}
|
||||
}
|
||||
|
||||
interface PreflightResult {
|
||||
status: PersonalWechatSenderStatus
|
||||
runtime?: RuntimeLayout
|
||||
}
|
||||
|
||||
function toConfigFileName(version: string): string {
|
||||
return `${version.replace(/\./g, '_')}_mac.json`
|
||||
}
|
||||
|
||||
function runtimeCandidates(): string[] {
|
||||
const override = String(process.env['WECHAT_CHATTER_RUNTIME_DIR'] || '').trim()
|
||||
const relative = ['connectors', 'wechat-personal', `${process.platform}-${process.arch}`]
|
||||
const downloaded = join(app.getPath('userData'), ...relative)
|
||||
const packaged = join(process.resourcesPath, 'resources', ...relative)
|
||||
const development = join(app.getAppPath(), 'resources', ...relative)
|
||||
const ordered = isPackagedRuntime()
|
||||
? [downloaded, packaged, development]
|
||||
: [downloaded, development, packaged]
|
||||
return override ? [override, ...ordered] : ordered
|
||||
}
|
||||
|
||||
export function findPersonalWechatRuntime(candidates = runtimeCandidates()): RuntimeLayout | null {
|
||||
for (const root of candidates) {
|
||||
const nestedExecutable = join(root, 'onebot', 'onebot')
|
||||
const flatExecutable = join(root, 'onebot')
|
||||
if (existsSync(nestedExecutable) && existsSync(join(root, 'onebot', 'script.js'))) {
|
||||
return {
|
||||
root,
|
||||
executable: nestedExecutable,
|
||||
workingDirectory: join(root, 'onebot'),
|
||||
configDirectory: join(root, 'wechat_version'),
|
||||
logPath: join(root, 'onebot', 'log', 'macos.log')
|
||||
}
|
||||
}
|
||||
if (existsSync(flatExecutable) && existsSync(join(root, 'script.js'))) {
|
||||
return {
|
||||
root,
|
||||
executable: flatExecutable,
|
||||
workingDirectory: root,
|
||||
configDirectory: join(root, 'wechat_version'),
|
||||
logPath: join(root, 'log', 'macos.log')
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function buildPersonalWechatOneBotRequest(
|
||||
request: PersonalWechatSendRequest,
|
||||
fileBase64?: string
|
||||
): {
|
||||
endpoint: string
|
||||
body: Record<string, unknown>
|
||||
} {
|
||||
const target = request.to.trim()
|
||||
const isGroup = request.isGroup || target.endsWith('@chatroom')
|
||||
const message =
|
||||
request.type === 'text'
|
||||
? [{ type: 'text', data: { text: request.text.trim() } }]
|
||||
: [
|
||||
{
|
||||
type: request.type === 'voice' ? 'record' : 'image',
|
||||
data: { file: `base64://${fileBase64 || ''}` }
|
||||
}
|
||||
]
|
||||
return {
|
||||
endpoint: isGroup ? '/send_group_msg' : '/send_private_msg',
|
||||
body: {
|
||||
...(isGroup ? { group_id: target } : { user_id: target }),
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildRuntimePath(): string {
|
||||
const existing = String(process.env['PATH'] || '')
|
||||
const bundledFfmpeg = String(ffmpegStaticPath || '')
|
||||
.replace('app.asar', 'app.asar.unpacked')
|
||||
.trim()
|
||||
if (!bundledFfmpeg || !existsSync(bundledFfmpeg)) return existing
|
||||
return [dirname(bundledFfmpeg), existing].filter(Boolean).join(delimiter)
|
||||
}
|
||||
|
||||
function buildRuntimePythonPath(runtimeRoot: string): string {
|
||||
return [join(runtimeRoot, 'python'), String(process.env['PYTHONPATH'] || '')]
|
||||
.filter(Boolean)
|
||||
.join(delimiter)
|
||||
}
|
||||
|
||||
function createWavBuffer(pcm: Buffer, sampleRate: number, channels: number): Buffer {
|
||||
const header = Buffer.alloc(44)
|
||||
header.write('RIFF', 0)
|
||||
header.writeUInt32LE(36 + pcm.length, 4)
|
||||
header.write('WAVE', 8)
|
||||
header.write('fmt ', 12)
|
||||
header.writeUInt32LE(16, 16)
|
||||
header.writeUInt16LE(1, 20)
|
||||
header.writeUInt16LE(channels, 22)
|
||||
header.writeUInt32LE(sampleRate, 24)
|
||||
header.writeUInt32LE(sampleRate * channels * 2, 28)
|
||||
header.writeUInt16LE(channels * 2, 32)
|
||||
header.writeUInt16LE(16, 34)
|
||||
header.write('data', 36)
|
||||
header.writeUInt32LE(pcm.length, 40)
|
||||
return Buffer.concat([header, pcm])
|
||||
}
|
||||
|
||||
async function prepareVoiceFile(filePath: string): Promise<Buffer> {
|
||||
const data = readFileSync(filePath)
|
||||
if (!data.subarray(0, 10).equals(Buffer.from('\x02#!SILK_V3'))) return data
|
||||
const decoded = await new SilkAudioDecoder().decode({
|
||||
data,
|
||||
codec: 'silk',
|
||||
sourceHash: createHash('sha256').update(data).digest('hex')
|
||||
})
|
||||
return createWavBuffer(decoded.pcm, decoded.sampleRate, decoded.channels)
|
||||
}
|
||||
|
||||
async function readWechatVersion(): Promise<string> {
|
||||
const { stdout } = await execFileAsync('/usr/libexec/PlistBuddy', [
|
||||
'-c',
|
||||
'Print :WeChatBundleVersion',
|
||||
join(WECHAT_APP_PATH, 'Contents', 'Info.plist')
|
||||
])
|
||||
return stdout.trim()
|
||||
}
|
||||
|
||||
async function readWechatPid(): Promise<number | undefined> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('/usr/bin/pgrep', ['-x', 'WeChat'])
|
||||
const pid = Number(stdout.trim().split(/\s+/)[0])
|
||||
return Number.isInteger(pid) && pid > 0 ? pid : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Locate the current account's temporary image directory required by the upstream hook. */
|
||||
export function findWechatImagePath(
|
||||
root = WECHAT_FILES_ROOT,
|
||||
now = new Date()
|
||||
): string | undefined {
|
||||
try {
|
||||
const month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
|
||||
const candidates: Array<{ path: string; mtime: number }> = []
|
||||
const fallbacks: Array<{ path: string; mtime: number }> = []
|
||||
for (const account of readdirSync(root)) {
|
||||
const tempRoot = join(root, account, 'temp')
|
||||
if (!existsSync(tempRoot)) continue
|
||||
fallbacks.push({
|
||||
path: join(tempRoot, 'ImageTemp', month),
|
||||
mtime: statSync(tempRoot).mtimeMs
|
||||
})
|
||||
const imageTempPath = join(tempRoot, 'ImageTemp', month)
|
||||
if (existsSync(imageTempPath)) {
|
||||
candidates.push({ path: imageTempPath, mtime: statSync(imageTempPath).mtimeMs })
|
||||
}
|
||||
for (const tempId of readdirSync(tempRoot)) {
|
||||
const imagePath = join(tempRoot, tempId, month, 'Img')
|
||||
if (existsSync(imagePath)) {
|
||||
candidates.push({ path: imagePath, mtime: statSync(imagePath).mtimeMs })
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates.sort((a, b) => b.mtime - a.mtime)
|
||||
fallbacks.sort((a, b) => b.mtime - a.mtime)
|
||||
const selected = candidates[0]?.path || fallbacks[0]?.path
|
||||
return selected ? `${selected}${sep}` : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function isSipDisabled(): Promise<boolean> {
|
||||
try {
|
||||
const { stdout, stderr } = await execFileAsync('/usr/bin/csrutil', ['status'])
|
||||
return `${stdout}\n${stderr}`.toLowerCase().includes('disabled')
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
interface OneBotProcessInfo {
|
||||
pid: number
|
||||
boundWechatPid?: number
|
||||
imagePath?: string
|
||||
command: string
|
||||
}
|
||||
|
||||
async function readOneBotProcessInfo(): Promise<OneBotProcessInfo | undefined> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('/usr/sbin/lsof', [
|
||||
'-nP',
|
||||
'-t',
|
||||
`-iTCP:${DEFAULT_HOST.split(':')[1]}`,
|
||||
'-sTCP:LISTEN'
|
||||
])
|
||||
const pid = Number(stdout.trim().split(/\s+/)[0])
|
||||
if (!Number.isInteger(pid) || pid <= 0) return undefined
|
||||
const { stdout: commandOutput } = await execFileAsync('/bin/ps', [
|
||||
'-p',
|
||||
String(pid),
|
||||
'-o',
|
||||
'command='
|
||||
])
|
||||
const command = commandOutput.trim()
|
||||
if (!/(^|\/)onebot(?:\s|$)/.test(command)) return undefined
|
||||
const boundWechatPid = Number(command.match(/-wechat_pid=(\d+)/)?.[1]) || undefined
|
||||
const imagePath = command.match(/-image_path=(\S+)/)?.[1]
|
||||
return {
|
||||
pid,
|
||||
...(boundWechatPid ? { boundWechatPid } : {}),
|
||||
...(imagePath ? { imagePath } : {}),
|
||||
command
|
||||
}
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function terminateOneBot(info: OneBotProcessInfo): Promise<void> {
|
||||
if (!/(^|\/)onebot(?:\s|$)/.test(info.command)) return
|
||||
try {
|
||||
process.kill(info.pid, 'SIGTERM')
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const startedAt = Date.now()
|
||||
while (Date.now() - startedAt < STOP_TIMEOUT_MS) {
|
||||
try {
|
||||
process.kill(info.pid, 0)
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function requestWithTimeout(
|
||||
url: string,
|
||||
init?: RequestInit,
|
||||
timeoutMs = 2_000
|
||||
): Promise<Response> {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
try {
|
||||
return await fetch(url, { ...init, signal: controller.signal })
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
export class PersonalWechatSendService {
|
||||
private child: ChildProcess | null = null
|
||||
private startPromise: Promise<PersonalWechatSenderStatus> | null = null
|
||||
private lastError = ''
|
||||
|
||||
async getStatus(): Promise<PersonalWechatSenderStatus> {
|
||||
const preflight = await this.preflight()
|
||||
const [endpointReady, oneBot] = await Promise.all([
|
||||
this.isEndpointOnline(),
|
||||
readOneBotProcessInfo()
|
||||
])
|
||||
const hook = this.readHookReadiness(preflight.runtime)
|
||||
const boundWechatPid = oneBot?.boundWechatPid || hook.boundWechatPid
|
||||
const boundToCurrentWechat = Boolean(
|
||||
preflight.status.wechatPid && boundWechatPid === preflight.status.wechatPid
|
||||
)
|
||||
const common = {
|
||||
...preflight.status,
|
||||
endpointReady,
|
||||
...(oneBot?.pid ? { oneBotPid: oneBot.pid } : {}),
|
||||
...(boundWechatPid ? { boundWechatPid } : {}),
|
||||
attachReady: hook.attached,
|
||||
...(hook.baseAddress ? { baseAddress: hook.baseAddress } : {}),
|
||||
baseAddressReady: Boolean(hook.baseAddress),
|
||||
textHookInstalled: hook.textHookInstalled,
|
||||
textHookReady: hook.textHookReady,
|
||||
imageHookInstalled: hook.imageHookInstalled,
|
||||
imageHookReady: hook.imageHookReady,
|
||||
messageListenerReady: hook.messageListenerReady
|
||||
}
|
||||
if (!endpointReady) return common
|
||||
if (!boundToCurrentWechat) {
|
||||
return {
|
||||
...common,
|
||||
state: 'hook_not_ready',
|
||||
canSend: false,
|
||||
canSendText: false,
|
||||
canSendImage: false,
|
||||
message: 'OneBot 仍绑定旧微信进程,请点击“尝试重新绑定”'
|
||||
}
|
||||
}
|
||||
if (hook.readiness === 'failed') {
|
||||
return {
|
||||
...common,
|
||||
state: 'error',
|
||||
canSend: false,
|
||||
canSendText: false,
|
||||
canSendImage: false,
|
||||
message: '微信发送 Hook 初始化失败,请尝试重新绑定',
|
||||
...(hook.error ? { error: hook.error } : {})
|
||||
}
|
||||
}
|
||||
const baseReady = hook.attached && Boolean(hook.baseAddress) && hook.textHookInstalled
|
||||
const canSendText = baseReady && hook.textHookReady
|
||||
const imagePathBound = Boolean(oneBot?.imagePath)
|
||||
const canSendImage = baseReady && hook.imageHookReady && imagePathBound
|
||||
const canSendVoice = baseReady && hook.imageHookReady
|
||||
return {
|
||||
...common,
|
||||
state: canSendText || canSendImage || canSendVoice ? 'online' : 'hook_not_ready',
|
||||
canSend: canSendText || canSendImage || canSendVoice,
|
||||
canSendText,
|
||||
canSendImage,
|
||||
canSendVoice,
|
||||
message:
|
||||
hook.imageHookReady && preflight.status.imagePath && !imagePathBound
|
||||
? 'OneBot 尚未绑定微信图片目录,请点击“尝试重新绑定”'
|
||||
: canSendText || canSendImage || canSendVoice
|
||||
? '个人微信已绑定,可使用已初始化的消息类型'
|
||||
: '个人微信已绑定,发送前请先在微信中手动初始化对应消息类型',
|
||||
...(hook.error ? { error: hook.error } : {})
|
||||
}
|
||||
}
|
||||
|
||||
async send(request: PersonalWechatSendRequest): Promise<PersonalWechatSendResult> {
|
||||
const to = String(request?.to || '').trim()
|
||||
if (!to) {
|
||||
const status = await this.getStatus()
|
||||
return { success: false, status, error: '接收者不能为空' }
|
||||
}
|
||||
let fileBase64: string | undefined
|
||||
if (request.type === 'text') {
|
||||
const text = String(request.text || '').trim()
|
||||
if (!text) {
|
||||
const status = await this.getStatus()
|
||||
return { success: false, status, error: '文字内容不能为空' }
|
||||
}
|
||||
if (text.length > 2_000) {
|
||||
const status = await this.getStatus()
|
||||
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.getStatus()
|
||||
return {
|
||||
success: false,
|
||||
status,
|
||||
error: `请选择有效的${request.type === 'voice' ? '语音' : '图片'}文件`
|
||||
}
|
||||
}
|
||||
const size = statSync(filePath).size
|
||||
const maxBytes = request.type === 'voice' ? MAX_VOICE_BYTES : MAX_IMAGE_BYTES
|
||||
if (size <= 0 || size > maxBytes) {
|
||||
const status = await this.getStatus()
|
||||
return {
|
||||
success: false,
|
||||
status,
|
||||
error: `测试${request.type === 'voice' ? '语音' : '图片'}必须小于 20 MB`
|
||||
}
|
||||
}
|
||||
fileBase64 = (
|
||||
request.type === 'voice' ? await prepareVoiceFile(filePath) : readFileSync(filePath)
|
||||
).toString('base64')
|
||||
request = { ...request, to, filePath }
|
||||
}
|
||||
|
||||
const status = await this.ensureRunning()
|
||||
const typeReady =
|
||||
request.type === 'text'
|
||||
? status.canSendText
|
||||
: request.type === 'voice'
|
||||
? status.canSendVoice
|
||||
: status.canSendImage
|
||||
if (!typeReady) {
|
||||
const guidance =
|
||||
request.type === 'text'
|
||||
? '请先在微信中给任意好友手动发送一条文字,再重新检测'
|
||||
: request.type === 'voice'
|
||||
? '语音复用媒体上传 Hook,请先在微信中手动发送一张普通图片,再重新检测'
|
||||
: '请先在微信中给任意好友手动发送一张普通图片,再重新检测'
|
||||
return { success: false, status, error: status.error || guidance }
|
||||
}
|
||||
|
||||
const oneBot = buildPersonalWechatOneBotRequest(request, fileBase64)
|
||||
try {
|
||||
const response = await requestWithTimeout(
|
||||
`http://${DEFAULT_HOST}${oneBot.endpoint}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(oneBot.body)
|
||||
},
|
||||
request.type === 'voice' ? 60_000 : REQUEST_TIMEOUT_MS
|
||||
)
|
||||
const responseText = await response.text()
|
||||
if (!response.ok) throw new Error(responseText || `HTTP ${response.status}`)
|
||||
const parsed = responseText ? (JSON.parse(responseText) as { status?: string }) : {}
|
||||
if (parsed.status && parsed.status !== 'ok') throw new Error(responseText)
|
||||
return { success: true, status: await this.getStatus() }
|
||||
} catch (error) {
|
||||
this.lastError = error instanceof Error ? error.message : String(error)
|
||||
const failedStatus = await this.getStatus()
|
||||
return {
|
||||
success: false,
|
||||
status: { ...failedStatus, state: 'error', error: this.lastError },
|
||||
error: `发送失败:${this.lastError}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async rebind(): Promise<PersonalWechatSenderStatus> {
|
||||
const preflight = await this.preflight()
|
||||
if (!preflight.runtime || !preflight.status.configPath || !preflight.status.wechatPid) {
|
||||
return preflight.status
|
||||
}
|
||||
const currentStatus = await this.getStatus()
|
||||
const oneBot = await readOneBotProcessInfo()
|
||||
if (
|
||||
oneBot?.boundWechatPid === preflight.status.wechatPid &&
|
||||
currentStatus.attachReady &&
|
||||
currentStatus.baseAddressReady &&
|
||||
currentStatus.textHookInstalled &&
|
||||
currentStatus.imageHookInstalled &&
|
||||
(!preflight.status.imagePath || Boolean(oneBot.imagePath)) &&
|
||||
currentStatus.state !== 'error'
|
||||
) {
|
||||
return {
|
||||
...currentStatus,
|
||||
message: '当前 OneBot 已绑定此微信进程,无需重复注入'
|
||||
}
|
||||
}
|
||||
if (oneBot) await terminateOneBot(oneBot)
|
||||
this.child = null
|
||||
this.startPromise = null
|
||||
this.lastError = ''
|
||||
let status = await this.startRuntime()
|
||||
const retryableHookFailure =
|
||||
status.state === 'error' &&
|
||||
/unable to intercept function|cannot find ['"]req2buf|hook 初始化失败/i.test(
|
||||
`${status.error || ''} ${status.message || ''}`
|
||||
)
|
||||
if (!retryableHookFailure) return status
|
||||
const failedOneBot = await readOneBotProcessInfo()
|
||||
if (failedOneBot) await terminateOneBot(failedOneBot)
|
||||
this.child = null
|
||||
this.lastError = ''
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_500))
|
||||
status = await this.startRuntime()
|
||||
return status
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
const child = this.child
|
||||
this.child = null
|
||||
this.startPromise = null
|
||||
// A second Attach to the same WeChat process is unstable. Leave OneBot alive;
|
||||
// it monitors the WeChat PID and exits when that process ends.
|
||||
if (child && child.exitCode === null) child.unref()
|
||||
}
|
||||
|
||||
async terminate(): Promise<void> {
|
||||
const oneBot = await readOneBotProcessInfo()
|
||||
if (oneBot) await terminateOneBot(oneBot)
|
||||
this.child = null
|
||||
this.startPromise = null
|
||||
this.lastError = ''
|
||||
}
|
||||
|
||||
private async ensureRunning(): Promise<PersonalWechatSenderStatus> {
|
||||
const currentStatus = await this.getStatus()
|
||||
if (currentStatus.state === 'online' || currentStatus.state === 'hook_not_ready') {
|
||||
return currentStatus
|
||||
}
|
||||
if (this.startPromise) return this.startPromise
|
||||
this.startPromise = this.startRuntime().finally(() => {
|
||||
this.startPromise = null
|
||||
})
|
||||
return this.startPromise
|
||||
}
|
||||
|
||||
private async startRuntime(): Promise<PersonalWechatSenderStatus> {
|
||||
const preflight = await this.preflight()
|
||||
if (!preflight.runtime || !preflight.status.configPath) {
|
||||
return preflight.status
|
||||
}
|
||||
|
||||
const pid = preflight.status.wechatPid
|
||||
const imagePath = findWechatImagePath()
|
||||
this.lastError = ''
|
||||
const child = spawn(
|
||||
preflight.runtime.executable,
|
||||
[
|
||||
'-type=local',
|
||||
`-receive_host=${DEFAULT_HOST}`,
|
||||
`-wechat_conf=${preflight.status.configPath}`,
|
||||
`-wechat_pid=${pid}`,
|
||||
...(imagePath ? [`-image_path=${imagePath}`] : []),
|
||||
'-send_interval=1000',
|
||||
'-log_level=info'
|
||||
],
|
||||
{
|
||||
cwd: preflight.runtime.workingDirectory,
|
||||
detached: true,
|
||||
stdio: 'ignore',
|
||||
windowsHide: true,
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: buildRuntimePath(),
|
||||
PYTHONPATH: buildRuntimePythonPath(preflight.runtime.root)
|
||||
}
|
||||
}
|
||||
)
|
||||
this.child = child
|
||||
child.unref()
|
||||
child.once('error', (error) => {
|
||||
this.lastError = error.message
|
||||
})
|
||||
child.once('exit', (code) => {
|
||||
if (this.child === child) this.child = null
|
||||
if (code && !this.lastError) this.lastError = `发送服务退出(code=${code})`
|
||||
})
|
||||
|
||||
const startedAt = Date.now()
|
||||
while (Date.now() - startedAt < START_TIMEOUT_MS) {
|
||||
const status = await this.getStatus()
|
||||
if (status.state === 'online') return status
|
||||
if (status.state === 'hook_not_ready' && status.attachReady && status.baseAddressReady) {
|
||||
return status
|
||||
}
|
||||
if (status.state === 'error') return status
|
||||
if (this.child?.exitCode !== null && this.child?.exitCode !== undefined) break
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
}
|
||||
const status = await this.preflight()
|
||||
return {
|
||||
...status.status,
|
||||
state: 'error',
|
||||
canSend: false,
|
||||
message: '个人微信发送服务启动失败',
|
||||
error: this.lastError || '启动超时,请查看应用日志'
|
||||
}
|
||||
}
|
||||
|
||||
private async preflight(): Promise<PreflightResult> {
|
||||
const base = {
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
sipDisabled: false,
|
||||
wechatRunning: false,
|
||||
runtimeReady: false,
|
||||
endpoint: DEFAULT_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
|
||||
}
|
||||
if (process.platform !== 'darwin' || process.arch !== 'arm64') {
|
||||
return {
|
||||
status: {
|
||||
...base,
|
||||
state: 'unsupported_platform',
|
||||
message: '个人微信测试发送当前仅支持 Apple Silicon Mac'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const [sipDisabled, wechatPid] = await Promise.all([isSipDisabled(), readWechatPid()])
|
||||
if (!wechatPid) {
|
||||
return {
|
||||
status: {
|
||||
...base,
|
||||
sipDisabled,
|
||||
state: 'wechat_not_running',
|
||||
message: '请先启动并登录 macOS 微信'
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!sipDisabled) {
|
||||
return {
|
||||
status: {
|
||||
...base,
|
||||
wechatRunning: true,
|
||||
wechatPid,
|
||||
state: 'sip_enabled',
|
||||
message: '当前 SIP 未关闭,无法直接连接微信进程'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let wechatVersion = ''
|
||||
try {
|
||||
wechatVersion = await readWechatVersion()
|
||||
} catch (error) {
|
||||
return {
|
||||
status: {
|
||||
...base,
|
||||
sipDisabled,
|
||||
wechatRunning: true,
|
||||
wechatPid,
|
||||
state: 'error',
|
||||
message: '无法读取微信精确版本',
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const runtime = findPersonalWechatRuntime()
|
||||
if (!runtime) {
|
||||
return {
|
||||
status: {
|
||||
...base,
|
||||
sipDisabled,
|
||||
wechatRunning: true,
|
||||
wechatPid,
|
||||
wechatVersion,
|
||||
state: 'runtime_missing',
|
||||
message: '个人微信发送组件尚未安装,请前往“设置 → 智能能力 → 文字转语音”下载'
|
||||
}
|
||||
}
|
||||
}
|
||||
const configPath = join(runtime.configDirectory, toConfigFileName(wechatVersion))
|
||||
if (!existsSync(configPath)) {
|
||||
return {
|
||||
runtime,
|
||||
status: {
|
||||
...base,
|
||||
sipDisabled,
|
||||
wechatRunning: true,
|
||||
wechatPid,
|
||||
wechatVersion,
|
||||
runtimeReady: true,
|
||||
executablePath: runtime.executable,
|
||||
state: 'unsupported_version',
|
||||
message: `当前微信版本 ${wechatVersion} 暂不支持,请前往文字转语音设置查看支持的版本`,
|
||||
error: `缺少 ${configPath}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const imagePath = findWechatImagePath()
|
||||
return {
|
||||
runtime,
|
||||
status: {
|
||||
...base,
|
||||
sipDisabled,
|
||||
wechatRunning: true,
|
||||
wechatPid,
|
||||
wechatVersion,
|
||||
runtimeReady: true,
|
||||
executablePath: runtime.executable,
|
||||
configPath,
|
||||
...(imagePath ? { imagePath } : {}),
|
||||
state: this.child && this.child.exitCode === null ? 'starting' : 'stopped',
|
||||
message: this.lastError || '尚未绑定当前微信,可点击“尝试重新绑定”'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async isEndpointOnline(): Promise<boolean> {
|
||||
try {
|
||||
const [host, portText] = DEFAULT_HOST.split(':')
|
||||
const port = Number(portText)
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const socket = createConnection({ host, port })
|
||||
const timer = setTimeout(() => {
|
||||
socket.destroy()
|
||||
reject(new Error('timeout'))
|
||||
}, 800)
|
||||
socket.once('connect', () => {
|
||||
clearTimeout(timer)
|
||||
socket.destroy()
|
||||
resolve()
|
||||
})
|
||||
socket.once('error', (error) => {
|
||||
clearTimeout(timer)
|
||||
socket.destroy()
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private readHookReadiness(
|
||||
runtime?: RuntimeLayout
|
||||
): ReturnType<typeof parsePersonalWechatHookLog> {
|
||||
if (!runtime || !existsSync(runtime.logPath)) {
|
||||
return {
|
||||
readiness: 'unknown',
|
||||
attached: false,
|
||||
textHookInstalled: false,
|
||||
textHookReady: false,
|
||||
imageHookInstalled: false,
|
||||
imageHookReady: false,
|
||||
messageListenerReady: false
|
||||
}
|
||||
}
|
||||
try {
|
||||
return parsePersonalWechatHookLog(readFileSync(runtime.logPath, 'utf8'))
|
||||
} catch {
|
||||
return {
|
||||
readiness: 'unknown',
|
||||
attached: false,
|
||||
textHookInstalled: false,
|
||||
textHookReady: false,
|
||||
imageHookInstalled: false,
|
||||
imageHookReady: false,
|
||||
messageListenerReady: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const personalWechatSendService = new PersonalWechatSendService()
|
||||
@@ -2,6 +2,7 @@ import { app } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import type { TextToSpeechModel } from '../../shared/text-to-speech'
|
||||
|
||||
/**
|
||||
* 把 V3 时代的 "...\\Documents\\WeChat Files" 路径重定向到
|
||||
@@ -36,6 +37,8 @@ export interface AppSettings {
|
||||
appearanceTheme: 'system' | 'light' | 'dark'
|
||||
compactMode: boolean
|
||||
showStartupProgress: boolean
|
||||
ttsSelectedVoiceId: string
|
||||
ttsModel: TextToSpeechModel
|
||||
}
|
||||
|
||||
function getDefaultDbRoot(): string {
|
||||
@@ -135,7 +138,9 @@ const DEFAULT_SETTINGS: AppSettings = {
|
||||
autoLoginPreferenceSet: false,
|
||||
appearanceTheme: 'system',
|
||||
compactMode: false,
|
||||
showStartupProgress: true
|
||||
showStartupProgress: true,
|
||||
ttsSelectedVoiceId: '',
|
||||
ttsModel: 's2.1-pro-free'
|
||||
}
|
||||
|
||||
const SETTINGS_FILE = path.join(
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
import { app } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import { randomUUID } from 'crypto'
|
||||
import type {
|
||||
ListTextToSpeechVoicesRequest,
|
||||
ListTextToSpeechVoicesResult,
|
||||
SaveTextToSpeechSettingsRequest,
|
||||
SynthesizeTextToSpeechRequest,
|
||||
SynthesizeTextToSpeechResult,
|
||||
TextToSpeechKeySource,
|
||||
TextToSpeechModel,
|
||||
TextToSpeechSettingsResult,
|
||||
TextToSpeechVoice
|
||||
} from '../../shared/text-to-speech'
|
||||
import { AIProviderKeyStore } from '../ai-provider-key-store'
|
||||
import { loadSettings, updateSettings } from './settings-store'
|
||||
|
||||
const FISH_AUDIO_KEY_ID = 'fish-audio-tts'
|
||||
const FISH_AUDIO_BASE_URL = 'https://api.fish.audio'
|
||||
const FISH_AUDIO_PUBLIC_ASSET_URL = 'https://public-platform.r2.fish.audio/'
|
||||
const DEFAULT_PAGE_SIZE = 24
|
||||
const MAX_PAGE_SIZE = 100
|
||||
const GENERATED_AUDIO_MAX_AGE_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
interface FishAudioModelEntity {
|
||||
_id: string
|
||||
type: 'svc' | 'tts'
|
||||
title: string
|
||||
description?: string
|
||||
cover_image?: string
|
||||
state: 'created' | 'training' | 'trained' | 'failed'
|
||||
tags?: string[]
|
||||
languages?: string[]
|
||||
default_text?: string
|
||||
samples?: Array<{ title: string; text: string; task_id: string; audio: string }>
|
||||
task_count?: number
|
||||
like_count?: number
|
||||
mark_count?: number
|
||||
author?: { _id: string; nickname: string; avatar: string }
|
||||
}
|
||||
|
||||
interface FishAudioModelListResponse {
|
||||
total: number
|
||||
items: FishAudioModelEntity[]
|
||||
has_more?: boolean | null
|
||||
}
|
||||
|
||||
export class TextToSpeechSettingsService {
|
||||
constructor(private readonly keyStore = new AIProviderKeyStore()) {}
|
||||
|
||||
get(): TextToSpeechSettingsResult {
|
||||
const resolved = this.resolveKey()
|
||||
const settings = loadSettings()
|
||||
return {
|
||||
success: resolved.success,
|
||||
settings: {
|
||||
provider: 'fish-audio',
|
||||
hasApiKey: Boolean(resolved.key),
|
||||
hasStoredApiKey: resolved.hasStoredApiKey,
|
||||
hasEnvironmentApiKey: resolved.hasEnvironmentApiKey,
|
||||
keySource: resolved.source,
|
||||
encryptionAvailable: resolved.encryptionAvailable,
|
||||
selectedVoiceId: normalizeSelectedVoiceId(settings.ttsSelectedVoiceId),
|
||||
outputFormat: 'mp3',
|
||||
model: normalizeModel(settings.ttsModel),
|
||||
phase: 'ready'
|
||||
},
|
||||
voices: [],
|
||||
error: resolved.error
|
||||
}
|
||||
}
|
||||
|
||||
save(request: SaveTextToSpeechSettingsRequest): TextToSpeechSettingsResult {
|
||||
const apiKey = request.apiKey?.trim()
|
||||
if (request.clearApiKey) {
|
||||
const cleared = this.keyStore.clear(FISH_AUDIO_KEY_ID)
|
||||
if (!cleared.success) return { ...this.get(), success: false, error: cleared.error }
|
||||
} else if (apiKey) {
|
||||
const saved = this.keyStore.save(FISH_AUDIO_KEY_ID, apiKey)
|
||||
if (!saved.success) return { ...this.get(), success: false, error: saved.error }
|
||||
}
|
||||
|
||||
const patch: { ttsSelectedVoiceId?: string; ttsModel?: TextToSpeechModel } = {}
|
||||
if (request.selectedVoiceId !== undefined) {
|
||||
patch.ttsSelectedVoiceId = request.selectedVoiceId.trim()
|
||||
}
|
||||
if (request.model !== undefined) patch.ttsModel = normalizeModel(request.model)
|
||||
if (Object.keys(patch).length) updateSettings(patch)
|
||||
return this.get()
|
||||
}
|
||||
|
||||
async listVoices(
|
||||
request: ListTextToSpeechVoicesRequest = {}
|
||||
): Promise<ListTextToSpeechVoicesResult> {
|
||||
const pageNumber = clampInteger(request.pageNumber, 1, Number.MAX_SAFE_INTEGER, 1)
|
||||
const pageSize = clampInteger(request.pageSize, 1, MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE)
|
||||
const resolved = this.resolveKey()
|
||||
if (!resolved.key) {
|
||||
return {
|
||||
success: false,
|
||||
items: [],
|
||||
total: 0,
|
||||
pageNumber,
|
||||
pageSize,
|
||||
hasMore: false,
|
||||
error: resolved.error || '请先配置语音服务 API Key'
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL('/model', FISH_AUDIO_BASE_URL)
|
||||
url.searchParams.set('page_size', String(pageSize))
|
||||
url.searchParams.set('page_number', String(pageNumber))
|
||||
url.searchParams.set('sort_by', 'score')
|
||||
if (request.title?.trim()) url.searchParams.set('title', request.title.trim())
|
||||
if (request.language?.trim()) url.searchParams.set('language', request.language.trim())
|
||||
for (const tag of request.tags || []) {
|
||||
if (tag.trim()) url.searchParams.append('tag', tag.trim())
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${resolved.key}` },
|
||||
signal: AbortSignal.timeout(30_000)
|
||||
})
|
||||
if (!response.ok) throw await fishAudioError(response)
|
||||
const payload = (await response.json()) as FishAudioModelListResponse
|
||||
let items = payload.items
|
||||
.filter((model) => model.type === 'tts' && model.state === 'trained')
|
||||
.map(toVoice)
|
||||
|
||||
const selectedVoiceId = normalizeSelectedVoiceId(loadSettings().ttsSelectedVoiceId)
|
||||
if (
|
||||
pageNumber === 1 &&
|
||||
!request.title?.trim() &&
|
||||
!(request.tags || []).length &&
|
||||
selectedVoiceId
|
||||
) {
|
||||
if (!items.some((item) => item.id === selectedVoiceId)) {
|
||||
const selected = await this.getVoice(selectedVoiceId, resolved.key)
|
||||
if (selected) items = [selected, ...items]
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
items,
|
||||
total: payload.total,
|
||||
pageNumber,
|
||||
pageSize,
|
||||
hasMore: payload.has_more ?? pageNumber * pageSize < payload.total
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
items: [],
|
||||
total: 0,
|
||||
pageNumber,
|
||||
pageSize,
|
||||
hasMore: false,
|
||||
error: safeFishAudioError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async synthesize(request: SynthesizeTextToSpeechRequest): Promise<SynthesizeTextToSpeechResult> {
|
||||
const text = request.text.trim()
|
||||
const referenceId = request.referenceId.trim()
|
||||
if (!text) return { success: false, error: '请输入要生成语音的文字' }
|
||||
if (text.length > 1000) return { success: false, error: '单次生成文字不能超过 1000 个字符' }
|
||||
if (!referenceId) return { success: false, error: '请先选择音色' }
|
||||
|
||||
const resolved = this.resolveKey()
|
||||
if (!resolved.key) {
|
||||
return {
|
||||
success: false,
|
||||
error: resolved.error || '请先配置语音服务 API Key'
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${FISH_AUDIO_BASE_URL}/v1/tts`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${resolved.key}`,
|
||||
'Content-Type': 'application/json',
|
||||
model: normalizeModel(loadSettings().ttsModel)
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text,
|
||||
reference_id: referenceId,
|
||||
format: 'mp3',
|
||||
mp3_bitrate: 128,
|
||||
latency: 'normal',
|
||||
normalize: true
|
||||
}),
|
||||
signal: AbortSignal.timeout(120_000)
|
||||
})
|
||||
if (!response.ok) throw await fishAudioError(response)
|
||||
const audio = Buffer.from(await response.arrayBuffer())
|
||||
if (audio.length < 128) throw new Error('语音服务返回的音频为空')
|
||||
|
||||
const directory = this.generatedAudioDirectory()
|
||||
fs.ensureDirSync(directory)
|
||||
this.cleanupGeneratedAudio(directory)
|
||||
const filePath = path.join(directory, `fish-audio-${Date.now()}-${randomUUID()}.mp3`)
|
||||
fs.writeFileSync(filePath, audio, { mode: 0o600 })
|
||||
return {
|
||||
success: true,
|
||||
filePath,
|
||||
audioDataUrl: `data:audio/mpeg;base64,${audio.toString('base64')}`
|
||||
}
|
||||
} catch (error) {
|
||||
return { success: false, error: safeFishAudioError(error) }
|
||||
}
|
||||
}
|
||||
|
||||
removeGeneratedAudio(filePath: string): { success: boolean; error?: string } {
|
||||
const directory = this.generatedAudioDirectory()
|
||||
const resolvedPath = path.resolve(filePath)
|
||||
if (!resolvedPath.startsWith(`${path.resolve(directory)}${path.sep}`)) {
|
||||
return { success: false, error: '拒绝删除非 Fish Audio 临时文件' }
|
||||
}
|
||||
try {
|
||||
fs.removeSync(resolvedPath)
|
||||
return { success: true }
|
||||
} catch {
|
||||
return { success: false, error: '临时语音文件清理失败' }
|
||||
}
|
||||
}
|
||||
|
||||
private resolveKey(): {
|
||||
success: boolean
|
||||
key?: string
|
||||
source: TextToSpeechKeySource
|
||||
hasStoredApiKey: boolean
|
||||
hasEnvironmentApiKey: boolean
|
||||
encryptionAvailable: boolean
|
||||
error?: string
|
||||
} {
|
||||
const stored = this.keyStore.get(FISH_AUDIO_KEY_ID)
|
||||
const environmentKey = String(process.env.FISH_API_KEY || '').trim()
|
||||
const storedKey = stored.key?.trim()
|
||||
const key = storedKey || environmentKey || undefined
|
||||
return {
|
||||
success: stored.success || Boolean(environmentKey),
|
||||
key,
|
||||
source: storedKey ? 'secure-storage' : environmentKey ? 'environment' : 'missing',
|
||||
hasStoredApiKey: Boolean(storedKey),
|
||||
hasEnvironmentApiKey: Boolean(environmentKey),
|
||||
encryptionAvailable: stored.available,
|
||||
error: key ? undefined : stored.error
|
||||
}
|
||||
}
|
||||
|
||||
private async getVoice(id: string, key: string): Promise<TextToSpeechVoice | null> {
|
||||
try {
|
||||
const response = await fetch(`${FISH_AUDIO_BASE_URL}/model/${encodeURIComponent(id)}`, {
|
||||
headers: { Authorization: `Bearer ${key}` },
|
||||
signal: AbortSignal.timeout(15_000)
|
||||
})
|
||||
if (!response.ok) return null
|
||||
const model = (await response.json()) as FishAudioModelEntity
|
||||
return model.type === 'tts' && model.state === 'trained' ? toVoice(model) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private generatedAudioDirectory(): string {
|
||||
return path.join(app.getPath('temp'), 'wechatexplorer-fish-audio')
|
||||
}
|
||||
|
||||
private cleanupGeneratedAudio(directory: string): void {
|
||||
try {
|
||||
const now = Date.now()
|
||||
for (const name of fs.readdirSync(directory)) {
|
||||
const candidate = path.join(directory, name)
|
||||
if (!name.startsWith('fish-audio-') || !name.endsWith('.mp3')) continue
|
||||
if (now - fs.statSync(candidate).mtimeMs > GENERATED_AUDIO_MAX_AGE_MS)
|
||||
fs.removeSync(candidate)
|
||||
}
|
||||
} catch {
|
||||
// 临时文件清理失败不应阻断当前语音生成。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toVoice(model: FishAudioModelEntity): TextToSpeechVoice {
|
||||
const sample = model.samples?.find((item) => item.audio) || model.samples?.[0]
|
||||
return {
|
||||
id: model._id,
|
||||
name: model.title || '未命名音色',
|
||||
description: model.description || sample?.text || '公开音色',
|
||||
tags: Array.isArray(model.tags) ? model.tags : [],
|
||||
languages: Array.isArray(model.languages) ? model.languages : [],
|
||||
source: 'fish-audio',
|
||||
coverImage: resolvePublicAssetUrl(model.cover_image || model.author?.avatar),
|
||||
previewUrl: sample?.audio || undefined,
|
||||
previewText: sample?.text || model.default_text || undefined,
|
||||
authorName: model.author?.nickname || undefined,
|
||||
taskCount: model.task_count,
|
||||
likeCount: model.like_count,
|
||||
markCount: model.mark_count
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePublicAssetUrl(value?: string): string | undefined {
|
||||
const normalized = String(value || '').trim()
|
||||
if (!normalized) return undefined
|
||||
if (/^https?:\/\//i.test(normalized)) return normalized
|
||||
if (normalized.startsWith('//')) return `https:${normalized}`
|
||||
return new URL(normalized.replace(/^\/+/, ''), FISH_AUDIO_PUBLIC_ASSET_URL).toString()
|
||||
}
|
||||
|
||||
function normalizeSelectedVoiceId(value: string): string {
|
||||
const normalized = String(value || '').trim()
|
||||
return normalized.startsWith('demo-') ? '' : normalized
|
||||
}
|
||||
|
||||
function normalizeModel(value: unknown): TextToSpeechModel {
|
||||
return value === 's2.1-pro' ? 's2.1-pro' : 's2.1-pro-free'
|
||||
}
|
||||
|
||||
function clampInteger(value: unknown, min: number, max: number, fallback: number): number {
|
||||
const parsed = Number(value)
|
||||
if (!Number.isFinite(parsed)) return fallback
|
||||
return Math.min(max, Math.max(min, Math.floor(parsed)))
|
||||
}
|
||||
|
||||
async function fishAudioError(response: Response): Promise<Error> {
|
||||
let detail = ''
|
||||
try {
|
||||
const payload = (await response.json()) as
|
||||
| { status?: number; message?: string }
|
||||
| Array<{ msg?: string }>
|
||||
detail = Array.isArray(payload)
|
||||
? payload
|
||||
.map((item) => item.msg)
|
||||
.filter(Boolean)
|
||||
.join(';')
|
||||
: payload.message || ''
|
||||
} catch {
|
||||
detail = await response.text().catch(() => '')
|
||||
}
|
||||
if (response.status === 401) return new Error('API Key 无效或已失效')
|
||||
if (response.status === 402) return new Error('语音服务余额不足')
|
||||
if (response.status === 404) return new Error('所选音色不存在或不可访问')
|
||||
if (response.status === 422) return new Error(detail || '语音生成参数不正确')
|
||||
if (response.status === 503) return new Error('语音服务暂时不可用,请稍后重试')
|
||||
return new Error(detail || `语音服务请求失败(HTTP ${response.status})`)
|
||||
}
|
||||
|
||||
function safeFishAudioError(error: unknown): string {
|
||||
if (error instanceof DOMException && error.name === 'TimeoutError') return '语音服务请求超时'
|
||||
if (error instanceof Error) return error.message
|
||||
return '语音服务请求失败'
|
||||
}
|
||||
Reference in new issue
Block a user