mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 新增群员统计与退群事件,并把本地索引集中到设置页
- 群员统计:档案中按群统计发言排行与未发言成员,可复制纯文本、按平台能力发送 - 退群事件永久保存,并以本地推断条目并入档案消息流 - 设置新增本地索引页,集中管理聊天记录索引与图片文字索引
This commit is contained in:
1 parent
b6d287a299
commit
766cd94788
44 files changed
+3949
-24
No files matched your search
@@ -1036,6 +1036,20 @@ export async function getGroupSnapshotAsync(userMd5: string): Promise<GroupSnaps
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把群会话 md5 解析成原生接口真正需要的 roomId(`xxx@chatroom`)。
|
||||
*
|
||||
* 存在的理由:群员统计从界面拿到的是会话 md5(与 `getGroupSnapshot(userMd5)` 同口径),
|
||||
* 而成员相关的原生接口吃的是 username。没有这层导出,调用方就得自己去碰
|
||||
* `dbRef.getWcdb4Client()`,等于让服务层绕开 chat-service 的封装。
|
||||
* 非群会话或解析不到时返回 null。
|
||||
*/
|
||||
export function resolveGroupRoomId(userMd5: string): string | null {
|
||||
if (!dbRef) return null
|
||||
const roomId = dbRef.getWcdb4Client().getUsernameByMd5(userMd5)
|
||||
return roomId && roomId.endsWith('@chatroom') ? roomId : null
|
||||
}
|
||||
|
||||
/** 退群检测专用轻量读取,不执行成员名称或头像 hydration。 */
|
||||
export async function getGroupMemberIdsAsync(
|
||||
roomId: string
|
||||
|
||||
@@ -57,6 +57,14 @@ type StoredGroupSnapshot = Pick<
|
||||
|
||||
const DB_CHANGE_DEBOUNCE_MS = 350
|
||||
const DUPLICATE_WINDOW_MS = 2 * 60 * 1000
|
||||
/**
|
||||
* **只约束「一次状态回传带多少条」**,不是存储上限。
|
||||
*
|
||||
* 事件现在写在 append-only 的 JSONL 里(`eventsPath()`),**永久保留、不做截断**。
|
||||
* 之所以必须把「存储」和「回传」分开:状态文件是整体重写的(`save()`),
|
||||
* 事件留在里面时每来一条新事件都要重写整个文件 —— 越写越慢。
|
||||
* 而 `getState()` 每次都把结果推过 IPC,也不能无上限。
|
||||
*/
|
||||
const MAX_EVENTS = 500
|
||||
|
||||
export interface GroupExitMonitorServiceDependencies {
|
||||
@@ -104,7 +112,9 @@ class GroupExitMonitorService {
|
||||
getState(): GroupExitMonitorState {
|
||||
this.ensureLoaded()
|
||||
return {
|
||||
events: [...this.events],
|
||||
events: this.events.slice(0, MAX_EVENTS),
|
||||
/** 永久保留的事件总数(`events` 只是最近一批)。 */
|
||||
totalEventCount: this.events.length,
|
||||
enabled: this.enabled,
|
||||
running: this.enabled && this.active && chat.isReady(),
|
||||
nativeMonitorActive: this.nativeMonitorActive,
|
||||
@@ -134,6 +144,7 @@ class GroupExitMonitorService {
|
||||
) {
|
||||
this.actionGateway.clearMemberEvents?.()
|
||||
this.events = []
|
||||
this.rewriteEventsToDisk([])
|
||||
this.lastReadAt = 0
|
||||
this.monitorSelectionConfigured = true
|
||||
this.monitoredRoomIds.clear()
|
||||
@@ -273,9 +284,41 @@ class GroupExitMonitorService {
|
||||
return this.getState()
|
||||
}
|
||||
|
||||
/**
|
||||
* 按群 / 时间范围查退群事件(档案合并展示用)。
|
||||
*
|
||||
* 与 `getState()` 的分工:后者只带回最近 `MAX_EVENTS` 条、且是**给管理页**看的概览;
|
||||
* 档案要的是「某个群在这段时间里的全部事件」,所以单独开一个查询入口,
|
||||
* 直接打在内存里的完整历史上(事件是永久保留的)。
|
||||
*
|
||||
* 返回**按时间升序**(旧 → 新),与档案消息流的顺序一致。
|
||||
*/
|
||||
listEvents(
|
||||
query: { roomId?: string; sinceMs?: number; untilMs?: number; limit?: number } = {}
|
||||
): GroupExitMonitorEvent[] {
|
||||
this.ensureLoaded()
|
||||
const roomId = String(query.roomId || '').trim()
|
||||
const since = Number(query.sinceMs)
|
||||
const until = Number(query.untilMs)
|
||||
const limit = Number(query.limit)
|
||||
|
||||
// this.events 是倒序(新在前)。
|
||||
let result = [...this.events].reverse()
|
||||
if (roomId) result = result.filter((event) => event.roomId === roomId)
|
||||
if (Number.isFinite(since)) result = result.filter((event) => event.detectedAt >= since)
|
||||
if (Number.isFinite(until)) result = result.filter((event) => event.detectedAt <= until)
|
||||
// 超量时保留**最近**的一批(尾部即最新)。
|
||||
if (Number.isFinite(limit) && limit > 0 && result.length > limit) {
|
||||
result = result.slice(-limit)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
clearEvents(): GroupExitMonitorState {
|
||||
this.ensureLoaded()
|
||||
this.events = []
|
||||
// 磁盘上的 append-only 历史也要清掉,否则下次启动又读回来了。
|
||||
this.rewriteEventsToDisk([])
|
||||
this.actionGateway.clearMemberEvents?.()
|
||||
this.lastReadAt = Date.now()
|
||||
this.save()
|
||||
@@ -593,7 +636,10 @@ class GroupExitMonitorService {
|
||||
notificationStatus: 'not_requested'
|
||||
}
|
||||
this.actionGateway.registerMemberEvent?.(event)
|
||||
this.events = [event, ...this.events].slice(0, MAX_EVENTS)
|
||||
// 内存按时间倒序(新事件在前);磁盘**只追加这一条**,不重写历史。
|
||||
// 这里不再有 `.slice(0, MAX_EVENTS)` —— 事件是永久保留的。
|
||||
this.events = [event, ...this.events]
|
||||
this.appendEventsToDisk([event])
|
||||
console.log(
|
||||
`[GroupMonitor] detected member exit roomId=${group.roomId} member=${member.wxid} ${previousCount}->${currentCount}`
|
||||
)
|
||||
@@ -681,13 +727,78 @@ class GroupExitMonitorService {
|
||||
return path.join(app.getPath('userData'), 'group-exit-monitor.json')
|
||||
}
|
||||
|
||||
/**
|
||||
* 退群事件的 append-only 存储(每行一条 JSON)。
|
||||
*
|
||||
* 与状态文件分开,因为两者的写入模式完全不同:
|
||||
* - **状态**(开关 / 监控范围 / 快照 / 模板)小、且总是整体重写;
|
||||
* - **事件**只增不改,且要求**永久保留**。
|
||||
* 混在一个文件里时,每来一条事件都要把整部历史重新序列化写一遍 —— 越写越慢。
|
||||
*/
|
||||
private eventsPath(): string {
|
||||
return path.join(app.getPath('userData'), 'group-exit-monitor-events.jsonl')
|
||||
}
|
||||
|
||||
/** 读全量历史事件。单行损坏只跳过该行,不让整部历史读不出来。 */
|
||||
private readEventsFromDisk(): GroupExitMonitorEvent[] {
|
||||
let raw = ''
|
||||
try {
|
||||
raw = fs.readFileSync(this.eventsPath(), 'utf8')
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
const events: GroupExitMonitorEvent[] = []
|
||||
for (const line of raw.split('\n')) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed) continue
|
||||
try {
|
||||
events.push(JSON.parse(trimmed) as GroupExitMonitorEvent)
|
||||
} catch {
|
||||
// 跳过坏行
|
||||
}
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
/** 只追加新增的那几行,不重写历史。 */
|
||||
private appendEventsToDisk(events: GroupExitMonitorEvent[]): void {
|
||||
if (!events.length) return
|
||||
try {
|
||||
fs.ensureDirSync(path.dirname(this.eventsPath()))
|
||||
const payload = events.map((event) => `${JSON.stringify(event)}\n`).join('')
|
||||
fs.appendFileSync(this.eventsPath(), payload, 'utf8')
|
||||
} catch (error) {
|
||||
console.warn('[GroupMonitor] 追加退群事件失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/** 整体重写事件文件(清空、切换账号、老数据迁移时使用)。 */
|
||||
private rewriteEventsToDisk(events: GroupExitMonitorEvent[]): void {
|
||||
try {
|
||||
fs.ensureDirSync(path.dirname(this.eventsPath()))
|
||||
const payload = events.map((event) => `${JSON.stringify(event)}\n`).join('')
|
||||
fs.writeFileSync(this.eventsPath(), payload, 'utf8')
|
||||
} catch (error) {
|
||||
console.warn('[GroupMonitor] 重写退群事件失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
private ensureLoaded(): void {
|
||||
if (this.loaded) return
|
||||
this.loaded = true
|
||||
try {
|
||||
const stored = fs.readJsonSync(this.filePath()) as StoredState
|
||||
this.enabled = stored.enabled !== false
|
||||
this.events = normalizeEvents(stored.events)
|
||||
// 事件从 append-only 文件读;状态文件不再承载它们。
|
||||
const fromDisk = this.readEventsFromDisk()
|
||||
const legacy = normalizeEvents(stored.events)
|
||||
if (legacy.length && !fromDisk.length) {
|
||||
// 老版本把事件塞在状态文件里 —— 一次性迁移过去,避免这批历史丢失。
|
||||
this.rewriteEventsToDisk(legacy)
|
||||
this.events = legacy
|
||||
} else {
|
||||
this.events = normalizeEvents(fromDisk)
|
||||
}
|
||||
this.actionGateway.registerMemberEvents?.(this.events)
|
||||
this.lastReadAt = Number(stored.lastReadAt) || 0
|
||||
this.accountRoot = String(stored.accountRoot || '')
|
||||
@@ -704,8 +815,9 @@ class GroupExitMonitorService {
|
||||
)
|
||||
this.snapshots = normalizeSnapshots(stored.snapshots, this.monitoredRoomIds)
|
||||
} catch {
|
||||
// 首次启动或文件损坏时从空记录开始。
|
||||
this.events = []
|
||||
// 首次启动或状态文件损坏时从空记录开始 —— 但事件在独立文件里,
|
||||
// 不该被状态文件的问题连累,仍然读回来。
|
||||
this.events = normalizeEvents(this.readEventsFromDisk())
|
||||
this.enabled = true
|
||||
this.lastReadAt = 0
|
||||
this.monitorSelectionConfigured = true
|
||||
@@ -725,7 +837,8 @@ class GroupExitMonitorService {
|
||||
{
|
||||
accountRoot: this.accountRoot,
|
||||
enabled: this.enabled,
|
||||
events: this.events,
|
||||
// 事件**不在这里**:它们走 append-only 的 JSONL(见 `eventsPath()`)。
|
||||
// 放进状态文件会让每新增一条事件都把整部历史重写一遍。
|
||||
lastReadAt: this.lastReadAt,
|
||||
monitorSelectionConfigured: this.monitorSelectionConfigured,
|
||||
monitoredRoomIds: Array.from(this.monitoredRoomIds),
|
||||
@@ -935,7 +1048,7 @@ function normalizeEvents(
|
||||
? { notification: normalizeNotification(value.notification) }
|
||||
: {})
|
||||
})
|
||||
if (normalized.length >= MAX_EVENTS) break
|
||||
// 不再按 MAX_EVENTS 截断:事件是永久保留的,截在这里等于每次启动都丢掉历史。
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import { isKnowledgeFresh } from '../../shared/knowledge'
|
||||
import {
|
||||
GROUP_STATS_LIMITATION,
|
||||
GROUP_STATS_STALE_LIMITATION,
|
||||
type GroupMemberStatsActiveMember,
|
||||
type GroupMemberStatsQuery,
|
||||
type GroupMemberStatsResult,
|
||||
type GroupMemberStatsSilentMember,
|
||||
type GroupStatsFreshness
|
||||
} from '../../shared/group-stats'
|
||||
import type { KnowledgeSearchService } from '../knowledge/knowledge-search-service'
|
||||
import * as chat from './chat-service'
|
||||
|
||||
/**
|
||||
* 触发一次追赶同步的最小间隔。
|
||||
*
|
||||
* 面板是可以反复开关的交互入口,而追赶同步跑的是真实增量 pass(会读 WCDB)。
|
||||
* 没有这个节流,连续点击就等于连续触发索引。
|
||||
*/
|
||||
const CATCH_UP_MIN_INTERVAL_MS = 30_000
|
||||
|
||||
/**
|
||||
* 追赶的有界等待预算。
|
||||
*
|
||||
* 与 Query 侧同一取舍:全量追赶可能以分钟计,交互查询绝不能无限等。
|
||||
* 预算用完之后**如实**把结果标成不完整,而不是假装完整。
|
||||
*/
|
||||
const FRESHNESS_WAIT_BUDGET_MS = 2_000
|
||||
|
||||
/**
|
||||
* 群员统计。
|
||||
*
|
||||
* 数据两路来源,职责严格分开:
|
||||
* - **当前成员名单** 走 WCDB 的轻路径(只取 wxid + 显示名,**不** hydrate 头像);
|
||||
* - **发言聚合** 走 Knowledge 派生库的 `GROUP BY sender_id`,不读 WCDB 原始消息。
|
||||
*
|
||||
* 「未发言」= 当前成员 ∖ 窗口内有发言的 sender。这个定义**不能**简化成
|
||||
* 「整段窗口都没说话」—— 入群/退群时间在源头就不存在(整个 DB 没有该字段),
|
||||
* 所以结论必须带上 limitation。
|
||||
*/
|
||||
export class GroupStatsService {
|
||||
constructor(private readonly knowledge: KnowledgeSearchService) {}
|
||||
|
||||
async getMemberStats(query: GroupMemberStatsQuery): Promise<GroupMemberStatsResult> {
|
||||
const { userMd5, startTime, endTime } = query
|
||||
const limitations = [GROUP_STATS_LIMITATION]
|
||||
|
||||
const roomId = chat.resolveGroupRoomId(userMd5)
|
||||
if (!roomId) {
|
||||
// 不是群 / md5 解析不到:如实返回空,不编造统计。
|
||||
return this.build({
|
||||
userMd5,
|
||||
startTime,
|
||||
endTime,
|
||||
freshness: 'unknown',
|
||||
limitations,
|
||||
members: [],
|
||||
activeMembers: [],
|
||||
silentMembers: [],
|
||||
unattributedMessages: 0,
|
||||
excludedSystemMessages: 0,
|
||||
firstMessageTime: null
|
||||
})
|
||||
}
|
||||
|
||||
// 1) 当前群成员 —— 轻路径。只取 wxid,再按需解析显示名;绝不走
|
||||
// `getGroupSnapshotAsync`(它会 materialize 整群并 hydrate 头像,实测 8 群 ≈ 42s)。
|
||||
const membership = await chat.getGroupMemberIdsAsync(roomId)
|
||||
const memberIds = membership?.memberIds ?? []
|
||||
const members = await chat.getGroupMemberNamesAsync(userMd5, memberIds)
|
||||
|
||||
// 2) 发言聚合(只统计当前群;系统消息在 SQL 层就被排除)
|
||||
let { result, sourceLatestAt } = await this.knowledge.memberStats({
|
||||
conversationId: userMd5,
|
||||
startTime,
|
||||
endTime
|
||||
})
|
||||
let freshness = judgeFreshness(result?.indexLatestAt ?? null, sourceLatestAt)
|
||||
|
||||
// 3) 索引没追平 → 有界追赶一次再判。追不上就如实标 stale,
|
||||
// **不允许**把落后索引算出来的「未发言」包装成完整结论。
|
||||
if (freshness !== 'fresh') {
|
||||
this.knowledge.requestCatchUp(CATCH_UP_MIN_INTERVAL_MS)
|
||||
const settled = await this.knowledge.waitForIndexingComplete(FRESHNESS_WAIT_BUDGET_MS)
|
||||
if (settled) {
|
||||
const retried = await this.knowledge.memberStats({
|
||||
conversationId: userMd5,
|
||||
startTime,
|
||||
endTime
|
||||
})
|
||||
result = retried.result
|
||||
sourceLatestAt = retried.sourceLatestAt
|
||||
freshness = judgeFreshness(result?.indexLatestAt ?? null, sourceLatestAt)
|
||||
}
|
||||
}
|
||||
|
||||
// 4) 差集:当前成员 × 窗口内发言
|
||||
const statBySender = new Map<string, { messageCount: number; lastMessageTime: number }>()
|
||||
for (const row of result?.senders ?? []) {
|
||||
if (row.senderId) statBySender.set(row.senderId, row)
|
||||
}
|
||||
|
||||
const knownSenderIds = new Set<string>()
|
||||
const activeMembers: GroupMemberStatsActiveMember[] = []
|
||||
const silentMembers: GroupMemberStatsSilentMember[] = []
|
||||
|
||||
for (const member of members) {
|
||||
const wxid = String(member.wxid || '').trim()
|
||||
if (!wxid) continue
|
||||
knownSenderIds.add(wxid)
|
||||
// 与 Knowledge 的 Join key 必须是 wxid,不是昵称 —— 昵称会变。
|
||||
// 显示名沿用项目既有优先级(nickname 已内含 `wechatNickname || groupNickname || username`)。
|
||||
const displayName = member.nickname || member.remark || wxid
|
||||
const groupNickname = member.groupNickname || ''
|
||||
const stat = statBySender.get(wxid)
|
||||
if (stat && stat.messageCount > 0) {
|
||||
activeMembers.push({
|
||||
senderId: wxid,
|
||||
displayName,
|
||||
groupNickname,
|
||||
messageCount: stat.messageCount,
|
||||
lastMessageTime: stat.lastMessageTime
|
||||
})
|
||||
} else {
|
||||
silentMembers.push({ senderId: wxid, displayName, groupNickname })
|
||||
}
|
||||
}
|
||||
|
||||
// 窗口内有发言、但已不在当前成员名单里的人(退群者)。
|
||||
// 默认**不**进活跃榜:那份名单读作「当前群成员」,混入已退群的人会误导。
|
||||
let formerSenderCount = 0
|
||||
for (const senderId of statBySender.keys()) {
|
||||
if (!knownSenderIds.has(senderId)) formerSenderCount += 1
|
||||
}
|
||||
|
||||
activeMembers.sort(
|
||||
(a, b) => b.messageCount - a.messageCount || b.lastMessageTime - a.lastMessageTime
|
||||
)
|
||||
silentMembers.sort((a, b) => a.displayName.localeCompare(b.displayName, 'zh-Hans-CN'))
|
||||
|
||||
if (freshness !== 'fresh') limitations.push(GROUP_STATS_STALE_LIMITATION)
|
||||
if (formerSenderCount > 0) {
|
||||
limitations.push(
|
||||
`另有 ${formerSenderCount} 位窗口内发言者已不在当前群成员名单中,未计入活跃榜。`
|
||||
)
|
||||
}
|
||||
|
||||
return this.build({
|
||||
userMd5,
|
||||
startTime,
|
||||
endTime,
|
||||
freshness,
|
||||
limitations,
|
||||
members,
|
||||
activeMembers,
|
||||
silentMembers,
|
||||
unattributedMessages: result?.unattributedMessages ?? 0,
|
||||
excludedSystemMessages: result?.excludedSystemMessages ?? 0,
|
||||
firstMessageTime: result?.earliestMessageTime ?? null
|
||||
})
|
||||
}
|
||||
|
||||
private build(input: {
|
||||
userMd5: string
|
||||
startTime: number
|
||||
endTime: number
|
||||
freshness: GroupStatsFreshness
|
||||
limitations: string[]
|
||||
members: Array<{ wxid: string }>
|
||||
activeMembers: GroupMemberStatsActiveMember[]
|
||||
silentMembers: GroupMemberStatsSilentMember[]
|
||||
unattributedMessages: number
|
||||
excludedSystemMessages: number
|
||||
firstMessageTime: number | null
|
||||
}): GroupMemberStatsResult {
|
||||
return {
|
||||
conversationId: input.userMd5,
|
||||
startTime: input.startTime,
|
||||
endTime: input.endTime,
|
||||
freshness: input.freshness,
|
||||
// 只有索引确实追平,才允许调用方把「未发言」当作完整结论。
|
||||
complete: input.freshness === 'fresh',
|
||||
memberCount: input.members.length,
|
||||
activeMemberCount: input.activeMembers.length,
|
||||
silentMemberCount: input.silentMembers.length,
|
||||
activeMembers: input.activeMembers,
|
||||
silentMembers: input.silentMembers,
|
||||
unattributedMessages: input.unattributedMessages,
|
||||
excludedSystemMessages: input.excludedSystemMessages,
|
||||
firstMessageTime: input.firstMessageTime,
|
||||
limitations: input.limitations
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `isKnowledgeFresh` 返回 `boolean | null`(任一侧口径缺失即 null)。
|
||||
* 三态都要能表达:`null` 绝不能当成「新鲜」。
|
||||
*/
|
||||
function judgeFreshness(
|
||||
indexLatestAt: number | null,
|
||||
sourceLatestAt: number | null
|
||||
): GroupStatsFreshness {
|
||||
const fresh = isKnowledgeFresh({ indexLatestAt, sourceLatestAt })
|
||||
if (fresh === true) return 'fresh'
|
||||
if (fresh === false) return 'stale'
|
||||
return 'unknown'
|
||||
}
|
||||
Reference in new issue
Block a user