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
05b881d79e
commit
f47af8024f
13 files changed
+1048
-46
No files matched your search
+54
-6
@@ -161,6 +161,10 @@ import {
|
||||
type MessageInsertCapability
|
||||
} from './services/msg-insert-capability-service'
|
||||
import { resolveExternalComponent } from './services/external-component-locator'
|
||||
import {
|
||||
cleanupMacWechatResidualProcesses,
|
||||
inspectMacWechatResidualProcesses
|
||||
} from './services/mac-wechat-residual-cleanup'
|
||||
import {
|
||||
isDefinitelyBlocked,
|
||||
isEntitlementBlocked,
|
||||
@@ -317,10 +321,7 @@ async function attachCapability(
|
||||
}
|
||||
}
|
||||
switches.recall_notice = applyPresentation('recall_notice', switches.recall_notice)!
|
||||
switches.group_exit_notice = applyPresentation(
|
||||
'group_exit_notice',
|
||||
switches.group_exit_notice
|
||||
)!
|
||||
switches.group_exit_notice = applyPresentation('group_exit_notice', switches.group_exit_notice)!
|
||||
return {
|
||||
...snapshot,
|
||||
switches,
|
||||
@@ -1982,7 +1983,8 @@ app.whenReady().then(async () => {
|
||||
* 刻意不返回资源密钥、完整 XML、fileid 或任何 CDN 凭据。
|
||||
*/
|
||||
ipcMain.handle(
|
||||
'image:getDebugInfo', async (_, request: ImageDebugInfoRequest): Promise<ImageDebugInfoResult> => {
|
||||
'image:getDebugInfo',
|
||||
async (_, request: ImageDebugInfoRequest): Promise<ImageDebugInfoResult> => {
|
||||
try {
|
||||
const service = ensureImageDecryptService()
|
||||
const self = chat.getSelfAccountInfo()
|
||||
@@ -2003,7 +2005,9 @@ app.whenReady().then(async () => {
|
||||
|
||||
// 复用真实选图逻辑;找不到就是 null,不根据文件名猜。
|
||||
const filePath = service
|
||||
? service.findImageFile(md5 || undefined, datName || undefined, { sessionId: sessionId || undefined })
|
||||
? service.findImageFile(md5 || undefined, datName || undefined, {
|
||||
sessionId: sessionId || undefined
|
||||
})
|
||||
: null
|
||||
const quality = filePath ? toDebugQuality(imageFileQuality(filePath)) : 'unknown'
|
||||
const relativePath =
|
||||
@@ -3466,6 +3470,50 @@ app.whenReady().then(async () => {
|
||||
ipcMain.handle('wechat-personal:getMacSendRuntimeAvailability', () =>
|
||||
macWechatRuntimeManager.getSendRuntimeAvailability()
|
||||
)
|
||||
ipcMain.handle('wechat-personal:startMacSendRuntime', () => {
|
||||
if (process.platform !== 'darwin') throw new Error('仅 macOS 支持微信发送组件')
|
||||
return macWechatRuntimeManager.startAfterResidualCleanup()
|
||||
})
|
||||
ipcMain.handle('wechat-personal:listMacResidualProcesses', () =>
|
||||
inspectMacWechatResidualProcesses()
|
||||
)
|
||||
ipcMain.handle('wechat-personal:cleanupMacResidualProcesses', async (_, pids: unknown) => {
|
||||
if (process.platform !== 'darwin') throw new Error('仅 macOS 支持清理微信残留进程')
|
||||
if (!Array.isArray(pids)) throw new Error('清理目标无效')
|
||||
const requestedTargets = pids.filter(
|
||||
(target): target is { pid: number; confirmationToken: string } =>
|
||||
Boolean(target) &&
|
||||
typeof target === 'object' &&
|
||||
Number.isSafeInteger((target as { pid?: unknown }).pid) &&
|
||||
typeof (target as { confirmationToken?: unknown }).confirmationToken === 'string'
|
||||
)
|
||||
if (requestedTargets.length === 0) throw new Error('没有确认的清理目标')
|
||||
const currentTargets = await inspectMacWechatResidualProcesses()
|
||||
const confirmedTargets = requestedTargets.filter((requested) =>
|
||||
currentTargets.some(
|
||||
(current) =>
|
||||
current.pid === requested.pid && current.confirmationToken === requested.confirmationToken
|
||||
)
|
||||
)
|
||||
if (confirmedTargets.length === 0) {
|
||||
return { stopped: [], remaining: currentTargets }
|
||||
}
|
||||
let runtimeStopped = false
|
||||
const result = await cleanupMacWechatResidualProcesses(
|
||||
confirmedTargets,
|
||||
undefined,
|
||||
(targets) => {
|
||||
if (
|
||||
macWechatRuntimeManager.getPort() === 4290 &&
|
||||
targets.some((target) => target.targets.includes('port_4290'))
|
||||
) {
|
||||
macWechatRuntimeManager.prepareForResidualCleanup()
|
||||
runtimeStopped = true
|
||||
}
|
||||
}
|
||||
)
|
||||
return { ...result, runtimeStopped }
|
||||
})
|
||||
ipcMain.handle('wechat-personal:refreshMacLicense', () =>
|
||||
macWechatRuntimeManager.refreshMacLicense()
|
||||
)
|
||||
|
||||
@@ -230,7 +230,12 @@ function builtInTemplate(template: ReportTemplateDefinition): InstalledReportTem
|
||||
}
|
||||
|
||||
export class ReportTemplateService {
|
||||
private readonly directory = rootPath()
|
||||
/* 延迟到首次真正用到时再取 app.getPath('userData')。
|
||||
* 这个类在模块顶层被 new(见文件末尾),而 import 顺序一变,模块就可能
|
||||
* 在 electron.app 可用之前被 require —— 那时 app 是 undefined,getPath 直接抛。 */
|
||||
private get directory(): string {
|
||||
return rootPath()
|
||||
}
|
||||
|
||||
async list(): Promise<InstalledReportTemplate[]> {
|
||||
await fs.mkdir(path.join(this.directory, INSTALLED_DIR), { recursive: true })
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { promisify } from 'node:util'
|
||||
import type { MacWechatResidualProcess } from '../../shared/personal-wechat-mac-runtime'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
type PidCommandRunner = (
|
||||
executable: string,
|
||||
args: string[],
|
||||
options: { timeout: number }
|
||||
) => Promise<{ stdout: string }>
|
||||
|
||||
export interface MacWechatResidualCleanupDependencies {
|
||||
platform: NodeJS.Platform
|
||||
listWechatPids: () => Promise<number[]>
|
||||
listPortPids: () => Promise<number[]>
|
||||
processName: (pid: number) => Promise<string>
|
||||
processIdentity: (pid: number) => Promise<string>
|
||||
signal: (pid: number, signal: NodeJS.Signals) => void
|
||||
wait: (milliseconds: number) => Promise<void>
|
||||
}
|
||||
|
||||
export async function readPids(
|
||||
executable: string,
|
||||
args: string[],
|
||||
run: PidCommandRunner = async (file, commandArgs, options) =>
|
||||
execFileAsync(file, commandArgs, options)
|
||||
): Promise<number[]> {
|
||||
try {
|
||||
const { stdout } = await run(executable, args, { timeout: 4_000 })
|
||||
return stdout
|
||||
.split(/\s+/)
|
||||
.map(Number)
|
||||
.filter((pid) => Number.isSafeInteger(pid) && pid > 0)
|
||||
} catch (error) {
|
||||
const result = error as { code?: unknown; status?: unknown }
|
||||
if (result.code === 'ENOENT' || result.code === 1 || result.status === 1) return []
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const defaultDependencies: MacWechatResidualCleanupDependencies = {
|
||||
platform: process.platform,
|
||||
listWechatPids: async () => {
|
||||
const results = await Promise.all([
|
||||
readPids('/usr/bin/pgrep', ['-x', 'WeChat']),
|
||||
readPids('/usr/bin/pgrep', ['-x', 'Weixin'])
|
||||
])
|
||||
return [...new Set(results.flat())]
|
||||
},
|
||||
listPortPids: () => readPids('/usr/sbin/lsof', ['-nP', '-t', '-iTCP:4290', '-sTCP:LISTEN']),
|
||||
processName: async (pid) => {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('/bin/ps', ['-p', String(pid), '-o', 'comm='], {
|
||||
timeout: 2_000
|
||||
})
|
||||
return stdout.trim().split('/').pop() || 'unknown'
|
||||
} catch {
|
||||
return 'unknown'
|
||||
}
|
||||
},
|
||||
processIdentity: async (pid) => {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
'/bin/ps',
|
||||
['-p', String(pid), '-o', 'lstart=', '-o', 'comm='],
|
||||
{ timeout: 2_000 }
|
||||
)
|
||||
return createHash('sha256').update(stdout.trim()).digest('hex')
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
},
|
||||
signal: (pid, signal) => process.kill(pid, signal),
|
||||
wait: (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))
|
||||
}
|
||||
|
||||
interface ObservedTarget extends MacWechatResidualProcess {
|
||||
confirmationToken: string
|
||||
}
|
||||
|
||||
function mergeTargets(
|
||||
wechatPids: number[],
|
||||
portPids: number[],
|
||||
processNames: Map<number, string>,
|
||||
processIdentities: Map<number, string>
|
||||
): ObservedTarget[] {
|
||||
const targets = new Map<number, Set<'wechat' | 'port_4290'>>()
|
||||
for (const pid of wechatPids) {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) continue
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'port_4290'>()
|
||||
reasons.add('wechat')
|
||||
targets.set(pid, reasons)
|
||||
}
|
||||
for (const pid of portPids) {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) continue
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'port_4290'>()
|
||||
reasons.add('port_4290')
|
||||
targets.set(pid, reasons)
|
||||
}
|
||||
return [...targets.entries()]
|
||||
.sort(([first], [second]) => first - second)
|
||||
.map(([pid, reasons]) => ({
|
||||
pid,
|
||||
name: processNames.get(pid) || 'unknown',
|
||||
targets: [...reasons].sort(),
|
||||
confirmationToken: processIdentities.get(pid) || ''
|
||||
}))
|
||||
}
|
||||
|
||||
async function inspectObservedTargets(
|
||||
dependencies: MacWechatResidualCleanupDependencies
|
||||
): Promise<ObservedTarget[]> {
|
||||
if (dependencies.platform !== 'darwin') return []
|
||||
const [rawWechatPids, rawPortPids] = await Promise.all([
|
||||
dependencies.listWechatPids(),
|
||||
dependencies.listPortPids()
|
||||
])
|
||||
const wechatPids = rawWechatPids.filter((pid) => pid !== process.pid)
|
||||
const portPids = rawPortPids.filter((pid) => pid !== process.pid)
|
||||
const pids = [...new Set([...wechatPids, ...portPids])].filter(
|
||||
(pid) => Number.isSafeInteger(pid) && pid > 0
|
||||
)
|
||||
const [names, identities] = await Promise.all([
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processName(pid)] as const)),
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processIdentity(pid)] as const))
|
||||
])
|
||||
return mergeTargets(wechatPids, portPids, new Map(names), new Map(identities))
|
||||
}
|
||||
|
||||
export async function inspectMacWechatResidualProcesses(
|
||||
dependencies: MacWechatResidualCleanupDependencies = defaultDependencies
|
||||
): Promise<MacWechatResidualProcess[]> {
|
||||
return inspectObservedTargets(dependencies)
|
||||
}
|
||||
|
||||
export async function cleanupMacWechatResidualProcesses(
|
||||
confirmedTargets: Array<Pick<MacWechatResidualProcess, 'pid' | 'confirmationToken'>>,
|
||||
dependencies: MacWechatResidualCleanupDependencies = defaultDependencies,
|
||||
onTargetsConfirmed?: (targets: MacWechatResidualProcess[]) => void
|
||||
): Promise<{ stopped: MacWechatResidualProcess[]; remaining: MacWechatResidualProcess[] }> {
|
||||
if (dependencies.platform !== 'darwin') return { stopped: [], remaining: [] }
|
||||
const confirmed = new Map(
|
||||
confirmedTargets
|
||||
.filter(
|
||||
(target) =>
|
||||
target.pid !== process.pid &&
|
||||
Number.isSafeInteger(target.pid) &&
|
||||
target.pid > 0 &&
|
||||
typeof target.confirmationToken === 'string' &&
|
||||
target.confirmationToken.length > 0
|
||||
)
|
||||
.map((target) => [target.pid, target.confirmationToken])
|
||||
)
|
||||
const current = await inspectObservedTargets(dependencies)
|
||||
const selected = current.filter(
|
||||
(target) => confirmed.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
if (selected.length === 0) {
|
||||
return {
|
||||
stopped: [],
|
||||
remaining: current.filter((target) => confirmed.has(target.pid))
|
||||
}
|
||||
}
|
||||
let cleanupTargetsNotified = false
|
||||
const signalMatchingTarget = async (
|
||||
target: ObservedTarget,
|
||||
expectedIdentity: string,
|
||||
signal: NodeJS.Signals
|
||||
): Promise<void> => {
|
||||
const identity = await dependencies.processIdentity(target.pid)
|
||||
if (!expectedIdentity || identity !== expectedIdentity) return
|
||||
try {
|
||||
dependencies.signal(target.pid, signal)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error
|
||||
}
|
||||
if (target.targets.includes('port_4290') && !cleanupTargetsNotified) {
|
||||
cleanupTargetsNotified = true
|
||||
onTargetsConfirmed?.([target])
|
||||
}
|
||||
}
|
||||
|
||||
for (const target of selected.filter((item) => item.targets.includes('wechat'))) {
|
||||
await signalMatchingTarget(target, confirmed.get(target.pid) || '', 'SIGTERM')
|
||||
}
|
||||
if (selected.some((item) => item.targets.includes('wechat'))) await dependencies.wait(1_000)
|
||||
|
||||
let remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid)
|
||||
)
|
||||
for (const target of remaining) {
|
||||
const selectedTarget = selected.find((item) => item.pid === target.pid)
|
||||
if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue
|
||||
await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGTERM')
|
||||
}
|
||||
if (remaining.length > 0) await dependencies.wait(1_000)
|
||||
|
||||
remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid)
|
||||
)
|
||||
for (const target of remaining) {
|
||||
const selectedTarget = selected.find((item) => item.pid === target.pid)
|
||||
if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue
|
||||
await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGKILL')
|
||||
}
|
||||
if (remaining.length > 0) await dependencies.wait(250)
|
||||
remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid)
|
||||
)
|
||||
return {
|
||||
stopped: selected
|
||||
.filter((target) => !remaining.some((item) => item.pid === target.pid))
|
||||
.map((target) => target),
|
||||
remaining
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,10 @@ import {
|
||||
* auto-binding, that path dead-ends in a 20s attach timeout every time.
|
||||
*/
|
||||
|
||||
const PORT = 4290
|
||||
/* 默认 4290。进程会 fork 继承监听 fd(CLOEXEC 只挡 exec),
|
||||
* host 崩溃后孤儿进程仍扣着端口,新 host bind 失败会返回 1 无限重启。
|
||||
* 被占用时用 TM_WECHAT_HOST_PORT 指到备用端口。 */
|
||||
const PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290
|
||||
const HOST = '127.0.0.1'
|
||||
const START_TIMEOUT_MS = 15_000
|
||||
const REQUEST_TIMEOUT_MS = 30_000
|
||||
@@ -199,6 +202,7 @@ class MacWechatRuntimeManager {
|
||||
private manifest: MacWechatRuntimeManifest | null = null
|
||||
private lastError: string | null = null
|
||||
private restartTimer: NodeJS.Timeout | null = null
|
||||
private manuallyStopped = false
|
||||
|
||||
getPort(): number {
|
||||
return PORT
|
||||
@@ -216,6 +220,22 @@ class MacWechatRuntimeManager {
|
||||
}
|
||||
}
|
||||
|
||||
prepareForResidualCleanup(): void {
|
||||
if (this.restartTimer) {
|
||||
clearTimeout(this.restartTimer)
|
||||
this.restartTimer = null
|
||||
}
|
||||
this.lifecycle = 'stopped'
|
||||
this.manuallyStopped = true
|
||||
this.child = null
|
||||
this.lastBinding = null
|
||||
this.lastError = null
|
||||
}
|
||||
|
||||
async startAfterResidualCleanup(): Promise<MacWechatRuntimeSnapshot> {
|
||||
return this.ensureStarted({ allowManualRestart: true })
|
||||
}
|
||||
|
||||
private resolveRuntimeDir(): string | null {
|
||||
if (isMacNativeRuntimeUnavailable()) return null
|
||||
const resolved = resolveWechatRuntimeDirectory()
|
||||
@@ -261,7 +281,11 @@ class MacWechatRuntimeManager {
|
||||
* comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime
|
||||
* online" and "WeChat bound" stay two independent states.
|
||||
*/
|
||||
async ensureStarted(): Promise<MacWechatRuntimeSnapshot> {
|
||||
async ensureStarted(
|
||||
options: { allowManualRestart?: boolean } = {}
|
||||
): Promise<MacWechatRuntimeSnapshot> {
|
||||
if (this.manuallyStopped && !options.allowManualRestart) return this.getSnapshot()
|
||||
if (options.allowManualRestart) this.manuallyStopped = false
|
||||
if (isMacNativeRuntimeUnavailable()) {
|
||||
this.manifest = null
|
||||
this.lifecycle = 'stopped'
|
||||
@@ -603,6 +627,12 @@ class MacWechatRuntimeManager {
|
||||
if (availability.state !== 'available') {
|
||||
return offlineMacLicenseStatus('runtime_missing', availability.message)
|
||||
}
|
||||
if (this.manuallyStopped) {
|
||||
return offlineMacLicenseStatus(
|
||||
'runtime_missing',
|
||||
'Mac 发送组件已停止,请在发送页点击“绑定微信”重新启动。'
|
||||
)
|
||||
}
|
||||
if (this.lifecycle === 'stopped') await this.ensureStarted()
|
||||
const { status, body } = await this.request('GET', '/license/status', LICENSE_STATUS_TIMEOUT_MS)
|
||||
if (status === null) {
|
||||
@@ -637,6 +667,12 @@ class MacWechatRuntimeManager {
|
||||
if (availability.state !== 'available') {
|
||||
return offlineMacLicenseStatus('runtime_missing', availability.message)
|
||||
}
|
||||
if (this.manuallyStopped) {
|
||||
return offlineMacLicenseStatus(
|
||||
'runtime_missing',
|
||||
'Mac 发送组件已停止,请在发送页点击“绑定微信”重新启动。'
|
||||
)
|
||||
}
|
||||
if (this.lifecycle === 'stopped') await this.ensureStarted()
|
||||
if (this.licenseRefreshInFlight) {
|
||||
// A refresh is already running; answer from the local snapshot so the
|
||||
@@ -725,7 +761,7 @@ class MacWechatRuntimeManager {
|
||||
* never succeed because the check itself is what should start the host.
|
||||
* Starting it never touches WeChat, so doing it from a read is safe.
|
||||
*/
|
||||
if (this.lifecycle === 'stopped') {
|
||||
if (this.lifecycle === 'stopped' && !this.manuallyStopped) {
|
||||
await this.ensureStarted().catch(() => undefined)
|
||||
}
|
||||
/* Self-heal the status card too: if WeChat was restarted, drop the stale
|
||||
@@ -817,7 +853,7 @@ class MacWechatRuntimeManager {
|
||||
return { ok: false, attached: false, state: 'runtime_offline', message: availability.message }
|
||||
}
|
||||
if (this.lifecycle !== 'online') {
|
||||
const snapshot = await this.ensureStarted()
|
||||
const snapshot = await this.ensureStarted({ allowManualRestart: true })
|
||||
if (snapshot.lifecycle !== 'online') {
|
||||
return {
|
||||
ok: false,
|
||||
@@ -902,7 +938,7 @@ class MacWechatRuntimeManager {
|
||||
async reload(): Promise<MacWechatRuntimeSnapshot> {
|
||||
await this.shutdown().catch(() => undefined)
|
||||
await new Promise((resolve) => setTimeout(resolve, 2_000))
|
||||
return this.ensureStarted()
|
||||
return this.ensureStarted({ allowManualRestart: true })
|
||||
}
|
||||
|
||||
private isProcessAlive(pid: number): boolean {
|
||||
|
||||
@@ -140,7 +140,7 @@ export function probeLicenseStatus(timeoutMs = PROBE_TIMEOUT_MS): Promise<Licens
|
||||
let req: http.ClientRequest
|
||||
try {
|
||||
req = http.get(
|
||||
{ host: '127.0.0.1', port: 4290, path: '/license/status', timeout: timeoutMs },
|
||||
{ host: '127.0.0.1', port: Number(process.env.TM_WECHAT_HOST_PORT) || 4290, path: '/license/status', timeout: timeoutMs },
|
||||
(res) => {
|
||||
const chunks: Buffer[] = []
|
||||
res.on('data', (chunk: Buffer) => chunks.push(chunk))
|
||||
|
||||
Reference in new issue
Block a user