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
c835d5c570
commit
4d5c6459fe
49 files changed
+6436
-4863
No files matched your search
@@ -5,24 +5,30 @@ import {
|
||||
DEFAULT_REPLY_TEXT,
|
||||
automationIdempotencyKey,
|
||||
normalizeReplyDelaySeconds,
|
||||
scheduledReportRangeLabel,
|
||||
type AutomationAction,
|
||||
type AutomationExecutionTrigger,
|
||||
type AutomationRule,
|
||||
type AutomationStep,
|
||||
type AutomationStepKey,
|
||||
type LeaveNotificationConfig
|
||||
type LeaveNotificationConfig,
|
||||
type ScheduledReportAutomationConfig
|
||||
} from '../../shared/automation'
|
||||
import {
|
||||
renderLeaveNotificationText,
|
||||
type GroupMemberExitedEvent
|
||||
} from '../../shared/group-exit-event'
|
||||
import type { WechatActionContent, WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
|
||||
import type { SaveGeneratedReportRequest, SaveGeneratedReportResult } from '../../shared/report-history'
|
||||
import {
|
||||
generateAgentGroupReport,
|
||||
type AgentGroupReportRequest,
|
||||
type AgentGroupReportResult
|
||||
} from './agent-group-report-service'
|
||||
import { wechatActionGateway } from './wechat-action-gateway'
|
||||
import type { LeaveNotificationTargetResolution } from './leave-notification-target'
|
||||
import { saveGeneratedReport } from '../report-history-service'
|
||||
import { getContactAvatars, resolveMd5 } from './chat-service'
|
||||
import type { AutomationTargetResolution } from './automation-wechat-target'
|
||||
|
||||
/**
|
||||
* AutomationActionRunner —— 把一次命中跑成**步骤序列**。
|
||||
@@ -46,6 +52,20 @@ const LEAVE_NOTIFICATION_STEP_ORDER: AutomationStepKey[] = [
|
||||
'exit_send'
|
||||
]
|
||||
|
||||
/**
|
||||
* 定时日报的步骤顺序(与另外两族**不共用**)。
|
||||
*
|
||||
* 「生成中 / 已生成」与「确定目标 / 已发送」**刻意拆成四步**:
|
||||
* 用户必须能一眼看出"日报确实生成了,只是没发出去" —— 合成两步就表达不了。
|
||||
*/
|
||||
const SCHEDULED_REPORT_STEP_ORDER: AutomationStepKey[] = [
|
||||
'schedule_triggered',
|
||||
'report_generating',
|
||||
'report_generated',
|
||||
'send_resolved',
|
||||
'report_sent'
|
||||
]
|
||||
|
||||
/**
|
||||
* 前置步骤失败时,后续步骤的 `skipReason`。
|
||||
*
|
||||
@@ -54,6 +74,15 @@ const LEAVE_NOTIFICATION_STEP_ORDER: AutomationStepKey[] = [
|
||||
const SKIPPED_AFTER_REPLY_FAILURE = '前置步骤失败(回复确认未成功),本次不再继续。'
|
||||
const SKIPPED_AFTER_REPORT_FAILURE = '前置步骤失败(日报未生成),没有图片可发送。'
|
||||
|
||||
/**
|
||||
* 定时日报「生成 / 落库」失败时,后续步骤的 `skipReason`。
|
||||
*
|
||||
* 与 `SKIPPED_AFTER_REPORT_FAILURE` 的区别:那条说的是「@我日报没图可发」,
|
||||
* 这条说的是「定时日报这一步就没跑起来」—— 文案分开,避免用户混淆两条链路。
|
||||
*/
|
||||
const SKIPPED_AFTER_SCHEDULED_GENERATION_FAILURE =
|
||||
'前置步骤失败(定时日报未生成或未保存),本次未发送。'
|
||||
|
||||
/**
|
||||
* 规则启用了「发送日报图片」,但手上没有图片文件。
|
||||
*
|
||||
@@ -90,7 +119,7 @@ export interface LeaveNotificationRunInput {
|
||||
executionId: string
|
||||
event: GroupMemberExitedEvent
|
||||
config: LeaveNotificationConfig
|
||||
resolution: LeaveNotificationTargetResolution
|
||||
resolution: AutomationTargetResolution
|
||||
/** 事件来源的显示名(群名 / 「群聊」)。**不含 wxid**。 */
|
||||
sourceDisplayName: string
|
||||
/** 发送能力缺失时的一句话说明;有值时 `exit_send` 直接判失败。 */
|
||||
@@ -103,12 +132,69 @@ export interface LeaveNotificationRunResult {
|
||||
errorSummary?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时日报的执行输入。
|
||||
*
|
||||
* 与退群通知同构:目标解析、来源显示名、发送能力预检都在 `AutomationService`
|
||||
* 调用前算好,runner 只负责"跑成步骤序列"。
|
||||
*/
|
||||
export interface ScheduledReportRunInput {
|
||||
executionId: string
|
||||
rule: AutomationRule
|
||||
config: ScheduledReportAutomationConfig
|
||||
resolution: AutomationTargetResolution
|
||||
/** 日报来源群的显示名(群名 / 「日报来源群」)。**不含 roomId**。 */
|
||||
sourceDisplayName: string
|
||||
/**
|
||||
* 本次触发方式。
|
||||
*
|
||||
* 只影响**发送节流口径**:定时触发算 `automation`(纳入发送节流),
|
||||
* 用户在页面上点「立即执行」算 `user`(与旧定时日报的手动执行一致)。
|
||||
* 执行日志里的 `trigger` 由 `AutomationService` 单独记录,不从这里读。
|
||||
*/
|
||||
trigger: Extract<AutomationExecutionTrigger, 'schedule' | 'manual'>
|
||||
/** 发送能力缺失时的一句话说明;有值时 `report_sent` 直接判失败。 */
|
||||
sendBlockedReason?: string
|
||||
}
|
||||
|
||||
export interface ScheduledReportRunResult {
|
||||
steps: AutomationStep[]
|
||||
status: 'success' | 'failed'
|
||||
errorSummary?: string
|
||||
/**
|
||||
* 日报是否**已经生成并落库**。
|
||||
*
|
||||
* 这是「生成成功但发送失败」的判据:`reportGenerated === true && status === 'failed'`
|
||||
* 就是"日报在,只是没发出去"。日报本身已进日报历史,不会被丢掉。
|
||||
*/
|
||||
reportGenerated: boolean
|
||||
/** 生成出来的 PNG(仅在内存里传递,**不落执行日志**)。 */
|
||||
pngPath?: string
|
||||
/**
|
||||
* 底层生成错误的**机器可读码**(例如 `NO_MESSAGES`)。
|
||||
*
|
||||
* 用途只有一个:让上层区分「真的失败了」和「这一天没有消息可生成」——
|
||||
* 后者不该给用户推微信异常通知。
|
||||
*/
|
||||
errorCode?: string
|
||||
}
|
||||
|
||||
export interface AutomationActionRunnerDependencies {
|
||||
generateReport?: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
|
||||
executeAction?: (request: WechatActionRequest) => Promise<WechatActionResult>
|
||||
now?: () => number
|
||||
/** 延迟实现。默认真 sleep;单测注入即时 resolve 的假实现,避免真的等 2 秒。 */
|
||||
delay?: (ms: number) => Promise<void>
|
||||
/** 日报落库(日报历史)。与旧定时日报**复用同一个**实现,不复制。 */
|
||||
saveGeneratedReport?: (request: SaveGeneratedReportRequest) => Promise<SaveGeneratedReportResult>
|
||||
/** 把日报来源群标识解析成联系人(拿头像 / 显示名)。 */
|
||||
resolveReportContact?: (raw: string) => {
|
||||
md5?: string
|
||||
m_nsUsrName?: string
|
||||
m_nsNickName?: string
|
||||
avatar?: string
|
||||
} | null
|
||||
getContactAvatars?: (usernames: string[]) => Promise<Record<string, string>>
|
||||
}
|
||||
|
||||
/** 策略层的错误码 → 用户可读短句。UI 直接展示这些文案,不做二次翻译。 */
|
||||
@@ -161,6 +247,13 @@ export class AutomationActionRunner {
|
||||
private readonly executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
|
||||
private readonly now: () => number
|
||||
private readonly delay: (ms: number) => Promise<void>
|
||||
private readonly saveGeneratedReport: (
|
||||
request: SaveGeneratedReportRequest
|
||||
) => Promise<SaveGeneratedReportResult>
|
||||
private readonly resolveReportContact: NonNullable<
|
||||
AutomationActionRunnerDependencies['resolveReportContact']
|
||||
>
|
||||
private readonly getContactAvatars: (usernames: string[]) => Promise<Record<string, string>>
|
||||
|
||||
constructor(dependencies: AutomationActionRunnerDependencies = {}) {
|
||||
this.generateReport = dependencies.generateReport ?? generateAgentGroupReport
|
||||
@@ -169,6 +262,9 @@ export class AutomationActionRunner {
|
||||
this.delay =
|
||||
dependencies.delay ??
|
||||
((ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
|
||||
this.saveGeneratedReport = dependencies.saveGeneratedReport ?? saveGeneratedReport
|
||||
this.resolveReportContact = dependencies.resolveReportContact ?? ((raw) => resolveMd5(raw))
|
||||
this.getContactAvatars = dependencies.getContactAvatars ?? ((ids) => getContactAvatars(ids))
|
||||
}
|
||||
|
||||
async run(input: AutomationRunInput): Promise<AutomationRunResult> {
|
||||
@@ -273,6 +369,224 @@ export class AutomationActionRunner {
|
||||
return { steps, status: 'success', pngPath }
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时日报:把一次「到点触发 / 手动立即执行」跑成一次生成 + 一次发送。
|
||||
*
|
||||
* 与旧 `ScheduledReportService.executeTask` 的行为对齐(**不重写日报能力**):
|
||||
* 1. 先生成(含落库进日报历史)—— 发送能力不足**也照常生成**(旧语义如此);
|
||||
* 2. 再解析目标 —— 解析失败**不 fallback**,直接判失败;
|
||||
* 3. 最后经 `WechatActionGateway` 发图片 —— 仍然是**发图片**,不退化成纯文本。
|
||||
*
|
||||
* 「生成成功但发送失败」是可表达的:`report_generated` 为 success、
|
||||
* `report_sent` 为 failed,整体 `failed`,且 `reportGenerated === true`。
|
||||
*/
|
||||
async runScheduledReport(input: ScheduledReportRunInput): Promise<ScheduledReportRunResult> {
|
||||
const steps = SCHEDULED_REPORT_STEP_ORDER.map((key) => createStep(key))
|
||||
const stepAt = (key: AutomationStepKey): AutomationStep =>
|
||||
steps.find((step) => step.key === key) as AutomationStep
|
||||
|
||||
markSuccess(stepAt('schedule_triggered'), this.now())
|
||||
|
||||
// ---- 生成日报(含落进日报历史)----
|
||||
const generatingStep = stepAt('report_generating')
|
||||
generatingStep.status = 'running'
|
||||
generatingStep.startedAt = this.now()
|
||||
let generated: AgentGroupReportResult
|
||||
try {
|
||||
generated = await this.generateReport({
|
||||
group: input.config.report.sourceConversationId,
|
||||
range: input.config.report.range,
|
||||
messageTypes: input.config.report.messageTypes,
|
||||
templateId: input.config.report.templateId,
|
||||
memberNameMode: input.config.report.memberNameMode,
|
||||
timeoutSeconds: input.config.report.timeoutSeconds
|
||||
})
|
||||
} catch (error) {
|
||||
generated = {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
if (!generated.success || !generated.pngPath) {
|
||||
// 生成失败就**不发**:绝不生成空图片、也绝不退而求其次发上一张旧图。
|
||||
const reason = generated.error || '日报生成失败'
|
||||
markFailed(generatingStep, this.now(), reason)
|
||||
markSkipped(stepAt('report_generated'), SKIPPED_AFTER_SCHEDULED_GENERATION_FAILURE)
|
||||
markSkipped(stepAt('send_resolved'), SKIPPED_AFTER_SCHEDULED_GENERATION_FAILURE)
|
||||
markSkipped(stepAt('report_sent'), SKIPPED_AFTER_SCHEDULED_GENERATION_FAILURE)
|
||||
return {
|
||||
steps,
|
||||
status: 'failed',
|
||||
errorSummary: reason,
|
||||
reportGenerated: false,
|
||||
...(generated.errorCode ? { errorCode: generated.errorCode } : {})
|
||||
}
|
||||
}
|
||||
|
||||
let pngPath = generated.pngPath
|
||||
try {
|
||||
const reportContact = this.resolveReportContact(input.config.report.sourceConversationId)
|
||||
let contactAvatar = reportContact?.avatar
|
||||
if (!contactAvatar && reportContact?.m_nsUsrName) {
|
||||
try {
|
||||
const avatars = await this.getContactAvatars([reportContact.m_nsUsrName])
|
||||
contactAvatar = avatars[reportContact.m_nsUsrName]
|
||||
} catch (error) {
|
||||
console.warn('[Automation] 日报群头像补全失败:', error)
|
||||
}
|
||||
}
|
||||
const savedHistory = await this.saveGeneratedReport({
|
||||
contactId: reportContact?.md5 || input.config.report.sourceConversationId,
|
||||
contactName:
|
||||
generated.groupName || reportContact?.m_nsNickName || input.sourceDisplayName || '群聊',
|
||||
contactAvatar,
|
||||
source: 'scheduled',
|
||||
dateRange: generated.reportMetadata?.dateRange || scheduledReportRangeLabel(input.config.report.range),
|
||||
reportDate: generated.reportMetadata?.reportDate,
|
||||
messageCount: generated.messageCount ?? generated.reportMetadata?.messageCount ?? 0,
|
||||
generatedAt: new Date(this.now()).toISOString(),
|
||||
htmlPath: generated.htmlPath,
|
||||
pngPath: generated.pngPath,
|
||||
duration: generated.duration,
|
||||
modelName: generated.modelName,
|
||||
tokenUsage: generated.tokenUsage,
|
||||
reportSnapshot: generated.reportSnapshot,
|
||||
reportMetadata: generated.reportMetadata,
|
||||
templateId: input.config.report.templateId
|
||||
})
|
||||
if (!savedHistory.success) {
|
||||
throw new Error(savedHistory.error || '日报历史保存失败')
|
||||
}
|
||||
const recordPath = savedHistory.record?.pngPath || generated.pngPath
|
||||
if (!recordPath) throw new Error('日报历史未返回可发送的 PNG 文件')
|
||||
pngPath = recordPath
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
markFailed(generatingStep, this.now(), reason)
|
||||
markSkipped(stepAt('report_generated'), SKIPPED_AFTER_SCHEDULED_GENERATION_FAILURE)
|
||||
markSkipped(stepAt('send_resolved'), SKIPPED_AFTER_SCHEDULED_GENERATION_FAILURE)
|
||||
markSkipped(stepAt('report_sent'), SKIPPED_AFTER_SCHEDULED_GENERATION_FAILURE)
|
||||
return { steps, status: 'failed', errorSummary: reason, reportGenerated: false }
|
||||
}
|
||||
markSuccess(generatingStep, this.now())
|
||||
|
||||
const generatedStep = stepAt('report_generated')
|
||||
markSuccess(generatedStep, this.now())
|
||||
const messageCount = generated.messageCount ?? 0
|
||||
if (messageCount > 0) generatedStep.detail = `共 ${messageCount} 条消息`
|
||||
|
||||
// ---- 目标解析失败:不许 fallback 到任何地方,直接判失败 ----
|
||||
const targetStep = stepAt('send_resolved')
|
||||
if (!input.resolution.ok) {
|
||||
markFailed(targetStep, this.now(), input.resolution.error)
|
||||
markSkipped(stepAt('report_sent'), '没有可用的发送目标,本次未发送。')
|
||||
return {
|
||||
steps,
|
||||
status: 'failed',
|
||||
errorSummary: input.resolution.error,
|
||||
reportGenerated: true,
|
||||
pngPath
|
||||
}
|
||||
}
|
||||
targetStep.status = 'success'
|
||||
targetStep.startedAt = this.now()
|
||||
targetStep.finishedAt = targetStep.startedAt
|
||||
targetStep.durationMs = 0
|
||||
// 用户可读的目标名(例如「文件传输助手」「张三」「我」)—— 不带任何 id。
|
||||
targetStep.detail = input.resolution.target.displayName
|
||||
|
||||
const sendStep = stepAt('report_sent')
|
||||
|
||||
// ---- 发送能力缺失:日报已生成,如实判失败(不回滚、不隐藏)----
|
||||
if (input.sendBlockedReason) {
|
||||
markFailed(sendStep, this.now(), input.sendBlockedReason)
|
||||
return {
|
||||
steps,
|
||||
status: 'failed',
|
||||
errorSummary: input.sendBlockedReason,
|
||||
reportGenerated: true,
|
||||
pngPath
|
||||
}
|
||||
}
|
||||
|
||||
sendStep.status = 'running'
|
||||
sendStep.startedAt = this.now()
|
||||
const sent = await this.sendScheduledReportImage(input, pngPath)
|
||||
if (!sent.ok) {
|
||||
markFailed(sendStep, this.now(), sent.error || '发送日报失败')
|
||||
return {
|
||||
steps,
|
||||
status: 'failed',
|
||||
errorSummary: sendStep.error,
|
||||
reportGenerated: true,
|
||||
pngPath
|
||||
}
|
||||
}
|
||||
markSuccess(sendStep, this.now())
|
||||
return { steps, status: 'success', reportGenerated: true, pngPath }
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时日报的统一发送出口。
|
||||
*
|
||||
* **必须走 `WechatActionGateway`**:幂等 + 3 秒发送间隔 + 审计落盘都在那里。
|
||||
* Automation 层不允许知道 OneBot / WCHook / native host / Windows hook 的存在。
|
||||
*/
|
||||
private async sendScheduledReportImage(
|
||||
input: ScheduledReportRunInput,
|
||||
pngPath: string
|
||||
): Promise<{ ok: boolean; error?: string }> {
|
||||
if (!input.resolution.ok) return { ok: false, error: input.resolution.error }
|
||||
// 定时触发走 automation(纳入发送节流);用户手动执行走 user(不纳入节流)。
|
||||
const triggerType = input.trigger === 'manual' ? 'user' : 'automation'
|
||||
try {
|
||||
const result = await this.executeAction({
|
||||
idempotencyKey: `${AUTOMATION_SEND_PURPOSE.scheduledReport}:${input.executionId}`,
|
||||
origin: AUTOMATION_SEND_ORIGIN,
|
||||
purpose: AUTOMATION_SEND_PURPOSE.scheduledReport,
|
||||
triggerType,
|
||||
executionId: input.executionId,
|
||||
recipient: input.resolution.target.recipient,
|
||||
content: { type: 'image', path: pngPath }
|
||||
})
|
||||
if (result.status !== 'sent') {
|
||||
return { ok: false, error: actionErrorMessage(result.errorCode, result.reason) }
|
||||
}
|
||||
|
||||
/*
|
||||
* 后置词:**只在图片明确 sent 之后**才发,图片失败时严格短路 ——
|
||||
* 与 `WechatActionGateway.executeReportImageSequence`(手动发送)同一口径。
|
||||
* 空字符串 = 用户只要图片,什么都不补发。
|
||||
*
|
||||
* 独立 purpose + 独立幂等位:共用一个 key 会让「图片发成功、后置词被
|
||||
* 幂等短路」变成常态。
|
||||
*/
|
||||
const postfixText = String(input.config.postfixText || '').trim()
|
||||
if (!postfixText) return { ok: true }
|
||||
|
||||
const postfix = await this.executeAction({
|
||||
idempotencyKey: `${AUTOMATION_SEND_PURPOSE.scheduledReportPostfix}:${input.executionId}`,
|
||||
origin: AUTOMATION_SEND_ORIGIN,
|
||||
purpose: AUTOMATION_SEND_PURPOSE.scheduledReportPostfix,
|
||||
triggerType,
|
||||
executionId: input.executionId,
|
||||
recipient: input.resolution.target.recipient,
|
||||
content: { type: 'text', text: postfixText }
|
||||
})
|
||||
if (postfix.status === 'sent') return { ok: true }
|
||||
// 绝不吞掉:图片确实发出去了,但这一次执行**没有完成**,必须如实报出来。
|
||||
return {
|
||||
ok: false,
|
||||
error: `日报图片已发送,但后置词发送失败:${actionErrorMessage(
|
||||
postfix.errorCode,
|
||||
postfix.reason
|
||||
)}`
|
||||
}
|
||||
} catch (error) {
|
||||
return { ok: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 退群通知:把「检测到成员退出」这件事跑成一次发送。
|
||||
*
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import path from 'node:path'
|
||||
import { app } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import type { AutomationExecution } from '../../shared/automation'
|
||||
import type {
|
||||
AutomationExecution,
|
||||
AutomationExecutionTrigger
|
||||
} from '../../shared/automation'
|
||||
|
||||
/**
|
||||
* AutomationExecutionLogService —— **用户层**执行日志。
|
||||
@@ -24,6 +27,8 @@ export interface AutomationExecutionLogDependencies {
|
||||
|
||||
const EXECUTION_STATUSES: AutomationExecution['status'][] = ['running', 'success', 'failed']
|
||||
|
||||
const EXECUTION_TRIGGERS: AutomationExecutionTrigger[] = ['message', 'exit', 'schedule', 'manual']
|
||||
|
||||
function normalizeExecution(value: unknown): AutomationExecution | null {
|
||||
if (!value || typeof value !== 'object') return null
|
||||
const record = value as Partial<AutomationExecution>
|
||||
@@ -34,6 +39,17 @@ function normalizeExecution(value: unknown): AutomationExecution | null {
|
||||
ruleId: String(record.ruleId || ''),
|
||||
ruleName: String(record.ruleName || ''),
|
||||
triggerTime: Number(record.triggerTime) || 0,
|
||||
/*
|
||||
* `trigger` 必须在这里**显式透传**。
|
||||
*
|
||||
* 这个归一化是白名单式的:没列出来的字段会被静默丢掉。定时日报的
|
||||
* 「本次是定时跑的还是用户点的立即执行」全靠这个字段区分,
|
||||
* 漏掉它就会变成"写的时候有、读出来永远没有"—— 而且没有任何报错。
|
||||
* 旧记录没有这个字段,保持 `undefined`(读盘不猜测)。
|
||||
*/
|
||||
...(EXECUTION_TRIGGERS.includes(record.trigger as AutomationExecutionTrigger)
|
||||
? { trigger: record.trigger as AutomationExecutionTrigger }
|
||||
: {}),
|
||||
sourceDisplayName: String(record.sourceDisplayName || ''),
|
||||
// 不认识的 status(含历史遗留值)一律降级成 `running`,绝不凭空造出成功/失败。
|
||||
status: EXECUTION_STATUSES.includes(record.status as AutomationExecution['status'])
|
||||
|
||||
@@ -6,15 +6,22 @@ import {
|
||||
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
|
||||
createDefaultDailyReportRule,
|
||||
createDefaultLeaveNotificationRule,
|
||||
createDefaultScheduledReportRule,
|
||||
normalizeRuleDraft,
|
||||
type AutomationRule,
|
||||
type AutomationRuleType
|
||||
type AutomationRuleType,
|
||||
type ScheduledReportAutomationConfig
|
||||
} from '../../shared/automation'
|
||||
import {
|
||||
planLeaveNotificationMigration,
|
||||
type LeaveNotificationMigrationPlan,
|
||||
type LegacyLeaveNotificationState
|
||||
} from './leave-notification-migration'
|
||||
import {
|
||||
planScheduledReportMigrationBatch,
|
||||
type LegacyScheduledReportTask,
|
||||
type ScheduledReportMigrationSummary
|
||||
} from './scheduled-report-migration'
|
||||
import {
|
||||
GROUP_EXIT_NOTIFICATION_TEMPLATE_MAX_LENGTH,
|
||||
insertGroupNamePlaceholder
|
||||
@@ -26,12 +33,10 @@ import {
|
||||
* 存储形态刻意做到最简:一个 JSON 文件(`{userData}/automation/rules.json`)。
|
||||
* 规则总量是个位数到几十条,引入数据库只会增加迁移负担。
|
||||
*
|
||||
* **内置规则的播种标记(`builtinSeeded`)单独存**:
|
||||
* **一次性标记全部单独存**(`builtinSeeded` / `leaveNotificationMigrated` /
|
||||
* `notificationTemplateUpgraded` / `scheduledReportMigrated`):
|
||||
* 如果靠"文件里有没有那条内置规则"来判断是否播种,用户一旦删掉它,
|
||||
* 下次启动就会被重新塞回来 —— 用户会认为删除功能坏了。
|
||||
*
|
||||
* 退群通知的迁移标记(`leaveNotificationMigrated`)同理:迁移**只允许跑一次**,
|
||||
* 否则用户删掉退群通知规则后重启又被塞回来。
|
||||
* 下次启动就会被重新塞回来 —— 用户会认为删除功能坏了。迁移同理。
|
||||
*/
|
||||
|
||||
const STORAGE_DIR = 'automation'
|
||||
@@ -39,7 +44,11 @@ const RULES_FILE = 'rules.json'
|
||||
const MIGRATION_BACKUP_FILE = 'leave-notification-migration-backup.json'
|
||||
/** 旧退群监控的状态文件(迁移时读一次,之后运行期不再读)。 */
|
||||
const LEGACY_MONITOR_FILE = 'group-exit-monitor.json'
|
||||
const CURRENT_VERSION = 3
|
||||
/** 旧定时日报的**任务**文件(迁移时读一次,之后运行期不再读)。 */
|
||||
const LEGACY_SCHEDULED_DIR = 'scheduled-reports'
|
||||
const LEGACY_SCHEDULED_TASKS_FILE = 'tasks.json'
|
||||
const SCHEDULED_MIGRATION_BACKUP_FILE = 'scheduled-report-migration-backup.json'
|
||||
const CURRENT_VERSION = 4
|
||||
|
||||
interface StoredRules {
|
||||
version: number
|
||||
@@ -54,12 +63,27 @@ interface StoredRules {
|
||||
* 于是用户主动删掉那一行后、下次启动又会被补回来 —— 删不掉的东西最烦人。
|
||||
*/
|
||||
notificationTemplateUpgraded: boolean
|
||||
/**
|
||||
* 旧「定时日报」任务是否已经迁移过。
|
||||
*
|
||||
* ⚠️ 与其它标记有一点不同:迁移需要**把旧群标识解析成稳定会话 id**,
|
||||
* 而那需要数据库。数据库没就绪时这一位**保持 false**,等解析器注入后再补跑 ——
|
||||
* 否则会把每一条规则都误判成"目标无法确认"。
|
||||
*/
|
||||
scheduledReportMigrated: boolean
|
||||
rules: AutomationRule[]
|
||||
}
|
||||
|
||||
export interface AutomationRuleStoreDependencies {
|
||||
userDataPath?: () => string
|
||||
now?: () => number
|
||||
/**
|
||||
* 迁移旧定时日报时,把 legacy 群标识(会话 md5 / 群名 / roomId)解析成
|
||||
* **稳定会话 id**(`xxx@chatroom`)。解析不到返回 `undefined`。
|
||||
*
|
||||
* 不注入 ⇒ 迁移**推迟**(不写任何规则、不置标记)。
|
||||
*/
|
||||
resolveLegacyConversationId?: (raw: string) => string | undefined
|
||||
}
|
||||
|
||||
function emptyState(): StoredRules {
|
||||
@@ -68,19 +92,24 @@ function emptyState(): StoredRules {
|
||||
builtinSeeded: false,
|
||||
leaveNotificationMigrated: false,
|
||||
notificationTemplateUpgraded: false,
|
||||
scheduledReportMigrated: false,
|
||||
rules: []
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRuleType(value: unknown): AutomationRuleType {
|
||||
return value === 'leave_notification' ? 'leave_notification' : 'daily_report'
|
||||
return value === 'leave_notification'
|
||||
? 'leave_notification'
|
||||
: value === 'scheduled_report'
|
||||
? 'scheduled_report'
|
||||
: 'daily_report'
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条规则的读盘归一化。
|
||||
*
|
||||
* 走 `normalizeRuleDraft` —— 它覆盖了 `AutomationRule` 除 id / 时间戳之外的**全部**字段,
|
||||
* 所以这是无损的,同时自动补上历史 rules.json 缺失的 `ruleType` / `leaveNotification`。
|
||||
* 所以这是无损的,同时自动补上历史 rules.json 缺失的 `ruleType` / 各类 config。
|
||||
*/
|
||||
function normalizeStoredRule(value: unknown): AutomationRule | null {
|
||||
if (!value || typeof value !== 'object') return null
|
||||
@@ -92,8 +121,9 @@ function normalizeStoredRule(value: unknown): AutomationRule | null {
|
||||
{
|
||||
...raw,
|
||||
ruleType,
|
||||
// 历史 daily_report 规则没有 leaveNotification;反过来也要避免脏字段落盘。
|
||||
...(ruleType === 'leave_notification' ? { leaveNotification: raw.leaveNotification } : {})
|
||||
// 历史规则没有这些字段;反过来也要避免脏字段落盘。
|
||||
...(ruleType === 'leave_notification' ? { leaveNotification: raw.leaveNotification } : {}),
|
||||
...(ruleType === 'scheduled_report' ? { scheduledReport: raw.scheduledReport } : {})
|
||||
},
|
||||
String(raw.name || '').trim() || '未命名自动化'
|
||||
)
|
||||
@@ -106,6 +136,9 @@ function normalizeStoredRule(value: unknown): AutomationRule | null {
|
||||
updatedAt,
|
||||
...(normalized.ruleType === 'leave_notification' && normalized.leaveNotification
|
||||
? { leaveNotification: normalized.leaveNotification }
|
||||
: {}),
|
||||
...(normalized.ruleType === 'scheduled_report' && normalized.scheduledReport
|
||||
? { scheduledReport: normalized.scheduledReport }
|
||||
: {})
|
||||
}
|
||||
}
|
||||
@@ -115,7 +148,6 @@ function normalizeStoredRule(value: unknown): AutomationRule | null {
|
||||
*
|
||||
* **为什么替他填**:模板里原先根本没有群名变量(`{groupRemark}` 是成员在本群的昵称)。
|
||||
* 目标一旦不是「当前群聊」,通知就等于「张三退群了」—— 收件人不知道是哪个群。
|
||||
* 模板是用户已保存的数据,让他自己去发现"少一个变量"是不合理的。
|
||||
*
|
||||
* **为什么只跑一次**:靠"模板里有没有 `{groupName}`"判断会导致用户删掉后被反复补回来。
|
||||
* 所以由 `notificationTemplateUpgraded` 标记保证一次性;用户之后删掉不会回来。
|
||||
@@ -139,7 +171,24 @@ function upgradeLeaveNotificationTemplate(rules: AutomationRule[]): {
|
||||
return { rules: next, count }
|
||||
}
|
||||
|
||||
/** 读盘容错:任何字段可疑都降级成安全值,绝不因为一个坏文件让功能整体不可用。 */function normalizeStored(value: unknown): StoredRules {
|
||||
/**
|
||||
* 调度游标(`lastRunAt` / `lastScheduledSlot`)**由 scheduler 拥有**,草稿改不动它们。
|
||||
*
|
||||
* 保存规则时一律从 `current` 取,而不是从草稿取 —— 否则用户进一次编辑页保存,
|
||||
* 就会把"已消费的槽位"抹掉,导致当天重复补跑一次日报。
|
||||
*/
|
||||
function pickScheduledReportRuntime(
|
||||
current: ScheduledReportAutomationConfig | undefined
|
||||
): Partial<ScheduledReportAutomationConfig> {
|
||||
if (!current) return {}
|
||||
return {
|
||||
...(current.lastRunAt ? { lastRunAt: current.lastRunAt } : {}),
|
||||
...(current.lastScheduledSlot ? { lastScheduledSlot: current.lastScheduledSlot } : {})
|
||||
}
|
||||
}
|
||||
|
||||
/** 读盘容错:任何字段可疑都降级成安全值,绝不因为一个坏文件让功能整体不可用。 */
|
||||
function normalizeStored(value: unknown): StoredRules {
|
||||
if (!value || typeof value !== 'object') return emptyState()
|
||||
const input = value as Partial<StoredRules>
|
||||
const rules = Array.isArray(input.rules)
|
||||
@@ -152,6 +201,7 @@ function upgradeLeaveNotificationTemplate(rules: AutomationRule[]): {
|
||||
builtinSeeded: input.builtinSeeded === true,
|
||||
leaveNotificationMigrated: input.leaveNotificationMigrated === true,
|
||||
notificationTemplateUpgraded: input.notificationTemplateUpgraded === true,
|
||||
scheduledReportMigrated: input.scheduledReportMigrated === true,
|
||||
rules
|
||||
}
|
||||
}
|
||||
@@ -163,10 +213,31 @@ export class AutomationRuleStore {
|
||||
private loaded = false
|
||||
/** 迁移结果,供启动日志/报告读取(不含任何 id)。 */
|
||||
private lastMigrationPlan: LeaveNotificationMigrationPlan | null = null
|
||||
private lastScheduledMigrationSummary: ScheduledReportMigrationSummary | null = null
|
||||
private legacyConversationResolver: ((raw: string) => string | undefined) | null
|
||||
|
||||
constructor(dependencies: AutomationRuleStoreDependencies = {}) {
|
||||
this.userDataPath = dependencies.userDataPath ?? (() => app.getPath('userData'))
|
||||
this.now = dependencies.now ?? (() => Date.now())
|
||||
this.legacyConversationResolver = dependencies.resolveLegacyConversationId ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* 注入 / 替换旧定时日报迁移所需的会话解析器(数据库就绪后由 main 调用)。
|
||||
*
|
||||
* 若之前因为"解析器不可用"推迟了迁移,这里会**立刻补跑**并落盘。
|
||||
*/
|
||||
setLegacyConversationResolver(resolver: (raw: string) => string | undefined): void {
|
||||
this.legacyConversationResolver = resolver
|
||||
if (!this.loaded) return
|
||||
if (this.state.scheduledReportMigrated) return
|
||||
if (this.runScheduledReportMigration(this.state)) this.persist()
|
||||
}
|
||||
|
||||
/** 旧定时日报迁移是否仍在等待解析器(仅用于启动日志与测试断言)。 */
|
||||
hasPendingScheduledReportMigration(): boolean {
|
||||
this.ensureLoaded()
|
||||
return !this.state.scheduledReportMigrated && this.readLegacyScheduledTasks().length > 0
|
||||
}
|
||||
|
||||
listRules(): AutomationRule[] {
|
||||
@@ -187,6 +258,12 @@ export class AutomationRuleStore {
|
||||
return this.lastMigrationPlan ? { ...this.lastMigrationPlan } : null
|
||||
}
|
||||
|
||||
/** 上一次旧定时日报迁移的统计(未迁移时为 null)。 */
|
||||
getLastScheduledReportMigration(): ScheduledReportMigrationSummary | null {
|
||||
this.ensureLoaded()
|
||||
return this.lastScheduledMigrationSummary ? { ...this.lastScheduledMigrationSummary } : null
|
||||
}
|
||||
|
||||
createRule(draft: unknown): AutomationRule {
|
||||
this.ensureLoaded()
|
||||
const timestamp = this.now()
|
||||
@@ -219,11 +296,26 @@ export class AutomationRuleStore {
|
||||
...(current.ruleType === 'leave_notification' && normalized.leaveNotification
|
||||
? { leaveNotification: normalized.leaveNotification }
|
||||
: {}),
|
||||
...(current.ruleType === 'scheduled_report' && normalized.scheduledReport
|
||||
? {
|
||||
scheduledReport: {
|
||||
...normalized.scheduledReport,
|
||||
...pickScheduledReportRuntime(current.scheduledReport)
|
||||
}
|
||||
}
|
||||
: {}),
|
||||
createdAt: current.createdAt,
|
||||
updatedAt: this.now()
|
||||
}
|
||||
// 切类型时不能留下另一种类型才认识的字段。
|
||||
if (rule.ruleType === 'daily_report') delete rule.leaveNotification
|
||||
if (rule.ruleType === 'daily_report') {
|
||||
delete rule.leaveNotification
|
||||
delete rule.scheduledReport
|
||||
} else if (rule.ruleType === 'leave_notification') {
|
||||
delete rule.scheduledReport
|
||||
} else {
|
||||
delete rule.leaveNotification
|
||||
}
|
||||
this.state.rules = this.state.rules.map((item, at) => (at === index ? rule : item))
|
||||
this.persist()
|
||||
return structuredClone(rule)
|
||||
@@ -275,6 +367,38 @@ export class AutomationRuleStore {
|
||||
return this.updateRule(id, { ...rule, enabled: enabled === true })
|
||||
}
|
||||
|
||||
/**
|
||||
* 写**调度游标**(`lastRunAt` / `lastScheduledSlot`)。
|
||||
*
|
||||
* 刻意不走 `updateRule`:这不是用户配置编辑,走草稿归一化会顺带触碰别的字段,
|
||||
* 也可能被"草稿里没这个字段"给抹掉。这里只允许改这两个键。
|
||||
*/
|
||||
setScheduledReportRuntime(
|
||||
id: string,
|
||||
patch: { lastRunAt?: string; lastScheduledSlot?: string }
|
||||
): AutomationRule | undefined {
|
||||
this.ensureLoaded()
|
||||
const key = String(id || '').trim()
|
||||
const index = this.state.rules.findIndex((rule) => rule.id === key)
|
||||
if (index < 0) return undefined
|
||||
const current = this.state.rules[index]
|
||||
if (current.ruleType !== 'scheduled_report' || !current.scheduledReport) return undefined
|
||||
const next: AutomationRule = {
|
||||
...current,
|
||||
scheduledReport: {
|
||||
...current.scheduledReport,
|
||||
...(patch.lastRunAt !== undefined ? { lastRunAt: patch.lastRunAt } : {}),
|
||||
...(patch.lastScheduledSlot !== undefined
|
||||
? { lastScheduledSlot: patch.lastScheduledSlot }
|
||||
: {})
|
||||
},
|
||||
updatedAt: this.now()
|
||||
}
|
||||
this.state.rules = this.state.rules.map((item, at) => (at === index ? next : item))
|
||||
this.persist()
|
||||
return structuredClone(next)
|
||||
}
|
||||
|
||||
private ensureLoaded(): void {
|
||||
if (this.loaded) return
|
||||
this.loaded = true
|
||||
@@ -301,6 +425,7 @@ export class AutomationRuleStore {
|
||||
console.log(`[Automation] 退群通知模板已补上群名变量(${upgraded.count} 条)`)
|
||||
}
|
||||
}
|
||||
this.runScheduledReportMigration(stored)
|
||||
stored.version = CURRENT_VERSION
|
||||
this.state = stored
|
||||
this.persist()
|
||||
@@ -326,11 +451,110 @@ export class AutomationRuleStore {
|
||||
template: plan.template,
|
||||
target: plan.target,
|
||||
enabled: plan.enabled,
|
||||
targetNeedsReview: plan.targetNeedsReview
|
||||
// 二次勾选(旧「通知群聊」)逐字保留,迁移不再是有损的。
|
||||
notifyScope: plan.notifyScope,
|
||||
notifyRoomIds: plan.notifyRoomIds
|
||||
})
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
* 旧「定时日报」任务 → `scheduled_report` 规则。**只跑一次**。
|
||||
*
|
||||
* 返回 `true` 表示本次真的做了迁移并需要落盘。
|
||||
* **解析器不可用时返回 `false` 且不置标记** —— 迁移推迟到数据库就绪后补跑。
|
||||
*/
|
||||
private runScheduledReportMigration(stored: StoredRules): boolean {
|
||||
if (stored.scheduledReportMigrated) return false
|
||||
const tasks = this.readLegacyScheduledTasks()
|
||||
if (!tasks.length) {
|
||||
// 全新安装 / 从没用过旧定时日报:没有历史可迁,直接置位。
|
||||
stored.scheduledReportMigrated = true
|
||||
console.log('[Automation] 定时日报迁移 outcome=fresh_install')
|
||||
return true
|
||||
}
|
||||
const resolver = this.legacyConversationResolver
|
||||
if (!resolver) {
|
||||
console.log(
|
||||
`[Automation] 定时日报迁移已推迟:数据库尚未就绪,无法解析旧群标识(待迁 ${tasks.length} 条)`
|
||||
)
|
||||
return false
|
||||
}
|
||||
const { plans, summary } = planScheduledReportMigrationBatch(tasks, resolver, this.now())
|
||||
this.lastScheduledMigrationSummary = summary
|
||||
this.writeScheduledMigrationBackup(tasks, summary)
|
||||
const existing = new Set(stored.rules.map((rule) => rule.id))
|
||||
const migrated: AutomationRule[] = []
|
||||
for (const plan of plans) {
|
||||
// 幂等:同一 id 已存在就不再插入(重复执行迁移也不会多出规则)。
|
||||
if (existing.has(plan.ruleId)) continue
|
||||
existing.add(plan.ruleId)
|
||||
migrated.push({
|
||||
...createDefaultScheduledReportRule(plan.createdAt, {
|
||||
id: plan.ruleId,
|
||||
name: plan.name,
|
||||
enabled: plan.enabled,
|
||||
config: plan.config
|
||||
}),
|
||||
createdAt: plan.createdAt,
|
||||
updatedAt: plan.updatedAt
|
||||
})
|
||||
}
|
||||
stored.rules = [...stored.rules, ...migrated]
|
||||
stored.scheduledReportMigrated = true
|
||||
// 只记数量与判定分布,**禁止**出现群名 / roomId / 群主昵称。
|
||||
console.log(
|
||||
`[Automation] 定时日报迁移 outcome=done total=${summary.total} migrated=${migrated.length}` +
|
||||
` lossless=${summary.lossless} needsReview=${summary.needsReview}` +
|
||||
` duplicatesSkipped=${summary.duplicatesSkipped}`
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 读旧定时日报**任务**文件。
|
||||
*
|
||||
* 只读、只在这里读一次;运行期其余代码**不再读** legacy(避免双读)。
|
||||
* 读失败视为"没有历史任务",不抛。
|
||||
*/
|
||||
private readLegacyScheduledTasks(): LegacyScheduledReportTask[] {
|
||||
try {
|
||||
const value = fs.readJsonSync(
|
||||
path.join(this.userDataPath(), LEGACY_SCHEDULED_DIR, LEGACY_SCHEDULED_TASKS_FILE)
|
||||
) as unknown
|
||||
return Array.isArray(value) ? (value as LegacyScheduledReportTask[]) : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** 迁移前把旧任务**原样**落一份 backup(不做不可逆覆盖)。 */
|
||||
private writeScheduledMigrationBackup(
|
||||
tasks: LegacyScheduledReportTask[],
|
||||
summary: ScheduledReportMigrationSummary
|
||||
): void {
|
||||
try {
|
||||
const filePath = path.join(
|
||||
this.userDataPath(),
|
||||
STORAGE_DIR,
|
||||
SCHEDULED_MIGRATION_BACKUP_FILE
|
||||
)
|
||||
fs.ensureDirSync(path.dirname(filePath))
|
||||
fs.writeJsonSync(
|
||||
filePath,
|
||||
{
|
||||
migratedAt: this.now(),
|
||||
summary,
|
||||
// 备份里保留原始字段:这是**用户数据**,不是日志,不进任何用户可见界面。
|
||||
legacyTasks: tasks
|
||||
},
|
||||
{ spaces: 2 }
|
||||
)
|
||||
} catch (error) {
|
||||
console.warn(`[Automation] 写入定时日报迁移备份失败: ${errorText(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读旧退群监控状态文件里的通知相关字段。
|
||||
*
|
||||
@@ -358,7 +582,7 @@ export class AutomationRuleStore {
|
||||
/**
|
||||
* 迁移前把旧配置原样落一份 backup。
|
||||
*
|
||||
* §「不要不可逆直接覆盖」:旧状态文件本身也**不删**,只是不再被运行时代码读取。
|
||||
* 不做不可逆覆盖:旧状态文件本身也**不删**,只是不再被运行时代码读取。
|
||||
*/
|
||||
private writeMigrationBackup(
|
||||
legacy: LegacyLeaveNotificationState,
|
||||
@@ -381,15 +605,14 @@ export class AutomationRuleStore {
|
||||
applied: {
|
||||
enabled: plan.enabled,
|
||||
targetType: plan.target.type,
|
||||
targetNeedsReview: plan.targetNeedsReview
|
||||
notifyScope: plan.notifyScope,
|
||||
notifyRoomIds: plan.notifyRoomIds
|
||||
}
|
||||
},
|
||||
{ spaces: 2 }
|
||||
)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[Automation] 写入退群通知迁移备份失败: ${errorText(error)}`
|
||||
)
|
||||
console.warn(`[Automation] 写入退群通知迁移备份失败: ${errorText(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,9 +6,12 @@ import {
|
||||
import {
|
||||
AUTOMATION_SEND_PURPOSE,
|
||||
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
|
||||
leaveNotificationCoversRoom,
|
||||
type AutomationExecution,
|
||||
type AutomationExecutionTrigger,
|
||||
type AutomationRule,
|
||||
type AutomationStatusSummary
|
||||
type AutomationStatusSummary,
|
||||
type ScheduledRuleRunOutcome
|
||||
} from '../../shared/automation'
|
||||
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
|
||||
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
|
||||
@@ -20,6 +23,11 @@ import {
|
||||
resolveLeaveNotificationTarget,
|
||||
type LeaveNotificationTargetResolution
|
||||
} from './leave-notification-target'
|
||||
import {
|
||||
resolveScheduledReportTarget,
|
||||
scheduledReportSourceDisplayName
|
||||
} from './scheduled-report-target'
|
||||
import type { AutomationTargetContact } from './automation-wechat-target'
|
||||
import {
|
||||
automationRuleStore,
|
||||
type AutomationRuleStore
|
||||
@@ -32,7 +40,6 @@ import {
|
||||
automationActionRunner,
|
||||
type AutomationActionRunner
|
||||
} from './automation-action-runner'
|
||||
|
||||
/**
|
||||
* AutomationService —— Automation v1 的编排层。
|
||||
*
|
||||
@@ -118,6 +125,26 @@ export function leaveNotificationIdempotencyKey(eventId: string): string {
|
||||
return `${AUTOMATION_SEND_PURPOSE.leaveNotification}:${eventId}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时日报的**确定性** executionId。
|
||||
*
|
||||
* 由 `ruleId + 槽位` 推出(不是 `randomUUID`):同一个每日槽位即使因为
|
||||
* 崩溃重启被重复触发,也算出同一个 executionId ——
|
||||
* `ExecutionLog.record()` 按 id 覆盖,`WechatActionGateway` 的落盘幂等键
|
||||
* (`automation_scheduled_report:<executionId>`)直接把第二次发送短路掉。
|
||||
*
|
||||
* **手动执行不算槽位**:每次都应该是独立的一次执行,否则用户连点两次
|
||||
* 「立即执行」会因为幂等而被静默吞掉。
|
||||
*/
|
||||
export function scheduledReportExecutionId(ruleId: string, slot: string): string {
|
||||
return createHash('sha1')
|
||||
.update(`scheduled_report\u0001${ruleId}\u0001${slot}`)
|
||||
.digest('hex')
|
||||
}
|
||||
|
||||
/** 定时日报一次执行的结果(定义在 shared 层,便于 IPC / 渲染层共用)。 */
|
||||
export type { ScheduledRuleRunOutcome }
|
||||
|
||||
export interface AutomationServiceDependencies {
|
||||
ruleStore?: AutomationRuleStore
|
||||
executionLog?: AutomationExecutionLogService
|
||||
@@ -159,6 +186,16 @@ export class AutomationService {
|
||||
*/
|
||||
private readonly gates = new Map<string, ConversationRuleGate>()
|
||||
|
||||
/**
|
||||
* 定时日报的 `ruleId inFlight` 锁。
|
||||
*
|
||||
* **刻意不用 `gates`(conversation gate)**:定时日报的触发与"某个会话刚被触发过"
|
||||
* 没有关系,套 60 秒 cooldown 会莫名其妙吞掉当天的补跑。
|
||||
* 这里只要一条最朴素的约束:**同一条规则同时最多一个 execution**;
|
||||
* 不同规则之间互不影响(可以并行)。
|
||||
*/
|
||||
private readonly scheduledInFlight = new Set<string>()
|
||||
|
||||
/** 仅用于诊断统计(`[Automation] blockedMessages=N`),**不进用户执行日志**。 */
|
||||
private blockedMessageCount = 0
|
||||
|
||||
@@ -300,10 +337,16 @@ export class AutomationService {
|
||||
* - 消息型规则:MessageListener → handleMessage → 动作链;
|
||||
* - 退群通知:GroupExitMonitor → **本入口** → 单次文本发送。
|
||||
*
|
||||
* 三层闸门(缺一不可):
|
||||
* 1. `enabled === false` → 不执行,**且不创建 execution**(§「没有执行:不创建」);
|
||||
* 2. `targetNeedsReview` → 迁移过来但目标无法无损映射,同样不执行、不创建记录;
|
||||
* 3. `ruleId + eventId` 幂等 → 同一事件即使重复投递也只发送一次。
|
||||
* 四层闸门(缺一不可):
|
||||
* 1. `enabled === false` → 不执行,**且不创建 execution**;
|
||||
* 2. `targetNeedsReview` → 存量迁移遗留的"目标待重选",同样不执行、不创建记录;
|
||||
* 3. **通知范围**(`notifyScope` / `notifyRoomIds`)→ 事件所在群不在二次勾选范围内则跳过。
|
||||
* 这是旧版「退群监控 → 通知群聊」的第二层,缺了它规则一启用就全量通知;
|
||||
* 同样**不创建 execution** —— 被范围排除不是"一次失败的执行"。
|
||||
* 4. `ruleId + eventId` 幂等 → 同一事件即使重复投递也只发送一次。
|
||||
*
|
||||
* 闸门顺序有意如此:范围判定放在幂等**之前**,否则一个被排除的群会白白占用
|
||||
* 该事件的幂等位(用户随后真的补勾了那个群,反而发不出去)。
|
||||
*/
|
||||
async handleGroupExit(event: GroupMemberExitedEvent): Promise<void> {
|
||||
const eventId = String(event?.eventId || '').trim()
|
||||
@@ -326,7 +369,12 @@ export class AutomationService {
|
||||
this.warn(`退群通知目标待重新选择,已跳过本次通知 ruleId=${rule.id}`)
|
||||
return
|
||||
}
|
||||
// ③ 幂等(内存快路径)。跨重启那一层由确定性 executionId + gateway 审计兜住。
|
||||
// ③ 通知范围:这个群没被勾选就不归本规则管(与 UI 共用 shared 同一份判定)。
|
||||
if (!leaveNotificationCoversRoom(rule.leaveNotification, event.conversationId)) {
|
||||
this.info(`退群通知范围外,已跳过本次通知 ruleId=${rule.id}`)
|
||||
return
|
||||
}
|
||||
// ④ 幂等(内存快路径)。跨重启那一层由确定性 executionId + gateway 审计兜住。
|
||||
if (!this.claimGroupExit(rule.id, eventId)) return
|
||||
|
||||
const executionId = leaveNotificationExecutionId(rule.id, eventId)
|
||||
@@ -382,8 +430,26 @@ export class AutomationService {
|
||||
rule: AutomationRule,
|
||||
event: GroupMemberExitedEvent
|
||||
): LeaveNotificationTargetResolution {
|
||||
let contacts: ReturnType<typeof listContacts> = []
|
||||
const { contacts, selfWxid } = this.resolveTargetContext()
|
||||
return resolveLeaveNotificationTarget({
|
||||
config: rule.leaveNotification,
|
||||
event,
|
||||
contacts,
|
||||
selfWxid
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 联系人清单 + 当前登录 wxid。
|
||||
*
|
||||
* 退群通知与定时日报**共用这一处**:两份都要"把目标解析成可发送对象",
|
||||
* 解析所需的数据源(通讯录 / 当前账号)必须只有一个出口,
|
||||
* 否则两边会慢慢长成两套判定。
|
||||
*/
|
||||
private resolveTargetContext(): { contacts: AutomationTargetContact[]; selfWxid: string } {
|
||||
let contacts: AutomationTargetContact[] = []
|
||||
try {
|
||||
// `FormattedContact` 结构上就满足 `AutomationTargetContact`,不需要断言。
|
||||
contacts = listContacts()
|
||||
} catch (error) {
|
||||
this.warn(`读取联系人失败: ${errorText(error)}`)
|
||||
@@ -394,12 +460,172 @@ export class AutomationService {
|
||||
} catch (error) {
|
||||
this.warn(`读取当前账号失败: ${errorText(error)}`)
|
||||
}
|
||||
return resolveLeaveNotificationTarget({
|
||||
config: rule.leaveNotification,
|
||||
event,
|
||||
contacts,
|
||||
selfWxid
|
||||
})
|
||||
return { contacts, selfWxid }
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时日报执行入口。**scheduler 与「立即执行」共用这一条**。
|
||||
*
|
||||
* ```text
|
||||
* Scheduler ─┐
|
||||
* ├─→ executeScheduledRule(ruleId, { trigger, scheduledSlot })
|
||||
* 手动执行 ───┘ ↓ resolveScheduledReportTarget
|
||||
* ↓ runner.runScheduledReport(生成 → 落库 → 解析目标 → Gateway 发图)
|
||||
* ↓ ExecutionLog.record(trigger = schedule | manual)
|
||||
* ```
|
||||
*
|
||||
* 三层闸门(与退群通知同口径,但**不套 conversation gate / cooldown**):
|
||||
* 1. `enabled === false` → 不执行、不创建记录;
|
||||
* 2. `targetNeedsReview` → 目标无法无损映射,不执行、不创建记录;
|
||||
* 3. `ruleId inFlight` → 同一条规则同时最多一个 execution(不同规则可并行)。
|
||||
*/
|
||||
async executeScheduledRule(
|
||||
ruleId: string,
|
||||
options: { trigger: 'schedule' | 'manual'; scheduledSlot?: string }
|
||||
): Promise<ScheduledRuleRunOutcome> {
|
||||
const key = String(ruleId || '').trim()
|
||||
if (!key) return { executed: false, reason: 'missing_rule' }
|
||||
|
||||
let rule: AutomationRule | undefined
|
||||
try {
|
||||
rule = this.ruleStore.getRule(key)
|
||||
} catch (error) {
|
||||
this.warn(`读取定时日报规则失败: ${errorText(error)}`)
|
||||
return { executed: false, reason: 'store_error' }
|
||||
}
|
||||
if (!rule || rule.ruleType !== 'scheduled_report' || !rule.scheduledReport) {
|
||||
return { executed: false, reason: 'rule_not_found' }
|
||||
}
|
||||
if (!rule.enabled) return { executed: false, reason: 'disabled' }
|
||||
if (rule.scheduledReport.targetNeedsReview) {
|
||||
this.warn(`定时日报目标待重新选择,已跳过 ruleId=${rule.id}`)
|
||||
return { executed: false, reason: 'target_needs_review' }
|
||||
}
|
||||
|
||||
// 并发保护:同一条规则同时最多一个执行。冲突时**直接返回**,不排队 ——
|
||||
// 排队会让"18:00 那次没跑完"变成"18:00 和 18:01 各发一份"。
|
||||
if (this.scheduledInFlight.has(rule.id)) {
|
||||
return { executed: false, reason: 'in_flight' }
|
||||
}
|
||||
this.scheduledInFlight.add(rule.id)
|
||||
|
||||
const scheduledSlot = String(options.scheduledSlot || '').trim()
|
||||
try {
|
||||
const startedAt = this.now()
|
||||
const executionId =
|
||||
options.trigger === 'schedule' && scheduledSlot
|
||||
? scheduledReportExecutionId(rule.id, scheduledSlot)
|
||||
: randomUUID()
|
||||
|
||||
const { contacts, selfWxid } = this.resolveTargetContext()
|
||||
const resolution = resolveScheduledReportTarget({
|
||||
config: rule.scheduledReport,
|
||||
contacts,
|
||||
selfWxid
|
||||
})
|
||||
const sourceDisplayName = scheduledReportSourceDisplayName(rule.scheduledReport, contacts)
|
||||
const sendBlockedReason = await this.scheduledReportCapabilityError()
|
||||
|
||||
let result: Awaited<ReturnType<AutomationActionRunner['runScheduledReport']>>
|
||||
try {
|
||||
result = await this.runner.runScheduledReport({
|
||||
executionId,
|
||||
rule,
|
||||
config: rule.scheduledReport,
|
||||
resolution,
|
||||
sourceDisplayName,
|
||||
trigger: options.trigger === 'manual' ? 'manual' : 'schedule',
|
||||
...(sendBlockedReason ? { sendBlockedReason } : {})
|
||||
})
|
||||
} catch (error) {
|
||||
result = {
|
||||
steps: [],
|
||||
status: 'failed',
|
||||
errorSummary: `执行过程异常:${errorText(error)}`,
|
||||
reportGenerated: false
|
||||
}
|
||||
}
|
||||
|
||||
this.executionLog.record(
|
||||
this.buildExecution({
|
||||
executionId,
|
||||
rule,
|
||||
startedAt,
|
||||
sourceDisplayName,
|
||||
trigger: options.trigger,
|
||||
status: result.status,
|
||||
durationMs: this.now() - startedAt,
|
||||
steps: result.steps,
|
||||
...(result.errorSummary ? { errorSummary: result.errorSummary } : {})
|
||||
})
|
||||
)
|
||||
|
||||
this.recordScheduledRun(rule.id, {
|
||||
trigger: options.trigger,
|
||||
...(scheduledSlot ? { scheduledSlot } : {}),
|
||||
finishedAt: new Date(this.now()).toISOString()
|
||||
})
|
||||
|
||||
// 隐私红线:日志只允许 ruleId / executionId / 触发方式 / 状态 / 耗时 / 步骤状态。
|
||||
// 群名、昵称、wxid、日报正文、图片路径一律不进日志。
|
||||
const trail = result.steps.map((step) => `${step.key}=${step.status}`).join(' ')
|
||||
this.info(
|
||||
`executed ruleId=${rule.id} executionId=${executionId} trigger=${options.trigger}` +
|
||||
` status=${result.status} durationMs=${this.now() - startedAt}${trail ? ` ${trail}` : ''}`
|
||||
)
|
||||
|
||||
return {
|
||||
executed: true,
|
||||
executionId,
|
||||
status: result.status,
|
||||
reportGenerated: result.reportGenerated,
|
||||
...(result.errorCode ? { errorCode: result.errorCode } : {}),
|
||||
...(result.errorSummary ? { errorSummary: result.errorSummary } : {})
|
||||
}
|
||||
} finally {
|
||||
this.scheduledInFlight.delete(rule.id)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写调度游标。
|
||||
*
|
||||
* - `lastRunAt`:**任何一次执行**(含手动)都会更新 —— UI 的"最近执行"要如实反映;
|
||||
* - `lastScheduledSlot`:**只有定时触发**才消费槽位。
|
||||
* 手动执行若也写它,会把今天已经安排好的那次定时执行一起吞掉。
|
||||
*/
|
||||
private recordScheduledRun(
|
||||
ruleId: string,
|
||||
input: { trigger: 'schedule' | 'manual'; scheduledSlot?: string; finishedAt: string }
|
||||
): void {
|
||||
try {
|
||||
this.ruleStore.setScheduledReportRuntime(ruleId, {
|
||||
lastRunAt: input.finishedAt,
|
||||
...(input.trigger === 'schedule' && input.scheduledSlot
|
||||
? { lastScheduledSlot: input.scheduledSlot }
|
||||
: {})
|
||||
})
|
||||
} catch (error) {
|
||||
// 游标写失败不影响本次执行 —— 但必须留痕,否则"同一天重复补跑"会变成无声故障。
|
||||
this.warn(`写入定时日报调度游标失败 ruleId=${ruleId}: ${errorText(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 定时日报只需要图片能力。缺失时给出用户能看懂的一句说明。 */
|
||||
private async scheduledReportCapabilityError(): Promise<string | undefined> {
|
||||
let capability: PersonalWechatSendCapability | null = null
|
||||
try {
|
||||
capability = await this.getCapability()
|
||||
} catch {
|
||||
return '暂时无法获知微信发送能力,本次定时日报未发送。'
|
||||
}
|
||||
if (!capability?.supported) {
|
||||
return capability?.message || '当前系统不支持微信消息发送'
|
||||
}
|
||||
if (!capability.capabilities?.image) {
|
||||
return '当前环境无法发送图片,本次定时日报未发送。'
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 退群通知只需要文字能力。缺失时给出用户能看懂的一句说明。 */
|
||||
@@ -565,6 +791,8 @@ export class AutomationService {
|
||||
rule: AutomationRule
|
||||
startedAt: number
|
||||
sourceDisplayName: string
|
||||
/** 触发方式。旧调用点不传时为 `undefined` —— 读盘不猜测。 */
|
||||
trigger?: AutomationExecutionTrigger
|
||||
status: AutomationExecution['status']
|
||||
durationMs: number
|
||||
steps: AutomationExecution['steps']
|
||||
@@ -575,6 +803,7 @@ export class AutomationService {
|
||||
ruleId: input.rule.id,
|
||||
ruleName: input.rule.name,
|
||||
triggerTime: input.startedAt,
|
||||
...(input.trigger ? { trigger: input.trigger } : {}),
|
||||
sourceDisplayName: input.sourceDisplayName,
|
||||
status: input.status,
|
||||
durationMs: input.durationMs,
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
import {
|
||||
LEAVE_NOTIFICATION_TARGET_OPTIONS,
|
||||
SCHEDULED_REPORT_TARGET_OPTIONS,
|
||||
leaveNotificationTargetLabel,
|
||||
scheduledReportTargetLabel
|
||||
} from '../../shared/automation'
|
||||
import { WECHAT_FILE_HELPER_USERNAME, isFileHelperUsername } from '../../shared/wechat-identities'
|
||||
|
||||
/**
|
||||
* **中性的微信发送目标解析**。
|
||||
*
|
||||
* 退群通知与定时日报的目标语义完全一致(来源会话 / 自己 / 文件传输助手 / 指定好友),
|
||||
* 差的只是"来源会话"从哪来:
|
||||
* - 退群通知 → 事件所在群(`event.conversationId`);
|
||||
* - 定时日报 → 该规则配置的日报来源群(`config.report.sourceConversationId`)。
|
||||
*
|
||||
* ⇒ 所以**只允许有一份实现**(只保留一套 resolve)。
|
||||
* 两个业务各自只有一层薄适配(把参数摊平后交给这里),不重复任何判定逻辑。
|
||||
*
|
||||
* 五条规则(两边共用):
|
||||
* 1. 目标解析失败 → **报错**,绝不 fallback 到别的目标(尤其不许偷偷发文件助手 / 来源群);
|
||||
* 2. 只允许出现在选项表里的目标类型;
|
||||
* 3. 显示名不带 wxid / roomId:日志与界面只出现用户能看懂的称呼;
|
||||
* 4. 联系人必须**可发送**(排除群聊 / 公众号 / 文件传输助手 / 自己);
|
||||
* 5. 只有 `source_chat` 用得到来源会话,其余目标完全不看它。
|
||||
*/
|
||||
|
||||
/** 解析所需的最小联系人结构(main 侧 `FormattedContact` 结构上可赋值给它)。 */
|
||||
export interface AutomationTargetContact {
|
||||
m_nsUsrName: string
|
||||
m_nsNickName?: string
|
||||
md5?: string
|
||||
type: 'user' | 'group'
|
||||
isOfficialAccount?: boolean
|
||||
wechatNickname?: string
|
||||
remark?: string
|
||||
}
|
||||
|
||||
/** 目标类型(两个业务共用同一组字面量)。 */
|
||||
export type AutomationTargetType = 'source_chat' | 'self' | 'file_transfer' | 'contact'
|
||||
|
||||
export interface ResolvedAutomationTarget {
|
||||
recipient: { type: 'group' | 'contact'; id: string; name: string }
|
||||
/** 用户可读的目标名,直接进执行日志的 `detail`。 */
|
||||
displayName: string
|
||||
}
|
||||
|
||||
export type AutomationTargetResolution =
|
||||
| { ok: true; target: ResolvedAutomationTarget }
|
||||
| { ok: false; error: string }
|
||||
|
||||
/** 联系人的展示名:备注 → 微信昵称 → 会话昵称 → 兜底称呼。**永不回落到 wxid**。 */
|
||||
export function automationContactDisplayName(contact: AutomationTargetContact): string {
|
||||
return (
|
||||
contact.remark?.trim() ||
|
||||
contact.wechatNickname?.trim() ||
|
||||
contact.m_nsNickName?.trim() ||
|
||||
'指定好友'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 这个联系人能不能作为「指定好友」的发送目标。
|
||||
*
|
||||
* 排除:群聊、公众号(`gh_`)、文件传输助手、自己。
|
||||
* UI 的联系人选择器与运行时的目标解析**共用这一条判定**,
|
||||
* 否则会出现"能选但发不出去"。
|
||||
*/
|
||||
export function isSendableFriendContact(
|
||||
contact: AutomationTargetContact,
|
||||
selfWxid?: string
|
||||
): boolean {
|
||||
if (contact.type !== 'user') return false
|
||||
if (contact.isOfficialAccount) return false
|
||||
const username = String(contact.m_nsUsrName || '').trim()
|
||||
if (!username) return false
|
||||
if (isFileHelperUsername(username)) return false
|
||||
const self = String(selfWxid || '').trim()
|
||||
if (self && username === self) return false
|
||||
return true
|
||||
}
|
||||
|
||||
/** 供 UI 用的「可选好友」过滤(与运行时同一套判定)。 */
|
||||
export function filterSendableFriendContacts<T extends AutomationTargetContact>(
|
||||
contacts: T[],
|
||||
selfWxid?: string
|
||||
): T[] {
|
||||
return contacts.filter((contact) => isSendableFriendContact(contact, selfWxid))
|
||||
}
|
||||
|
||||
/** 目标类型是否在(该业务的)选项表里。 */
|
||||
function isKnownTargetType(
|
||||
type: string,
|
||||
options: ReadonlyArray<{ type: string }>
|
||||
): boolean {
|
||||
return options.some((option) => option.type === type)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把群标识解析成**稳定会话 id**(`xxx@chatroom`)。
|
||||
*
|
||||
* 兼容三种历史形态:roomId 本身 / 会话 md5 / 群名。
|
||||
* 解析不出来返回 `undefined` —— 调用方必须如实报错,**不许回落**。
|
||||
*/
|
||||
export function resolveGroupConversationId(
|
||||
raw: string,
|
||||
contacts: AutomationTargetContact[]
|
||||
): string | undefined {
|
||||
const value = String(raw || '').trim()
|
||||
if (!value) return undefined
|
||||
if (value.endsWith('@chatroom')) return value
|
||||
const matched = contacts.find(
|
||||
(contact) =>
|
||||
(contact.type === 'group' || contact.m_nsUsrName.endsWith('@chatroom')) &&
|
||||
(contact.md5 === value ||
|
||||
contact.m_nsUsrName === value ||
|
||||
contact.m_nsNickName?.trim() === value)
|
||||
)
|
||||
const conversationId = String(matched?.m_nsUsrName || '').trim()
|
||||
return conversationId.endsWith('@chatroom') ? conversationId : undefined
|
||||
}
|
||||
|
||||
/** 群标识 → 可读群名(解析不到时返回空串,由调用方决定兜底文案)。 */
|
||||
export function resolveGroupDisplayName(
|
||||
raw: string,
|
||||
contacts: AutomationTargetContact[]
|
||||
): string {
|
||||
const value = String(raw || '').trim()
|
||||
if (!value) return ''
|
||||
const matched = contacts.find(
|
||||
(contact) =>
|
||||
contact.m_nsUsrName === value ||
|
||||
contact.md5 === value ||
|
||||
contact.m_nsNickName?.trim() === value
|
||||
)
|
||||
return String(matched?.m_nsNickName || '').trim()
|
||||
}
|
||||
|
||||
export interface ResolveAutomationTargetInput {
|
||||
targetType: AutomationTargetType
|
||||
/**
|
||||
* `source_chat` 时使用:来源会话(退群事件所在群 / 日报来源群)。
|
||||
* 允许是 roomId / 会话 md5 / 群名 —— 一律经 `resolveGroupConversationId` 收敛。
|
||||
*/
|
||||
sourceConversationId?: string
|
||||
/** 来源会话的可读名(拿不到时留空,由这里给兜底称呼)。 */
|
||||
sourceDisplayName?: string
|
||||
/** `contact` 时使用:稳定 id(wxid / username)。 */
|
||||
contactId?: string
|
||||
contacts: AutomationTargetContact[]
|
||||
/** 当前登录账号的 wxid;拿不到时传空串。 */
|
||||
selfWxid?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 目标解析的**文案与类型表**(按业务注入)。
|
||||
*
|
||||
* 为什么把文案参数化而不是各写一份 switch:两个业务的**判定逻辑必须一模一样**,
|
||||
* 只有"主语"不同。文案集中放在这里,判定仍然只有一份。
|
||||
*/
|
||||
export interface AutomationTargetMessages {
|
||||
/** 目标类型表的单一来源(与 UI 选项同源)。 */
|
||||
options: ReadonlyArray<{ type: string }>
|
||||
/** 类型非法(伪造值 / 未知值)。 */
|
||||
invalidTarget: string
|
||||
/** `source_chat` 但来源会话拿不到。 */
|
||||
sourceMissing: string
|
||||
/** `source_chat` 且来源会话没有可读名时,`recipient.name` 的兜底。 */
|
||||
sourceRecipientName: string
|
||||
/** `source_chat` 且来源会话没有可读名时,`displayName` 的兜底。 */
|
||||
sourceDisplayName: string
|
||||
/** `self` 但拿不到自身身份。 */
|
||||
selfMissing: string
|
||||
/** `contact` 但没选联系人。 */
|
||||
contactNotChosen: string
|
||||
/** `contact` 但联系人失效 / 不可发送。 */
|
||||
contactUnavailable: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 中性目标解析。**唯一的实现**。
|
||||
*/
|
||||
export function resolveAutomationTarget(
|
||||
input: ResolveAutomationTargetInput,
|
||||
messages: AutomationTargetMessages
|
||||
): AutomationTargetResolution {
|
||||
const type = input.targetType
|
||||
if (!type || !isKnownTargetType(type, messages.options)) {
|
||||
return { ok: false, error: messages.invalidTarget }
|
||||
}
|
||||
|
||||
switch (type) {
|
||||
case 'source_chat': {
|
||||
const conversationId = resolveGroupConversationId(
|
||||
String(input.sourceConversationId || ''),
|
||||
input.contacts
|
||||
)
|
||||
if (!conversationId) return { ok: false, error: messages.sourceMissing }
|
||||
const explicitName = String(input.sourceDisplayName || '').trim()
|
||||
const resolvedName = resolveGroupDisplayName(conversationId, input.contacts)
|
||||
const name = explicitName || resolvedName || messages.sourceRecipientName
|
||||
const displayName = explicitName || resolvedName || messages.sourceDisplayName
|
||||
return {
|
||||
ok: true,
|
||||
target: {
|
||||
recipient: { type: 'group', id: conversationId, name },
|
||||
displayName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case 'self': {
|
||||
const selfWxid = String(input.selfWxid || '').trim()
|
||||
// 明确报错,不 fallback。
|
||||
if (!selfWxid) return { ok: false, error: messages.selfMissing }
|
||||
return {
|
||||
ok: true,
|
||||
target: {
|
||||
recipient: { type: 'contact', id: selfWxid, name: '我' },
|
||||
displayName: '我'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case 'file_transfer':
|
||||
return {
|
||||
ok: true,
|
||||
target: {
|
||||
recipient: {
|
||||
type: 'contact',
|
||||
id: WECHAT_FILE_HELPER_USERNAME,
|
||||
name: '文件传输助手'
|
||||
},
|
||||
displayName: '文件传输助手'
|
||||
}
|
||||
}
|
||||
|
||||
case 'contact': {
|
||||
const contactId = String(input.contactId || '').trim()
|
||||
if (!contactId) return { ok: false, error: messages.contactNotChosen }
|
||||
const contact = input.contacts.find(
|
||||
(item) => String(item.m_nsUsrName || '').trim() === contactId
|
||||
)
|
||||
if (!contact || !isSendableFriendContact(contact, input.selfWxid)) {
|
||||
// 之前选择的联系人被删除 / 不可发送 / 找不到时,规则不偷偷改发别处。
|
||||
return { ok: false, error: messages.contactUnavailable }
|
||||
}
|
||||
const displayName = automationContactDisplayName(contact)
|
||||
return {
|
||||
ok: true,
|
||||
target: {
|
||||
recipient: { type: 'contact', id: contactId, name: displayName },
|
||||
displayName
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 退群通知的已知目标类型表(与文案同源)。 */
|
||||
export const LEAVE_NOTIFICATION_TARGET_TYPES = LEAVE_NOTIFICATION_TARGET_OPTIONS
|
||||
|
||||
/** 定时日报的已知目标类型表(与文案同源)。 */
|
||||
export const SCHEDULED_REPORT_TARGET_TYPES = SCHEDULED_REPORT_TARGET_OPTIONS
|
||||
|
||||
export { leaveNotificationTargetLabel, scheduledReportTargetLabel }
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
LEAVE_NOTIFICATION_DEFAULT_TARGET_TYPE,
|
||||
normalizeLeaveNotificationRoomIds,
|
||||
normalizeLeaveNotificationTemplate,
|
||||
type LeaveNotificationNotifyScope,
|
||||
type LeaveNotificationTarget
|
||||
} from '../../shared/automation'
|
||||
|
||||
@@ -12,6 +13,11 @@ import {
|
||||
*
|
||||
* ## 旧语义(实测自 `group-exit-monitor-service.ts`)
|
||||
*
|
||||
* 旧版是**两层**配置,缺一不可:
|
||||
* 1. **管理群聊**(`monitoredRoomIds`)= 监测哪些群有人退出;
|
||||
* 2. **通知群聊**(`notificationRoomIds`)= 上面这批群里,**哪些要真的发通知**
|
||||
* —— 即对第 1 层的二次勾选。
|
||||
*
|
||||
* `notificationRoomIds` **不是**"统一通知接收目标列表",而是
|
||||
* **"哪些被监控群要在自己群里通报成员退出"**(per-group 多值):
|
||||
* - `applyCurrentMemberships()` 只在 `notificationRoomIds.has(roomId)` 时通知;
|
||||
@@ -19,10 +25,13 @@ import {
|
||||
*
|
||||
* ## 新语义
|
||||
*
|
||||
* 单值目标:`source_chat` / `self` / `file_transfer` / `contact`。
|
||||
* 拆成**两个正交维度**,恰好一一对应旧版那两层:
|
||||
* - `target` ← 旧版第 2 层里"发回本群"这个事实 ⇒ 恒为 `source_chat`;
|
||||
* - `notifyScope` / `notifyRoomIds` ← 旧版第 2 层是"哪些群",逐字保留。
|
||||
*
|
||||
* ⇒ 两者**只在一种情况下等价**:旧配置把**每一个**被监控群都勾上了通知。
|
||||
* 严格子集无法表达,按保守策略处理,绝不"随便取第一个群"。
|
||||
* ⇒ **迁移现在是无损的**。早期版本把目标压成单值、丢掉了第 2 层的"哪些群",
|
||||
* 于是部分勾选只能判成 `needs_review` 并强制停用;恢复 `notifyScope` 之后
|
||||
* 这个特例整体消失,用户不会再有"规则被无辜停用"的体验。
|
||||
*/
|
||||
|
||||
export interface LegacyLeaveNotificationState {
|
||||
@@ -34,30 +43,23 @@ export interface LegacyLeaveNotificationState {
|
||||
export type LeaveNotificationMigrationOutcome =
|
||||
/** 旧配置从不通知任何人 ⇒ 迁移成"关闭",行为完全一致。 */
|
||||
| 'lossless_off'
|
||||
/** 旧配置在**每个**被监控群里通报 ⇒ 等价于 `source_chat`,行为完全一致。 */
|
||||
| 'lossless_source_chat'
|
||||
/** 旧配置只在**部分**群里通报 ⇒ 单值目标无法表达,需用户重选。 */
|
||||
| 'needs_review'
|
||||
/** 旧配置在**每个**被监控群里通报 ⇒ `notifyScope: 'all'`,行为完全一致。 */
|
||||
| 'lossless_all_groups'
|
||||
/** 旧配置只在**部分**群里通报 ⇒ `notifyScope: 'selected'` + 原样保留那份勾选。 */
|
||||
| 'lossless_selected_groups'
|
||||
|
||||
export interface LeaveNotificationMigrationPlan {
|
||||
outcome: LeaveNotificationMigrationOutcome
|
||||
enabled: boolean
|
||||
target: LeaveNotificationTarget
|
||||
notifyScope: LeaveNotificationNotifyScope
|
||||
notifyRoomIds: string[]
|
||||
targetNeedsReview: boolean
|
||||
template: string
|
||||
}
|
||||
|
||||
function uniqueRoomIds(values: unknown): string[] {
|
||||
if (!Array.isArray(values)) return []
|
||||
const result: string[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const value of values) {
|
||||
const roomId = String(value || '').trim()
|
||||
if (!roomId || seen.has(roomId)) continue
|
||||
seen.add(roomId)
|
||||
result.push(roomId)
|
||||
}
|
||||
return result
|
||||
return normalizeLeaveNotificationRoomIds(values)
|
||||
}
|
||||
|
||||
export function planLeaveNotificationMigration(
|
||||
@@ -71,36 +73,44 @@ export function planLeaveNotificationMigration(
|
||||
)
|
||||
// 模板永远是无损迁移的那一项:它就是用户写的那段文字。
|
||||
const template = normalizeLeaveNotificationTemplate(legacy.notificationTemplate)
|
||||
const defaultTarget: LeaveNotificationTarget = { type: LEAVE_NOTIFICATION_DEFAULT_TARGET_TYPE }
|
||||
// 旧版收件人恒为事件所在群 ⇒ 无论勾了几个群,目标都是 source_chat。
|
||||
const target: LeaveNotificationTarget = { type: 'source_chat' }
|
||||
|
||||
if (!notifications.length) {
|
||||
// 旧语义是"从不通知" ⇒ 关掉,避免迁移后突然开始发消息。
|
||||
// 同时把范围写成 `selected` + 空集:配置本身也精确表达"一个都不通知"。
|
||||
return {
|
||||
outcome: 'lossless_off',
|
||||
enabled: false,
|
||||
target: defaultTarget,
|
||||
target,
|
||||
notifyScope: 'selected',
|
||||
notifyRoomIds: [],
|
||||
targetNeedsReview: false,
|
||||
template
|
||||
}
|
||||
}
|
||||
|
||||
if (monitored.length > 0 && notifications.length === monitored.length) {
|
||||
// 每个被监控群都在自己群里通报 ⇔ 单值的 `source_chat`。
|
||||
// 每个被监控群都在自己群里通报 ⇒ 等价于"全部已监控群聊"。
|
||||
return {
|
||||
outcome: 'lossless_source_chat',
|
||||
outcome: 'lossless_all_groups',
|
||||
enabled: true,
|
||||
target: { type: 'source_chat' },
|
||||
target,
|
||||
notifyScope: 'all',
|
||||
notifyRoomIds: [],
|
||||
targetNeedsReview: false,
|
||||
template
|
||||
}
|
||||
}
|
||||
|
||||
// 部分勾选:**不能**无损映射。不取第一个群、不改写成当前群聊、保持关闭、要求重选。
|
||||
// 部分勾选:**无损**保留那份子集,不再降级成 needs_review。
|
||||
return {
|
||||
outcome: 'needs_review',
|
||||
enabled: false,
|
||||
target: defaultTarget,
|
||||
targetNeedsReview: true,
|
||||
outcome: 'lossless_selected_groups',
|
||||
enabled: true,
|
||||
target,
|
||||
notifyScope: 'selected',
|
||||
notifyRoomIds: notifications,
|
||||
targetNeedsReview: false,
|
||||
template
|
||||
}
|
||||
}
|
||||
@@ -4,81 +4,65 @@ import {
|
||||
type LeaveNotificationConfig
|
||||
} from '../../shared/automation'
|
||||
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
|
||||
import { WECHAT_FILE_HELPER_USERNAME, isFileHelperUsername } from '../../shared/wechat-identities'
|
||||
import {
|
||||
automationContactDisplayName,
|
||||
filterSendableFriendContacts as filterSendable,
|
||||
isSendableFriendContact as isSendable,
|
||||
resolveAutomationTarget,
|
||||
type AutomationTargetContact,
|
||||
type AutomationTargetResolution,
|
||||
type ResolvedAutomationTarget
|
||||
} from './automation-wechat-target'
|
||||
|
||||
/**
|
||||
* 退群通知的**目标解析**。
|
||||
* 退群通知的**目标解析**(薄适配层)。
|
||||
*
|
||||
* 纯函数(联系人清单与自身身份由调用方注入),因为这里最容易出错、
|
||||
* 也最需要被单测穷举:发错人是不可撤销的。
|
||||
* 真正的判定在 `automation-wechat-target.ts` —— 那里才是**唯一实现**,
|
||||
* 定时日报与退群通知共用它。这里只有两件事:
|
||||
* 1. 把 `LeaveNotificationConfig` + 退群事件摊平成中性输入;
|
||||
* 2. 提供退群通知专属文案,保持既有调用方 / 测试不变。
|
||||
*
|
||||
* 四条规则:
|
||||
* 1. `source_chat` 取**事件所在群**(`event.conversationId`),
|
||||
* 不是"当前正在看的聊天",也不是"最后一个活跃会话"。
|
||||
* 2. 目标解析失败 → **报错**,绝不 fallback 到别的目标(尤其不许偷偷发文件助手)。
|
||||
* 3. 只允许出现在选项表里的目标类型。
|
||||
* 4. 显示名不带 wxid:日志与界面只出现用户能看懂的称呼。
|
||||
* ⚠️ 这里**不允许**再出现一份 switch / 判定逻辑 —— 两套并存迟早分叉。
|
||||
*/
|
||||
|
||||
/** 解析所需的最小联系人结构(`FormattedContact` 结构上可赋值给它)。 */
|
||||
export interface LeaveNotificationCandidateContact {
|
||||
m_nsUsrName: string
|
||||
m_nsNickName?: string
|
||||
type: 'user' | 'group'
|
||||
isOfficialAccount?: boolean
|
||||
wechatNickname?: string
|
||||
remark?: string
|
||||
}
|
||||
export type LeaveNotificationCandidateContact = AutomationTargetContact
|
||||
|
||||
export interface ResolvedLeaveNotificationTarget {
|
||||
recipient: { type: 'group' | 'contact'; id: string; name: string }
|
||||
/** 用户可读的目标名,直接进执行日志的 `detail`。 */
|
||||
displayName: string
|
||||
}
|
||||
export type ResolvedLeaveNotificationTarget = ResolvedAutomationTarget
|
||||
|
||||
export type LeaveNotificationTargetResolution =
|
||||
| { ok: true; target: ResolvedLeaveNotificationTarget }
|
||||
| { ok: false; error: string }
|
||||
export type LeaveNotificationTargetResolution = AutomationTargetResolution
|
||||
|
||||
/** 退群通知的目标文案(唯一一份)。 */
|
||||
export const LEAVE_NOTIFICATION_TARGET_MESSAGES = {
|
||||
options: LEAVE_NOTIFICATION_TARGET_OPTIONS,
|
||||
invalidTarget: '退群通知的发送目标无效,请重新选择',
|
||||
sourceMissing: '无法确定发生退群的群聊,本次通知未发送',
|
||||
sourceRecipientName: '当前群聊',
|
||||
sourceDisplayName: '发生退群事件的群聊',
|
||||
selfMissing: '无法确定当前登录的微信账号,本次通知未发送',
|
||||
contactNotChosen: '还没有选择通知联系人,请重新选择',
|
||||
contactUnavailable: '通知联系人已不存在或当前无法发送,请重新选择'
|
||||
} as const
|
||||
|
||||
/** 联系人显示名:备注 → 微信昵称 → 会话昵称 → 兜底称呼。**永不回落到 wxid**。 */
|
||||
export function leaveNotificationContactDisplayName(
|
||||
contact: LeaveNotificationCandidateContact
|
||||
): string {
|
||||
return (
|
||||
contact.remark?.trim() ||
|
||||
contact.wechatNickname?.trim() ||
|
||||
contact.m_nsNickName?.trim() ||
|
||||
'指定好友'
|
||||
)
|
||||
export function leaveNotificationContactDisplayName(contact: AutomationTargetContact): string {
|
||||
return automationContactDisplayName(contact)
|
||||
}
|
||||
|
||||
/**
|
||||
* 这个联系人能不能作为「指定好友」的发送目标。
|
||||
*
|
||||
* 排除:群聊、公众号(`gh_`)、文件传输助手、自己。
|
||||
* UI 的联系人选择器与运行时的目标解析**共用这一条判定**,
|
||||
* 否则会出现"能选但发不出去"。
|
||||
*/
|
||||
/** 这个联系人能不能作为「指定好友」的发送目标(与定时日报共用同一条判定)。 */
|
||||
export function isSendableFriendContact(
|
||||
contact: LeaveNotificationCandidateContact,
|
||||
contact: AutomationTargetContact,
|
||||
selfWxid?: string
|
||||
): boolean {
|
||||
if (contact.type !== 'user') return false
|
||||
if (contact.isOfficialAccount) return false
|
||||
const username = String(contact.m_nsUsrName || '').trim()
|
||||
if (!username) return false
|
||||
if (isFileHelperUsername(username)) return false
|
||||
const self = String(selfWxid || '').trim()
|
||||
if (self && username === self) return false
|
||||
return true
|
||||
return isSendable(contact, selfWxid)
|
||||
}
|
||||
|
||||
/** 供 UI 用的「可选好友」过滤(与运行时同一套判定)。 */
|
||||
export function filterSendableFriendContacts<T extends LeaveNotificationCandidateContact>(
|
||||
export function filterSendableFriendContacts<T extends AutomationTargetContact>(
|
||||
contacts: T[],
|
||||
selfWxid?: string
|
||||
): T[] {
|
||||
return contacts.filter((contact) => isSendableFriendContact(contact, selfWxid))
|
||||
return filterSendable(contacts, selfWxid)
|
||||
}
|
||||
|
||||
export function resolveLeaveNotificationTarget(input: {
|
||||
@@ -89,84 +73,19 @@ export function resolveLeaveNotificationTarget(input: {
|
||||
selfWxid?: string
|
||||
}): LeaveNotificationTargetResolution {
|
||||
const config = input.config
|
||||
if (!config) {
|
||||
return { ok: false, error: '退群通知尚未配置发送目标' }
|
||||
}
|
||||
const known = LEAVE_NOTIFICATION_TARGET_OPTIONS.some(
|
||||
(option) => option.type === config.target?.type
|
||||
if (!config) return { ok: false, error: '退群通知尚未配置发送目标' }
|
||||
return resolveAutomationTarget(
|
||||
{
|
||||
targetType: config.target?.type as never,
|
||||
sourceConversationId: String(input.event.conversationId || '').trim(),
|
||||
sourceDisplayName: String(input.event.groupName || '').trim(),
|
||||
...(config.target?.contactId ? { contactId: config.target.contactId } : {}),
|
||||
contacts: input.contacts,
|
||||
...(input.selfWxid ? { selfWxid: input.selfWxid } : {})
|
||||
},
|
||||
LEAVE_NOTIFICATION_TARGET_MESSAGES
|
||||
)
|
||||
if (!known) {
|
||||
return { ok: false, error: '退群通知的发送目标无效,请重新选择' }
|
||||
}
|
||||
|
||||
switch (config.target.type) {
|
||||
case 'source_chat': {
|
||||
const conversationId = String(input.event.conversationId || '').trim()
|
||||
if (!conversationId) {
|
||||
return { ok: false, error: '无法确定发生退群的群聊,本次通知未发送' }
|
||||
}
|
||||
const groupName = String(input.event.groupName || '').trim()
|
||||
return {
|
||||
ok: true,
|
||||
target: {
|
||||
recipient: {
|
||||
type: 'group',
|
||||
id: conversationId,
|
||||
name: groupName || '当前群聊'
|
||||
},
|
||||
displayName: groupName || '发生退群事件的群聊'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case 'self': {
|
||||
const selfWxid = String(input.selfWxid || '').trim()
|
||||
if (!selfWxid) {
|
||||
// 明确报错,不 fallback。§「不要偷偷 fallback 文件传输助手」。
|
||||
return { ok: false, error: '无法确定当前登录的微信账号,本次通知未发送' }
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
target: {
|
||||
recipient: { type: 'contact', id: selfWxid, name: '我' },
|
||||
displayName: '我'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case 'file_transfer':
|
||||
return {
|
||||
ok: true,
|
||||
target: {
|
||||
recipient: {
|
||||
type: 'contact',
|
||||
id: WECHAT_FILE_HELPER_USERNAME,
|
||||
name: leaveNotificationTargetLabel('file_transfer')
|
||||
},
|
||||
displayName: leaveNotificationTargetLabel('file_transfer')
|
||||
}
|
||||
}
|
||||
|
||||
case 'contact': {
|
||||
const contactId = String(config.target.contactId || '').trim()
|
||||
if (!contactId) {
|
||||
return { ok: false, error: '还没有选择通知联系人,请重新选择' }
|
||||
}
|
||||
const contact = input.contacts.find(
|
||||
(item) => String(item.m_nsUsrName || '').trim() === contactId
|
||||
)
|
||||
if (!contact || !isSendableFriendContact(contact, input.selfWxid)) {
|
||||
// §「如果之前选择的联系人被删除 / 不可发送 / 找不到,规则不要偷偷发给其它地方」。
|
||||
return { ok: false, error: '通知联系人已不存在或当前无法发送,请重新选择' }
|
||||
}
|
||||
const displayName = leaveNotificationContactDisplayName(contact)
|
||||
return {
|
||||
ok: true,
|
||||
target: {
|
||||
recipient: { type: 'contact', id: contactId, name: displayName },
|
||||
displayName
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 目标类型 → 界面短标签(保持既有导出面)。 */
|
||||
export { leaveNotificationTargetLabel }
|
||||
@@ -27,8 +27,7 @@ export interface ScheduledReportApiDependencies {
|
||||
| 'deleteTask'
|
||||
| 'setTaskEnabled'
|
||||
| 'runScheduledReportNow'
|
||||
> &
|
||||
Partial<Pick<ScheduledReportService, 'retryScheduledReportSend'>>
|
||||
>
|
||||
getCapability: () => Promise<PersonalWechatSendCapability>
|
||||
listContacts: () => FormattedContact[]
|
||||
isDatabaseReady: () => boolean
|
||||
@@ -250,16 +249,20 @@ export class ScheduledReportApiService {
|
||||
return result.data
|
||||
}
|
||||
|
||||
async retrySend(executionId: string): Promise<ScheduledReportExecution> {
|
||||
const retry = this.deps.service.retryScheduledReportSend
|
||||
if (!retry) {
|
||||
throw new ScheduledReportApiError(501, 'not_supported', '当前运行时不支持重新发送日报')
|
||||
}
|
||||
const result = await retry.call(this.deps.service, executionId)
|
||||
if (!result.data) {
|
||||
throw new ScheduledReportApiError(404, 'not_found', result.error || '未找到定时日报执行记录')
|
||||
}
|
||||
return result.data
|
||||
/**
|
||||
* 「重新发送」不再支持。
|
||||
*
|
||||
* 日报图片归日报历史所有,发送目标由规则配置决定,「把某次执行记录里那张 PNG
|
||||
* 就地再发一遍」这个语义已经不存在 —— 与其在此伪造一个只对部分规则有效的重发
|
||||
* 语义,不如**明确返回 501**。
|
||||
* 用户的替代路径:在日报历史里手动转发,或对该规则点「立即执行」重跑一次。
|
||||
*/
|
||||
async retrySend(_executionId: string): Promise<ScheduledReportExecution> {
|
||||
throw new ScheduledReportApiError(
|
||||
501,
|
||||
'not_supported',
|
||||
'当前运行时不支持重新发送日报;请在 TraceMemo 的自动化页面使用「立即执行」,或从日报历史手动转发。'
|
||||
)
|
||||
}
|
||||
|
||||
async executions(taskId: string): Promise<ScheduledReportApiExecution[]> {
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import {
|
||||
normalizeScheduledReportConfig,
|
||||
type ScheduledReportAutomationConfig
|
||||
} from '../../shared/automation'
|
||||
import type {
|
||||
ScheduledReportMemberNameMode,
|
||||
ScheduledReportMessageType,
|
||||
ScheduledReportRange
|
||||
} from '../../shared/scheduled-report'
|
||||
import type { SelectableReportTemplateId } from '../../shared/report-templates'
|
||||
|
||||
/**
|
||||
* 旧「定时日报任务」→ 新「AutomationRule(ruleType='scheduled_report')」的**纯映射器**。
|
||||
*
|
||||
* 单独成文件是为了能直接单测:这是整轮迁移里**唯一会改变用户既有行为**的地方,
|
||||
* 不允许只靠"跑一遍看看"来验证。
|
||||
*
|
||||
* ## 旧 target 的真实语义(实测)
|
||||
*
|
||||
* `ScheduledReportService.resolveTarget()`:
|
||||
* - `target` 以 `@chatroom` 结尾 ⇒ **直接发到那个群**(可能是另一个群);
|
||||
* - 否则 ⇒ **静默回落到来源群**。
|
||||
*
|
||||
* ⇒ 历史行为**事实上支持「生成 A 群日报 → 发 B 群」**,也存在一处静默 fallback。
|
||||
* 新产品明确不支持"指定另一个群聊",所以:
|
||||
* **能证明同群 → 无损映射成 `source_chat`;不能证明 → 停用 + 要求用户重选**,
|
||||
* 绝不自动改写、绝不偷偷丢掉目标。
|
||||
*/
|
||||
|
||||
/** 旧任务里迁移真正用得到的字段(其余字段不参与,也不需要读)。 */
|
||||
export interface LegacyScheduledReportTask {
|
||||
id?: unknown
|
||||
name?: unknown
|
||||
group?: unknown
|
||||
scheduleTime?: unknown
|
||||
reportRange?: unknown
|
||||
messageTypes?: unknown
|
||||
templateId?: unknown
|
||||
memberNameMode?: unknown
|
||||
timeoutSeconds?: unknown
|
||||
target?: unknown
|
||||
enabled?: unknown
|
||||
createdAt?: unknown
|
||||
updatedAt?: unknown
|
||||
lastRunAt?: unknown
|
||||
lastScheduledSlot?: unknown
|
||||
}
|
||||
|
||||
export type ScheduledReportMigrationOutcome =
|
||||
/** 目标与来源群是同一群 ⇒ 等价于 `source_chat`,行为完全一致。 */
|
||||
| 'lossless_source_chat'
|
||||
/** 目标是另一个群 / 无法确认是否同群 ⇒ 单值四选一表达不了,需用户重选。 */
|
||||
| 'needs_review'
|
||||
|
||||
export interface ScheduledReportMigrationPlan {
|
||||
outcome: ScheduledReportMigrationOutcome
|
||||
/** 迁移后的规则 id(确定性,可重复执行且不产生新 id)。 */
|
||||
ruleId: string
|
||||
name: string
|
||||
enabled: boolean
|
||||
config: ScheduledReportAutomationConfig
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
/** 把任意输入收敛成字符串。 */
|
||||
function asText(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : String(value ?? '').trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* 确定性 ruleId。
|
||||
*
|
||||
* 优先**原样复用旧 taskId**(旧 id 形如 `scheduled_report_<uuid>`,与自动化现有
|
||||
* id 空间 —— `randomUUID()` / `builtin-*` —— 不可能冲突)。
|
||||
* 旧 id 缺失时(文件被手改坏),退化成一个**由稳定字段派生**的 id,
|
||||
* 保证"重复迁移不会生成新规则"。
|
||||
*/
|
||||
export function scheduledReportMigrationRuleId(task: LegacyScheduledReportTask): string {
|
||||
const id = asText(task.id)
|
||||
if (id) return id
|
||||
const digest = createHash('sha1')
|
||||
.update(
|
||||
[asText(task.name), asText(task.group), asText(task.scheduleTime), asText(task.target)].join(
|
||||
'\u0001'
|
||||
)
|
||||
)
|
||||
.digest('hex')
|
||||
return `scheduled-report:${digest.slice(0, 32)}`
|
||||
}
|
||||
|
||||
/** 旧 `createdAt` / `updatedAt` 是 ISO 字符串;非法时回落到迁移时刻。 */
|
||||
function parseIso(value: unknown, fallback: number): number {
|
||||
const text = asText(value)
|
||||
if (!text) return fallback
|
||||
const parsed = Date.parse(text)
|
||||
return Number.isFinite(parsed) ? parsed : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条旧任务 → 迁移计划。
|
||||
*
|
||||
* `resolveConversationId` 由调用方注入(main 侧是 `chat-service.resolveMd5`,
|
||||
* 单测里是假的联系人表)。**它拿不到就说明主进程还没准备好**,
|
||||
* 调用方必须**推迟整批迁移**,而不是用"解析不到"去误判成 needs_review。
|
||||
*/
|
||||
export function planScheduledReportMigration(
|
||||
task: LegacyScheduledReportTask,
|
||||
resolveConversationId: (raw: string) => string | undefined,
|
||||
now: number
|
||||
): ScheduledReportMigrationPlan {
|
||||
const sourceRaw = asText(task.group)
|
||||
const targetRaw = asText(task.target)
|
||||
const sourceResolved = resolveConversationId(sourceRaw)
|
||||
const targetResolved = resolveConversationId(targetRaw)
|
||||
|
||||
/*
|
||||
* 三种"能证明是同一个群"的情况:
|
||||
* 1. target 为空 —— 旧 `normalizeInput` 本就把空 target 填成 group;
|
||||
* 2. 两者文本完全相等 —— 无论能否解析,用户表达的就是同一个东西;
|
||||
* 3. 两者都能解析且解析结果相同 —— 旧 UI 的常态(group=会话 md5,target=roomId)。
|
||||
*/
|
||||
const sameGroup =
|
||||
!targetRaw || targetRaw === sourceRaw || Boolean(sourceResolved && targetResolved && sourceResolved === targetResolved)
|
||||
|
||||
const config = normalizeScheduledReportConfig({
|
||||
schedule: { time: asText(task.scheduleTime) },
|
||||
report: {
|
||||
// 解析得到就用稳定会话 id;解析不到**保留原值** —— 运行期会如实失败,
|
||||
// 绝不在这里"猜一个群"。
|
||||
sourceConversationId: sourceResolved ?? sourceRaw,
|
||||
range: asText(task.reportRange) as ScheduledReportRange,
|
||||
messageTypes: task.messageTypes as ScheduledReportMessageType[],
|
||||
templateId: asText(task.templateId) as SelectableReportTemplateId,
|
||||
memberNameMode: asText(task.memberNameMode) as ScheduledReportMemberNameMode,
|
||||
timeoutSeconds: Number(task.timeoutSeconds)
|
||||
},
|
||||
target: { type: 'source_chat' },
|
||||
...(sameGroup ? {} : { targetNeedsReview: true }),
|
||||
// 旧目标原文只作展示;`sameGroup` 时不保留,避免留下看起来像"还生效"的残值。
|
||||
...(sameGroup || !targetRaw ? {} : { legacyTarget: targetRaw }),
|
||||
// 来源群被改写过(md5/群名 → roomId)时留下原文,便于用户核对。
|
||||
...(sourceRaw && sourceResolved && sourceRaw !== sourceResolved
|
||||
? { legacySourceGroup: sourceRaw }
|
||||
: {}),
|
||||
...(asText(task.lastRunAt) ? { lastRunAt: asText(task.lastRunAt) } : {}),
|
||||
...(asText(task.lastScheduledSlot) ? { lastScheduledSlot: asText(task.lastScheduledSlot) } : {})
|
||||
})
|
||||
|
||||
const name = asText(task.name) || '定时日报'
|
||||
return {
|
||||
outcome: sameGroup ? 'lossless_source_chat' : 'needs_review',
|
||||
ruleId: scheduledReportMigrationRuleId(task),
|
||||
name,
|
||||
// 不自动改写、也不自动启用:无法确认目标的规则一律停用。
|
||||
enabled: sameGroup ? task.enabled !== false : false,
|
||||
config,
|
||||
createdAt: parseIso(task.createdAt, now),
|
||||
updatedAt: parseIso(task.updatedAt, now)
|
||||
}
|
||||
}
|
||||
|
||||
export interface ScheduledReportMigrationSummary {
|
||||
total: number
|
||||
migrated: number
|
||||
lossless: number
|
||||
needsReview: number
|
||||
duplicatesSkipped: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 整批任务的迁移结果:**按 id 去重**,保证幂等(同一份旧文件跑两次结果一致)。
|
||||
*/
|
||||
export function planScheduledReportMigrationBatch(
|
||||
tasks: LegacyScheduledReportTask[],
|
||||
resolveConversationId: (raw: string) => string | undefined,
|
||||
now: number
|
||||
): { plans: ScheduledReportMigrationPlan[]; summary: ScheduledReportMigrationSummary } {
|
||||
const plans: ScheduledReportMigrationPlan[] = []
|
||||
const seen = new Set<string>()
|
||||
let duplicatesSkipped = 0
|
||||
let lossless = 0
|
||||
let needsReview = 0
|
||||
for (const task of tasks) {
|
||||
if (!task || typeof task !== 'object') continue
|
||||
const plan = planScheduledReportMigration(task, resolveConversationId, now)
|
||||
if (seen.has(plan.ruleId)) {
|
||||
duplicatesSkipped += 1
|
||||
continue
|
||||
}
|
||||
seen.add(plan.ruleId)
|
||||
plans.push(plan)
|
||||
if (plan.outcome === 'lossless_source_chat') lossless += 1
|
||||
else needsReview += 1
|
||||
}
|
||||
return {
|
||||
plans,
|
||||
summary: {
|
||||
total: plans.length + duplicatesSkipped,
|
||||
migrated: plans.length,
|
||||
lossless,
|
||||
needsReview,
|
||||
duplicatesSkipped
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
SCHEDULED_REPORT_TARGET_OPTIONS,
|
||||
scheduledReportTargetLabel,
|
||||
type ScheduledReportAutomationConfig
|
||||
} from '../../shared/automation'
|
||||
import {
|
||||
resolveAutomationTarget,
|
||||
resolveGroupConversationId,
|
||||
resolveGroupDisplayName,
|
||||
type AutomationTargetContact,
|
||||
type AutomationTargetResolution
|
||||
} from './automation-wechat-target'
|
||||
|
||||
/**
|
||||
* 定时日报的**目标解析**(薄适配层)。
|
||||
*
|
||||
* 判定逻辑在 `automation-wechat-target.ts`,与退群通知**共用同一份**。
|
||||
* 差异只有一处:来源会话不是"事件所在群",而是**这条规则配置的日报来源群**。
|
||||
*/
|
||||
|
||||
/** 定时日报的目标文案(唯一一份)。 */
|
||||
export const SCHEDULED_REPORT_TARGET_MESSAGES = {
|
||||
options: SCHEDULED_REPORT_TARGET_OPTIONS,
|
||||
invalidTarget: '定时日报的发送目标无效,请重新选择',
|
||||
sourceMissing: '无法确定日报来源群,本次日报未发送',
|
||||
sourceRecipientName: '日报来源群',
|
||||
sourceDisplayName: '日报来源群',
|
||||
selfMissing: '无法确定当前登录的微信账号,本次日报未发送',
|
||||
contactNotChosen: '还没有选择发送联系人,请重新选择',
|
||||
contactUnavailable: '发送联系人已不存在或当前无法发送,请重新选择'
|
||||
} as const
|
||||
|
||||
export function resolveScheduledReportTarget(input: {
|
||||
config: ScheduledReportAutomationConfig | undefined
|
||||
contacts: AutomationTargetContact[]
|
||||
/** 当前登录账号的 wxid;拿不到时传空串。 */
|
||||
selfWxid?: string
|
||||
}): AutomationTargetResolution {
|
||||
const config = input.config
|
||||
if (!config) return { ok: false, error: '定时日报尚未配置发送目标' }
|
||||
const sourceConversationId = String(config.report?.sourceConversationId || '').trim()
|
||||
return resolveAutomationTarget(
|
||||
{
|
||||
targetType: config.target?.type as never,
|
||||
sourceConversationId,
|
||||
// 来源群的可读名从通讯录解析;解析不到时由中性层给兜底称呼。
|
||||
sourceDisplayName: resolveGroupDisplayName(sourceConversationId, input.contacts),
|
||||
...(config.target?.contactId ? { contactId: config.target.contactId } : {}),
|
||||
contacts: input.contacts,
|
||||
...(input.selfWxid ? { selfWxid: input.selfWxid } : {})
|
||||
},
|
||||
SCHEDULED_REPORT_TARGET_MESSAGES
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 日报来源群的可读显示名(执行日志的 `sourceDisplayName` 用它)。
|
||||
*
|
||||
* **绝不回落到裸 id**:解析不到就说「日报来源群」。
|
||||
*/
|
||||
export function scheduledReportSourceDisplayName(
|
||||
config: ScheduledReportAutomationConfig | undefined,
|
||||
contacts: AutomationTargetContact[]
|
||||
): string {
|
||||
const raw = String(config?.report?.sourceConversationId || '').trim()
|
||||
if (!raw) return '日报来源群'
|
||||
return resolveGroupDisplayName(raw, contacts) || '日报来源群'
|
||||
}
|
||||
|
||||
/** 日报来源群解析成稳定会话 id(执行前预检用;解析不到返回 undefined)。 */
|
||||
export function scheduledReportSourceConversationId(
|
||||
config: ScheduledReportAutomationConfig | undefined,
|
||||
contacts: AutomationTargetContact[]
|
||||
): string | undefined {
|
||||
return resolveGroupConversationId(
|
||||
String(config?.report?.sourceConversationId || ''),
|
||||
contacts
|
||||
)
|
||||
}
|
||||
|
||||
export { scheduledReportTargetLabel }
|
||||
@@ -32,6 +32,12 @@ const AUTOMATION_PURPOSE_ALLOWLIST = new Set([
|
||||
// 退群通知(由 Automation 发出)。目标可以是群 / 自己 / 文件传输助手 / 指定好友,
|
||||
// 所以**不绑定**任何 "只能发回原群" 的作用域锁。
|
||||
'automation_leave_notification',
|
||||
// 定时日报(由 Automation 的 `scheduled_report` 规则发出)。目标是四选一,
|
||||
// 同样**不绑定**任何作用域锁。
|
||||
'automation_scheduled_report',
|
||||
// 定时日报的「后置词」(图片 sent 之后补发的那条文本)。与图片是两个独立
|
||||
// purpose,各自有幂等位 —— 少这一条会被 evaluateWechatActionPolicy 拦下。
|
||||
'automation_scheduled_report_postfix',
|
||||
'manual_report_image',
|
||||
'manual_report_postfix'
|
||||
])
|
||||
|
||||
Reference in new issue
Block a user