mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: Windows增加发送视频 dy下载脚本
This commit is contained in:
1 parent
ebea992b10
commit
b171818df5
8 files changed
+1262
-64
No files matched your search
@@ -55,6 +55,8 @@ interface CachedGroupSnapshotFile {
|
||||
|
||||
interface ScheduledWrite {
|
||||
value: unknown
|
||||
/** 内容指纹,与 value 一一对应;用于判断"磁盘上是否已经是这份内容" */
|
||||
signature: string
|
||||
revision: number
|
||||
generation: number
|
||||
cleanupFile?: string
|
||||
@@ -78,6 +80,27 @@ const MAX_MEMORY_GROUP_SNAPSHOTS = 32
|
||||
const WRITE_DEBOUNCE_MS = 300
|
||||
const PRUNE_INTERVAL_MS = 30_000
|
||||
|
||||
/**
|
||||
* 替换目标文件时的重试节奏(毫秒)。
|
||||
*
|
||||
* 覆盖写走 `rename`(Windows 上是 MoveFileEx+REPLACE_EXISTING),杀软扫描、索引器
|
||||
* 短暂持有句柄都会让它抛 EPERM/EBUSY/EACCES —— 这类占用是瞬时的,重试即可。
|
||||
* 4 次总计约 0.5s,超过这个量级说明是真的写不进去,应该保留旧缓存而不是继续磨。
|
||||
*/
|
||||
const REPLACE_RETRY_DELAYS_MS = [40, 120, 300] as const
|
||||
/** 可重试的瞬时错误码。除此以外的错误重试也不会好。 */
|
||||
const REPLACE_RETRYABLE_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY', 'EAGAIN'])
|
||||
/**
|
||||
* 退出刷盘的重试总预算(毫秒)。
|
||||
*
|
||||
* 单文件最坏重试等待 40+120+300=460ms;待写文件一多,累加起来就是肉眼可见的
|
||||
* 退出卡顿。这里给整批一个固定预算,预算耗尽后不再等待重试,剩余文件各试一次。
|
||||
* 首次尝试(真正的 writeFileSync + renameSync)不受预算限制 —— 那是必须做的写。
|
||||
*/
|
||||
const FLUSH_RETRY_BUDGET_MS = 120
|
||||
/** 恢复写入用临时文件名的偏移量,避免与普通 revision 撞名。 */
|
||||
const RESTORE_REVISION_OFFSET = 1_000_000
|
||||
|
||||
const startupMemory = new Map<string, StartupCacheFile>()
|
||||
const messageMemory = new Map<string, CachedMessageBucketFile>()
|
||||
const groupMemory = new Map<string, CachedGroupSnapshotFile>()
|
||||
@@ -86,6 +109,32 @@ const writeQueues = new Map<string, Promise<void>>()
|
||||
const scheduledWrites = new Map<string, ScheduledWrite>()
|
||||
const writeRevisions = new Map<string, number>()
|
||||
const lastPrunedAt = new Map<string, number>()
|
||||
/**
|
||||
* 磁盘上**已经确认写入成功**的内容指纹。
|
||||
*
|
||||
* 与 `startupMemory` / `scheduledWrites` 是三份独立状态:
|
||||
* - startupMemory = 最新内存状态(可能是还没落盘的)
|
||||
* - scheduledWrites = 待写入队列(可能被后来的调用顶掉)
|
||||
* - persistedSignatures = 上一次真正 rename 成功的内容
|
||||
* 只有 rename 成功才更新它;失败的写入绝不能把内存态标记成"已持久化",
|
||||
* 否则后续相同内容的保存会被指纹闸门静默丢掉,缓存永远追不上内存。
|
||||
*/
|
||||
const persistedSignatures = new Map<string, string>()
|
||||
/**
|
||||
* 最近一次成功落盘的内容(只记启动缓存这类带指纹的文件)。
|
||||
*
|
||||
* 存在的唯一理由:rename 是"检查-执行"两段,检查通过之后到 rename 真正生效之间,
|
||||
* 退出刷盘或清缓存仍可能插进来。事后靠这份日志判断"我这一笔是不是把更新的内容踩了",
|
||||
* 是就把它恢复回来。只留一条/文件,内存占用与一个 startup.json 同级。
|
||||
*/
|
||||
const lastCommits = new Map<string, { value: unknown; signature: string; generation: number }>()
|
||||
/**
|
||||
* 退出刷盘纪元。
|
||||
*
|
||||
* `flushBootstrapCacheWritesSync()` 自增它,让已经越过检查点、正在飞行的异步写入
|
||||
* 在最后一步放弃 —— 退出时同步写的内容不应该被一个更早发起的异步写覆盖回去。
|
||||
*/
|
||||
let flushEpoch = 0
|
||||
let cacheGeneration = 0
|
||||
|
||||
function normalizeRoot(accountRoot?: string): string {
|
||||
@@ -96,6 +145,151 @@ function digest(value: string): string {
|
||||
return crypto.createHash('sha1').update(value).digest('hex').slice(0, 24)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 JSON 语义递归规范化:对象键排序、跳过值为 `undefined` 的属性。
|
||||
*
|
||||
* 与 `JSON.stringify` 的行为保持一致(后者同样丢弃 undefined 属性、保留 null),
|
||||
* 这样"指纹看到的"和"写进磁盘的"是同一份内容。
|
||||
*/
|
||||
function sortForStable(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map((item) => sortForStable(item))
|
||||
if (value === null || typeof value !== 'object') return value
|
||||
const source = value as Record<string, unknown>
|
||||
const sorted: Record<string, unknown> = {}
|
||||
for (const key of Object.keys(source).sort()) {
|
||||
const item = source[key]
|
||||
if (item === undefined) continue
|
||||
sorted[key] = sortForStable(item)
|
||||
}
|
||||
return sorted
|
||||
}
|
||||
|
||||
/** 稳定序列化:同一份数据不论键序如何,结果一致。 */
|
||||
function stableStringify(value: unknown): string {
|
||||
return JSON.stringify(sortForStable(value))
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动缓存内容指纹。
|
||||
*
|
||||
* 覆盖**实际会被持久化的全部内容**:直接对 `self` 和每个 `contact` 做稳定序列化,
|
||||
* 不维护字段白名单 —— 白名单漏一个字段就会出现"字段变了却不写盘"的静默失效,
|
||||
* 这比多写一次严重得多。`updatedAt` / `version` / `platform` 因为不属于 self 或
|
||||
* 任一 contact,天然不参与计算。
|
||||
*
|
||||
* 联系人顺序不参与语义:先压成规范串再对**字符串数组**排序;
|
||||
* 排序的是派生副本,传入数组本身不会被原地修改。
|
||||
*
|
||||
* 复杂度 O(n·k log k),n = 联系人数、k = 单条字段数;相比写 2MB 磁盘可忽略。
|
||||
*/
|
||||
function startupSignature(cache: StartupCacheFile): string {
|
||||
const contacts = Array.isArray(cache.contacts) ? cache.contacts : []
|
||||
const contactKeys = contacts.map((contact) => stableStringify(contact))
|
||||
contactKeys.sort()
|
||||
const selfKey = cache.self ? stableStringify(cache.self) : 'none'
|
||||
return crypto
|
||||
.createHash('sha1')
|
||||
.update(`v${CACHE_VERSION}|${cache.platform}|${normalizeRoot(cache.accountRoot)}`)
|
||||
.update('|self|')
|
||||
.update(selfKey)
|
||||
.update('|contacts|')
|
||||
.update(contactKeys.join('\n'))
|
||||
.digest('hex')
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
/** 同步 sleep:退出路径不能用 setTimeout,用 Atomics.wait 才不会空转烧 CPU。 */
|
||||
function delaySync(ms: number): void {
|
||||
if (ms <= 0) return
|
||||
try {
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
|
||||
} catch {
|
||||
const until = Date.now() + ms
|
||||
while (Date.now() < until) {
|
||||
/* 极端环境下退化:没有 SharedArrayBuffer 时只能忙等 */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 原子替换:临时文件 → 目标文件,全程不删除目标。
|
||||
*
|
||||
* `fs.rename` 在 Windows 上走 MoveFileExW(MOVEFILE_REPLACE_EXISTING),在 POSIX 上是
|
||||
* rename(2):两者都是"用新名字替换旧名字",旧文件内容由文件系统在提交点丢弃,
|
||||
* 不存在"先删掉目标再尝试改名"的空窗期。
|
||||
*
|
||||
* EXDEV(跨卷)在这里是**不可恢复**的:临时文件天生建在目标同目录,正常永远跨不了卷。
|
||||
* 真出现 EXDEV 说明路径本身出了问题,此时唯一安全的动作是放弃本次写入 ——
|
||||
* `copyFile` 覆盖没有原子性,写到一半断电/磁盘满会把旧缓存截成半截 JSON,
|
||||
* 比"这次没更新"严重得多。所以这里直接抛出,旧文件原样保留。
|
||||
*/
|
||||
async function replaceFileAtomic(tempFile: string, file: string): Promise<void> {
|
||||
let lastError: unknown = null
|
||||
for (let attempt = 0; attempt <= REPLACE_RETRY_DELAYS_MS.length; attempt += 1) {
|
||||
try {
|
||||
await fs.rename(tempFile, file)
|
||||
return
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException)?.code || ''
|
||||
if (code === 'EXDEV') throw error
|
||||
if (!REPLACE_RETRYABLE_CODES.has(code)) throw error
|
||||
lastError = error
|
||||
if (attempt < REPLACE_RETRY_DELAYS_MS.length) {
|
||||
await delay(REPLACE_RETRY_DELAYS_MS[attempt])
|
||||
}
|
||||
}
|
||||
}
|
||||
throw lastError instanceof Error ? lastError : new Error('replace failed')
|
||||
}
|
||||
|
||||
/**
|
||||
* `replaceFileAtomic` 的同步版本,供退出时的 `flushBootstrapCacheWritesSync` 使用。
|
||||
*
|
||||
* `deadline` 是整批刷盘的重试预算:超过它就不再等待重试,直接把这个文件的失败
|
||||
* 算掉(旧缓存保留)。不设预算的话,N 个待写文件 × 460ms 能把退出拖成分钟级。
|
||||
*/
|
||||
function replaceFileAtomicSync(
|
||||
tempFile: string,
|
||||
file: string,
|
||||
deadline = Number.POSITIVE_INFINITY
|
||||
): void {
|
||||
let lastError: unknown = null
|
||||
for (let attempt = 0; attempt <= REPLACE_RETRY_DELAYS_MS.length; attempt += 1) {
|
||||
try {
|
||||
fs.renameSync(tempFile, file)
|
||||
return
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException)?.code || ''
|
||||
// 与异步路径同样的判断:跨卷不做覆盖复制,直接失败、旧文件保留。
|
||||
if (code === 'EXDEV') throw error
|
||||
if (!REPLACE_RETRYABLE_CODES.has(code)) throw error
|
||||
lastError = error
|
||||
if (attempt < REPLACE_RETRY_DELAYS_MS.length) {
|
||||
const wait = REPLACE_RETRY_DELAYS_MS[attempt]
|
||||
if (Date.now() + wait > deadline) break
|
||||
delaySync(wait)
|
||||
}
|
||||
}
|
||||
}
|
||||
throw lastError instanceof Error ? lastError : new Error('replace failed')
|
||||
}
|
||||
|
||||
function makeTempFile(file: string, revision: number): string {
|
||||
// 临时文件必须与目标同目录:跨卷 rename 会退化成 EXDEV。
|
||||
return `${file}.${process.pid}.${revision}.tmp`
|
||||
}
|
||||
|
||||
function removeTempFileSync(tempFile: string): void {
|
||||
try {
|
||||
if (fs.existsSync(tempFile)) fs.removeSync(tempFile)
|
||||
} catch {
|
||||
// 清理失败不改变本次写入的结论,只是留下一个 .tmp
|
||||
}
|
||||
}
|
||||
|
||||
function getAccountCachePaths(accountRoot: string): AccountCachePaths {
|
||||
const normalizedRoot = normalizeRoot(accountRoot)
|
||||
const accountKey = digest(`${process.platform}:${normalizedRoot}`)
|
||||
@@ -192,7 +386,7 @@ function readStartupCacheFile(accountRoot: string): StartupCacheFile | null {
|
||||
contacts: Array.isArray(legacy.contacts) ? legacy.contacts : []
|
||||
}
|
||||
startupMemory.set(file, migrated)
|
||||
scheduleWrite(file, migrated, { cleanupFile: paths.legacy })
|
||||
scheduleWrite(file, migrated, startupSignature(migrated), { cleanupFile: paths.legacy })
|
||||
return migrated
|
||||
}
|
||||
const raw = fs.readJsonSync(file) as Partial<StartupCacheFile>
|
||||
@@ -206,6 +400,9 @@ function readStartupCacheFile(accountRoot: string): StartupCacheFile | null {
|
||||
contacts: Array.isArray(raw.contacts) ? raw.contacts : []
|
||||
}
|
||||
startupMemory.set(file, result)
|
||||
// 刚从磁盘读出来的内容就等于磁盘内容,直接登记为"已持久化"。
|
||||
// 不登记的话,每次启动后的第一次保存都会无条件重写一遍 —— 正是要消掉的放大。
|
||||
if (!persistedSignatures.has(file)) persistedSignatures.set(file, startupSignature(result))
|
||||
return result
|
||||
} catch (error) {
|
||||
console.warn('[BootstrapCache] startup read failed:', error)
|
||||
@@ -322,6 +519,7 @@ async function pruneCacheDirectory(directory: string, maxFiles: number): Promise
|
||||
function queueWrite(file: string): void {
|
||||
const scheduled = scheduledWrites.get(file)
|
||||
if (!scheduled) return
|
||||
const epochAtSchedule = flushEpoch
|
||||
const previous = writeQueues.get(file) || Promise.resolve()
|
||||
const next = previous
|
||||
.catch(() => undefined)
|
||||
@@ -335,19 +533,91 @@ function queueWrite(file: string): void {
|
||||
return
|
||||
}
|
||||
|
||||
const tempFile = `${file}.${process.pid}.${scheduled.revision}.tmp`
|
||||
const tempFile = makeTempFile(file, scheduled.revision)
|
||||
await fs.ensureDir(path.dirname(file))
|
||||
// 先把完整内容写进临时文件:目标文件在整个过程中始终是上一份完整数据。
|
||||
await fs.writeFile(tempFile, JSON.stringify(current.value), 'utf8')
|
||||
|
||||
const latest = scheduledWrites.get(file)
|
||||
if (
|
||||
!latest ||
|
||||
latest.revision !== scheduled.revision ||
|
||||
latest.generation !== cacheGeneration
|
||||
latest.generation !== cacheGeneration ||
|
||||
flushEpoch !== epochAtSchedule
|
||||
) {
|
||||
await fs.remove(tempFile)
|
||||
await fs.remove(tempFile).catch(() => undefined)
|
||||
return
|
||||
}
|
||||
await fs.move(tempFile, file, { overwrite: true })
|
||||
|
||||
// 替换前的最后一道闸:被 clear 掉(generation 变)或退出刷盘(epoch 变)就不提交。
|
||||
if (flushEpoch !== epochAtSchedule || scheduled.generation !== cacheGeneration) {
|
||||
await fs.remove(tempFile).catch(() => undefined)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await replaceFileAtomic(tempFile, file)
|
||||
} catch (error) {
|
||||
// 失败:目标文件仍是旧内容(rename 是原子替换,没有"先删后改"的中间态),
|
||||
// 本次临时文件必须清掉,否则反复失败会堆 .tmp。
|
||||
await fs.remove(tempFile).catch(() => undefined)
|
||||
// 同时撤掉这条待写入记录:留着它会让下一次 commitStartupCache 误以为
|
||||
// "队列里还有一份不同内容",白写一次。
|
||||
const failed = scheduledWrites.get(file)
|
||||
if (failed?.revision === scheduled.revision) scheduledWrites.delete(file)
|
||||
throw error
|
||||
}
|
||||
|
||||
// 落盘之后核一次账:rename 是原子的,但"检查 epoch/generation"和"rename 生效"
|
||||
// 之间仍有窗口 —— 退出刷盘或清缓存可能正好插在中间。
|
||||
// 这时我们刚写下去的可能是旧内容,必须按日志把更新的那份放回去。
|
||||
const clobberedByFlush = flushEpoch !== epochAtSchedule
|
||||
const clobberedByClear = scheduled.generation !== cacheGeneration
|
||||
let committedSignature = scheduled.signature
|
||||
let committedValue: unknown = scheduled.value
|
||||
|
||||
if (scheduled.signature && (clobberedByFlush || clobberedByClear)) {
|
||||
const newer = lastCommits.get(file)
|
||||
if (newer && newer.signature !== scheduled.signature) {
|
||||
// 有比我们更新的一份已经落过盘:恢复它。
|
||||
const restoreTemp = makeTempFile(file, scheduled.revision + RESTORE_REVISION_OFFSET)
|
||||
try {
|
||||
fs.writeFileSync(restoreTemp, JSON.stringify(newer.value), 'utf8')
|
||||
replaceFileAtomicSync(restoreTemp, file)
|
||||
committedSignature = newer.signature
|
||||
committedValue = newer.value
|
||||
} catch (error) {
|
||||
removeTempFileSync(restoreTemp)
|
||||
console.warn('[BootstrapCache] restore after race failed:', error)
|
||||
}
|
||||
} else if (clobberedByClear) {
|
||||
// 清缓存之后才落地的旧数据:不该留在磁盘上(否则等于缓存复活)。
|
||||
try {
|
||||
fs.removeSync(file)
|
||||
} catch {
|
||||
// 删不掉也不阻塞后续流程,下一次保存会覆盖它
|
||||
}
|
||||
committedSignature = ''
|
||||
committedValue = undefined
|
||||
}
|
||||
}
|
||||
|
||||
// 只有 rename 成功才承认"磁盘上是这份内容"。superseded 的情况下也照记:
|
||||
// persistedSignatures 描述的是磁盘现状,不是"最新意图"。
|
||||
if (scheduled.signature) {
|
||||
if (committedSignature) {
|
||||
persistedSignatures.set(file, committedSignature)
|
||||
lastCommits.set(file, {
|
||||
value: committedValue,
|
||||
signature: committedSignature,
|
||||
generation: scheduled.generation
|
||||
})
|
||||
} else {
|
||||
persistedSignatures.delete(file)
|
||||
lastCommits.delete(file)
|
||||
}
|
||||
}
|
||||
|
||||
const completed = scheduledWrites.get(file)
|
||||
if (
|
||||
completed?.revision === scheduled.revision &&
|
||||
@@ -372,6 +642,7 @@ function queueWrite(file: string): void {
|
||||
function scheduleWrite(
|
||||
file: string,
|
||||
value: unknown,
|
||||
signature: string,
|
||||
options?: { cleanupFile?: string; prune?: { directory: string; maxFiles: number } }
|
||||
): void {
|
||||
const existingTimer = writeTimers.get(file)
|
||||
@@ -380,6 +651,7 @@ function scheduleWrite(
|
||||
writeRevisions.set(file, revision)
|
||||
scheduledWrites.set(file, {
|
||||
value,
|
||||
signature,
|
||||
revision,
|
||||
generation: cacheGeneration,
|
||||
cleanupFile: options?.cleanupFile,
|
||||
@@ -394,6 +666,17 @@ function scheduleWrite(
|
||||
)
|
||||
}
|
||||
|
||||
/** 取消待写入任务(不动磁盘、不动内存态)。revision 递增让在途写入失效。 */
|
||||
function cancelScheduledWrite(file: string): void {
|
||||
const timer = writeTimers.get(file)
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
writeTimers.delete(file)
|
||||
}
|
||||
writeRevisions.set(file, (writeRevisions.get(file) || 0) + 1)
|
||||
scheduledWrites.delete(file)
|
||||
}
|
||||
|
||||
function loadOrCreateStartupCache(accountRoot: string): StartupCacheFile | null {
|
||||
const normalizedRoot = normalizeRoot(accountRoot)
|
||||
if (!normalizedRoot) return null
|
||||
@@ -410,10 +693,39 @@ function loadOrCreateStartupCache(accountRoot: string): StartupCacheFile | null
|
||||
return created
|
||||
}
|
||||
|
||||
function writeStartupCache(cache: StartupCacheFile): void {
|
||||
const paths = getAccountCachePaths(cache.accountRoot)
|
||||
startupMemory.set(paths.startup, cache)
|
||||
scheduleWrite(paths.startup, cache, { cleanupFile: paths.legacy })
|
||||
/**
|
||||
* 提交一份新的启动缓存状态。
|
||||
*
|
||||
* 调用方必须传**新建的对象**(copy-on-write),不能传 `loadOrCreateStartupCache()`
|
||||
* 返回的那个内存对象本身 —— 否则"旧状态"和"新状态"是同一个引用,
|
||||
* 指纹永远相等,缓存就再也写不下去了。
|
||||
*/
|
||||
function commitStartupCache(next: StartupCacheFile): void {
|
||||
const paths = getAccountCachePaths(next.accountRoot)
|
||||
const file = paths.startup
|
||||
const signature = startupSignature(next)
|
||||
const persisted = persistedSignatures.get(file)
|
||||
const pending = scheduledWrites.get(file)
|
||||
|
||||
startupMemory.set(file, next)
|
||||
|
||||
if (persisted === signature) {
|
||||
// 磁盘上已经是这份内容。
|
||||
if (!pending) return
|
||||
if (pending.signature === signature) {
|
||||
// 队列里排着的就是要写的同一份内容:撤掉它,别做无意义的一次替换。
|
||||
cancelScheduledWrite(file)
|
||||
return
|
||||
}
|
||||
// 队列里排着一份**不同**的内容(A→B→A 的收尾):必须再写一次,
|
||||
// 否则 B 落盘后内存里的 A 就永远丢了。
|
||||
}
|
||||
|
||||
// 只有真正要写盘时才推进 updatedAt:内容没变却刷新时间戳,
|
||||
// 会让上层"上次更新时间"变成噪音。
|
||||
const value: StartupCacheFile = { ...next, updatedAt: Date.now() }
|
||||
startupMemory.set(file, value)
|
||||
scheduleWrite(file, value, signature, { cleanupFile: paths.legacy })
|
||||
}
|
||||
|
||||
function containsLegacyMisparsedAppMessage(items: Message[]): boolean {
|
||||
@@ -523,9 +835,8 @@ export function mergeCachedContactAvatars(accountRoot: string, contacts: Contact
|
||||
export function saveBootstrapSelf(accountRoot: string, self: CachedSelfInfo): void {
|
||||
const cache = loadOrCreateStartupCache(accountRoot)
|
||||
if (!cache) return
|
||||
cache.self = self
|
||||
cache.updatedAt = Date.now()
|
||||
writeStartupCache(cache)
|
||||
// copy-on-write:不原地改内存对象,指纹才可能是"这次的新内容"。
|
||||
commitStartupCache({ ...cache, self })
|
||||
}
|
||||
|
||||
export function saveBootstrapContacts(accountRoot: string, contacts: Contact[]): void {
|
||||
@@ -543,7 +854,8 @@ export function saveBootstrapContacts(accountRoot: string, contacts: Contact[]):
|
||||
)
|
||||
.map((contact) => [contact.m_nsUsrName, contact.m_nsNickName])
|
||||
)
|
||||
cache.contacts = contacts.map((contact) => ({
|
||||
// 注意:`contacts.map` 产出新数组,传入的数组本身不会被排序或改写。
|
||||
const merged = contacts.map((contact) => ({
|
||||
...contact,
|
||||
avatar:
|
||||
contact.avatar || !avatarByUsername.has(contact.m_nsUsrName)
|
||||
@@ -554,23 +866,21 @@ export function saveBootstrapContacts(accountRoot: string, contacts: Contact[]):
|
||||
? contact.m_nsNickName
|
||||
: nameByUsername.get(contact.m_nsUsrName) || contact.m_nsNickName
|
||||
}))
|
||||
cache.updatedAt = Date.now()
|
||||
writeStartupCache(cache)
|
||||
commitStartupCache({ ...cache, contacts: merged })
|
||||
}
|
||||
|
||||
export function mergeBootstrapAvatars(accountRoot: string, avatars: Record<string, string>): void {
|
||||
const cache = loadOrCreateStartupCache(accountRoot)
|
||||
if (!cache?.contacts.length) return
|
||||
let changed = false
|
||||
cache.contacts = cache.contacts.map((contact) => {
|
||||
const merged = cache.contacts.map((contact) => {
|
||||
const avatar = avatars[contact.m_nsUsrName]
|
||||
if (!avatar || contact.avatar === avatar) return contact
|
||||
changed = true
|
||||
return { ...contact, avatar }
|
||||
})
|
||||
if (!changed) return
|
||||
cache.updatedAt = Date.now()
|
||||
writeStartupCache(cache)
|
||||
commitStartupCache({ ...cache, contacts: merged })
|
||||
}
|
||||
|
||||
export function getCachedMessages(
|
||||
@@ -610,29 +920,29 @@ export function saveCachedGroupSnapshot(
|
||||
const file = getGroupCacheFile(normalizedRoot, userMd5)
|
||||
const previous = readGroupSnapshotFile(normalizedRoot, userMd5)?.snapshot
|
||||
const previousByWxid = new Map((previous?.members || []).map((member) => [member.wxid, member]))
|
||||
const mergedSnapshot: CachedGroupSnapshot = previous && previous.roomId === snapshot.roomId
|
||||
? {
|
||||
...snapshot,
|
||||
members: snapshot.members.map((member) => {
|
||||
const oldMember = previousByWxid.get(member.wxid)
|
||||
const freshGroupNickname = String(member.groupNickname || '').trim()
|
||||
const freshWechatNickname = String(member.wechatNickname || '').trim()
|
||||
const oldGroupNickname = String(oldMember?.groupNickname || '').trim()
|
||||
const freshLooksLikeContactFallback =
|
||||
!freshGroupNickname ||
|
||||
freshGroupNickname === freshWechatNickname
|
||||
const groupNickname =
|
||||
freshLooksLikeContactFallback && oldGroupNickname
|
||||
? oldGroupNickname
|
||||
: freshGroupNickname
|
||||
return {
|
||||
...member,
|
||||
groupNickname,
|
||||
nickname: groupNickname || member.nickname
|
||||
}
|
||||
})
|
||||
}
|
||||
: snapshot
|
||||
const mergedSnapshot: CachedGroupSnapshot =
|
||||
previous && previous.roomId === snapshot.roomId
|
||||
? {
|
||||
...snapshot,
|
||||
members: snapshot.members.map((member) => {
|
||||
const oldMember = previousByWxid.get(member.wxid)
|
||||
const freshGroupNickname = String(member.groupNickname || '').trim()
|
||||
const freshWechatNickname = String(member.wechatNickname || '').trim()
|
||||
const oldGroupNickname = String(oldMember?.groupNickname || '').trim()
|
||||
const freshLooksLikeContactFallback =
|
||||
!freshGroupNickname || freshGroupNickname === freshWechatNickname
|
||||
const groupNickname =
|
||||
freshLooksLikeContactFallback && oldGroupNickname
|
||||
? oldGroupNickname
|
||||
: freshGroupNickname
|
||||
return {
|
||||
...member,
|
||||
groupNickname,
|
||||
nickname: groupNickname || member.nickname
|
||||
}
|
||||
})
|
||||
}
|
||||
: snapshot
|
||||
const value: CachedGroupSnapshotFile = {
|
||||
version: CACHE_VERSION,
|
||||
platform: process.platform,
|
||||
@@ -642,7 +952,9 @@ export function saveCachedGroupSnapshot(
|
||||
snapshot: mergedSnapshot
|
||||
}
|
||||
touchMemory(groupMemory, file, value, MAX_MEMORY_GROUP_SNAPSHOTS)
|
||||
scheduleWrite(file, value, {
|
||||
// 消息桶/群快照不做内容指纹(每次读都是一份新数据),signature 传空串,
|
||||
// queueWrite 会跳过 persistedSignatures 登记。
|
||||
scheduleWrite(file, value, '', {
|
||||
prune: { directory: paths.groups, maxFiles: MAX_GROUP_SNAPSHOTS }
|
||||
})
|
||||
return mergedSnapshot
|
||||
@@ -671,22 +983,43 @@ export function saveCachedMessages(
|
||||
items: messages.slice(-MAX_MESSAGES_PER_BUCKET)
|
||||
}
|
||||
touchMemory(messageMemory, file, value, MAX_MEMORY_MESSAGE_BUCKETS)
|
||||
scheduleWrite(file, value, {
|
||||
scheduleWrite(file, value, '', {
|
||||
prune: { directory: paths.messages, maxFiles: MAX_MESSAGE_BUCKETS }
|
||||
})
|
||||
}
|
||||
|
||||
export function flushBootstrapCacheWritesSync(): void {
|
||||
// 自增纪元:已经越过检查点、正在飞行的异步写会在 rename 前发现自己过期并放弃,
|
||||
// 避免退出时的同步内容被一个更早发起的异步写覆盖回去。
|
||||
flushEpoch += 1
|
||||
for (const timer of writeTimers.values()) clearTimeout(timer)
|
||||
writeTimers.clear()
|
||||
const writes = Array.from(scheduledWrites.entries())
|
||||
scheduledWrites.clear()
|
||||
// 整批共享一份重试预算,避免 N 个文件各自重试把退出拖成分钟级。
|
||||
const deadline = Date.now() + FLUSH_RETRY_BUDGET_MS
|
||||
for (const [file, scheduled] of writes) {
|
||||
// 退出时同步写也算一次 revision 变更,让队列里同一文件的任务作废。
|
||||
writeRevisions.set(file, (writeRevisions.get(file) || 0) + 1)
|
||||
const tempFile = makeTempFile(file, scheduled.revision)
|
||||
try {
|
||||
fs.ensureDirSync(path.dirname(file))
|
||||
fs.writeFileSync(file, JSON.stringify(scheduled.value), 'utf8')
|
||||
// 与异步路径保持同一套语义:先写完整临时文件,再原子换名,绝不先删目标。
|
||||
fs.writeFileSync(tempFile, JSON.stringify(scheduled.value), 'utf8')
|
||||
replaceFileAtomicSync(tempFile, file, deadline)
|
||||
if (scheduled.signature) {
|
||||
persistedSignatures.set(file, scheduled.signature)
|
||||
// 记进提交日志:若此时还有一笔在途异步写正好落在我们之后,
|
||||
// 它会在核账时发现自己踩了更新的内容,并按这条日志恢复。
|
||||
lastCommits.set(file, {
|
||||
value: scheduled.value,
|
||||
signature: scheduled.signature,
|
||||
generation: scheduled.generation
|
||||
})
|
||||
}
|
||||
if (scheduled.cleanupFile) fs.removeSync(scheduled.cleanupFile)
|
||||
} catch (error) {
|
||||
removeTempFileSync(tempFile)
|
||||
console.warn('[BootstrapCache] flush failed:', error)
|
||||
}
|
||||
}
|
||||
@@ -694,12 +1027,17 @@ export function flushBootstrapCacheWritesSync(): void {
|
||||
|
||||
export function clearBootstrapCache(): void {
|
||||
cacheGeneration += 1
|
||||
// 清缓存同样让在途写入作废,并且丢掉"已持久化"记录 —— 磁盘上的文件可能马上被删,
|
||||
// 留着旧指纹会让下一次保存误以为"磁盘上已经有了"而不写。
|
||||
flushEpoch += 1
|
||||
for (const timer of writeTimers.values()) clearTimeout(timer)
|
||||
writeTimers.clear()
|
||||
scheduledWrites.clear()
|
||||
writeQueues.clear()
|
||||
writeRevisions.clear()
|
||||
lastPrunedAt.clear()
|
||||
persistedSignatures.clear()
|
||||
lastCommits.clear()
|
||||
startupMemory.clear()
|
||||
messageMemory.clear()
|
||||
groupMemory.clear()
|
||||
|
||||
@@ -254,7 +254,11 @@ function windowsImageTempRoot(): string {
|
||||
throw new Error('无法创建 Windows 图片临时目录')
|
||||
}
|
||||
|
||||
export function prepareWindowsImageFile(filePath: string): {
|
||||
/** hook 侧用 ANSI API 判文件存在,非 ASCII 路径一律判成不存在,先拷一份 ASCII 副本。 */
|
||||
export function prepareWindowsMediaFile(
|
||||
filePath: string,
|
||||
options: { prefix: string; fallbackExtension: string }
|
||||
): {
|
||||
filePath: string
|
||||
temporary: boolean
|
||||
} {
|
||||
@@ -262,12 +266,12 @@ export function prepareWindowsImageFile(filePath: string): {
|
||||
if (isAsciiPath(normalized)) return { filePath: normalized, temporary: false }
|
||||
|
||||
const extension = extname(normalized).toLowerCase()
|
||||
const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.png'
|
||||
const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : options.fallbackExtension
|
||||
const temporaryPath = join(
|
||||
windowsImageTempRoot(),
|
||||
`tm-img-${randomBytes(8).toString('hex')}${safeExtension}`
|
||||
`${options.prefix}${randomBytes(8).toString('hex')}${safeExtension}`
|
||||
)
|
||||
if (!isAsciiPath(temporaryPath)) throw new Error('Windows 图片临时路径必须只包含 ASCII 字符')
|
||||
if (!isAsciiPath(temporaryPath)) throw new Error('Windows 媒体临时路径必须只包含 ASCII 字符')
|
||||
try {
|
||||
copyFileSync(normalized, temporaryPath)
|
||||
} catch (error) {
|
||||
@@ -281,6 +285,13 @@ export function prepareWindowsImageFile(filePath: string): {
|
||||
return { filePath: temporaryPath, temporary: true }
|
||||
}
|
||||
|
||||
export function prepareWindowsImageFile(filePath: string): {
|
||||
filePath: string
|
||||
temporary: boolean
|
||||
} {
|
||||
return prepareWindowsMediaFile(filePath, { prefix: 'tm-img-', fallbackExtension: '.png' })
|
||||
}
|
||||
|
||||
function prepareMacWechatImageFile(
|
||||
filePath: string,
|
||||
senderWxid: string,
|
||||
@@ -558,6 +569,7 @@ function windowsStatusBase(host = windowsHookHost() || ''): PersonalWechatSender
|
||||
canSendText: false,
|
||||
canSendImage: false,
|
||||
canSendVoice: false,
|
||||
canSendVideo: false,
|
||||
message: '正在检查 Windows 微信消息接口'
|
||||
}
|
||||
}
|
||||
@@ -607,6 +619,21 @@ function logSendDiagnostic(
|
||||
*/
|
||||
const WINDOWS_TEMP_IMAGE_GRACE_MS = 0
|
||||
|
||||
/** 视频上传在 send_message 返回后才开始,删早了接收端只能拿到空文件。 */
|
||||
const WINDOWS_TEMP_VIDEO_GRACE_MS = 10 * 60 * 1000
|
||||
|
||||
// unref: 不让清理定时器拖住进程退出
|
||||
function scheduleTempFileCleanup(target: string, delayMs: number): void {
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
unlinkSync(target)
|
||||
} catch {
|
||||
// best effort
|
||||
}
|
||||
}, delayMs)
|
||||
timer.unref?.()
|
||||
}
|
||||
|
||||
async function requestWindowsHook(
|
||||
endpoint: string,
|
||||
body: Record<string, unknown>,
|
||||
@@ -744,6 +771,7 @@ export class PersonalWechatSendService {
|
||||
canSendText: true,
|
||||
canSendImage: true,
|
||||
canSendVoice: true,
|
||||
canSendVideo: true,
|
||||
message: 'Windows 微信发送能力已连接,可以发送消息'
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -1147,6 +1175,7 @@ export class PersonalWechatSendService {
|
||||
if (!status.canSend) return { success: false, status, error: status.error || status.message }
|
||||
|
||||
let temporaryImagePath: string | undefined
|
||||
let temporaryVideoPath: string | undefined
|
||||
let temporaryVoicePath: string | undefined
|
||||
try {
|
||||
if (request.type === 'text') {
|
||||
@@ -1169,8 +1198,20 @@ export class PersonalWechatSendService {
|
||||
})
|
||||
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 60_000)
|
||||
} else if (request.type === 'video') {
|
||||
// 视频不复制到临时目录:原生 Host 直接按绝对路径读取。
|
||||
const windowsRequest = buildWindowsWechatRequest(request)
|
||||
const preparedVideo = prepareWindowsMediaFile(request.filePath, {
|
||||
prefix: 'tm-video-',
|
||||
fallbackExtension: '.mp4'
|
||||
})
|
||||
temporaryVideoPath = preparedVideo.temporary ? preparedVideo.filePath : undefined
|
||||
logSendDiagnostic('video-prepared', {
|
||||
sourceBytes: safeFileSize(request.filePath),
|
||||
usedTempCopy: preparedVideo.temporary,
|
||||
copiedBytes: safeFileSize(preparedVideo.filePath)
|
||||
})
|
||||
const windowsRequest = buildWindowsWechatRequest({
|
||||
...request,
|
||||
filePath: preparedVideo.filePath
|
||||
})
|
||||
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 180_000)
|
||||
} else if (request.type === 'voice') {
|
||||
const fromId = String(request.fromId || '').trim()
|
||||
@@ -1223,6 +1264,9 @@ export class PersonalWechatSendService {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (temporaryVideoPath) {
|
||||
scheduleTempFileCleanup(temporaryVideoPath, WINDOWS_TEMP_VIDEO_GRACE_MS)
|
||||
}
|
||||
if (temporaryVoicePath) {
|
||||
try {
|
||||
unlinkSync(temporaryVoicePath)
|
||||
|
||||
@@ -30,6 +30,7 @@ function fallbackStatus(error: unknown): PersonalWechatSenderStatus {
|
||||
canSendText: false,
|
||||
canSendImage: false,
|
||||
canSendVoice: false,
|
||||
canSendVideo: false,
|
||||
message: '无法检测 Windows 微信发送能力',
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user