mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 17:25:15 +08:00
286 lines
9.3 KiB
JavaScript
286 lines
9.3 KiB
JavaScript
'use strict'
|
|
|
|
/** AI 晨报纯逻辑模块:配置收敛、媒体批次编排、AI 摘要提示词与严格静态 HTML 渲染构建。 */
|
|
|
|
const DEFAULT_CONFIG = {
|
|
groupIds: [],
|
|
groupNames: {},
|
|
windowHours: 24,
|
|
maxMessagesPerGroup: 300,
|
|
enableImageOcr: true,
|
|
enableImageVision: false,
|
|
enableVoiceTranscribe: true,
|
|
maxMediaPerGroup: 6,
|
|
renderWidth: 460,
|
|
/** 默认禁止自动发微信,需用户显式开启或手动点击发送。 */
|
|
autoSendWechat: false,
|
|
wechatTargetGroupId: ''
|
|
}
|
|
|
|
function clampInt(value, fallback, min, max) {
|
|
const num = Number(value)
|
|
if (!Number.isFinite(num)) return fallback
|
|
return Math.max(min, Math.min(max, Math.round(num)))
|
|
}
|
|
|
|
function normalizeConfig(raw) {
|
|
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
|
const groupIds = Array.isArray(src.groupIds)
|
|
? Array.from(
|
|
new Set(
|
|
src.groupIds
|
|
.map((item) => String(item || '').trim())
|
|
.filter(Boolean)
|
|
.slice(0, 10)
|
|
)
|
|
)
|
|
: []
|
|
const groupNames = {}
|
|
if (src.groupNames && typeof src.groupNames === 'object' && !Array.isArray(src.groupNames)) {
|
|
for (const [id, name] of Object.entries(src.groupNames)) {
|
|
const cleanId = String(id || '').trim()
|
|
const cleanName = String(name || '').trim().slice(0, 64)
|
|
if (cleanId && cleanName) groupNames[cleanId] = cleanName
|
|
}
|
|
}
|
|
return {
|
|
groupIds,
|
|
groupNames,
|
|
windowHours: clampInt(src.windowHours, DEFAULT_CONFIG.windowHours, 1, 168),
|
|
maxMessagesPerGroup: clampInt(
|
|
src.maxMessagesPerGroup,
|
|
DEFAULT_CONFIG.maxMessagesPerGroup,
|
|
20,
|
|
1000
|
|
),
|
|
enableImageOcr: src.enableImageOcr !== false,
|
|
enableImageVision: src.enableImageVision === true,
|
|
enableVoiceTranscribe: src.enableVoiceTranscribe !== false,
|
|
maxMediaPerGroup: clampInt(src.maxMediaPerGroup, DEFAULT_CONFIG.maxMediaPerGroup, 0, 15),
|
|
renderWidth: clampInt(src.renderWidth, DEFAULT_CONFIG.renderWidth, 320, 960),
|
|
autoSendWechat: src.autoSendWechat === true,
|
|
wechatTargetGroupId: String(src.wechatTargetGroupId || '').trim().slice(0, 128)
|
|
}
|
|
}
|
|
|
|
function escapeHtml(value) {
|
|
return String(value ?? '')
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/"/g, '"')
|
|
.replace(/'/g, ''')
|
|
}
|
|
|
|
/** 挑选待按需解析的图片与语音消息引用,单群总量受限以避免慢任务拖垮晨报生成。 */
|
|
function selectMediaBatchItems(messages, config, grantedPermissions = []) {
|
|
const limit = clampInt(config.maxMediaPerGroup, 6, 0, 15)
|
|
if (limit === 0 || !Array.isArray(messages) || messages.length === 0) return []
|
|
const perms = new Set(Array.isArray(grantedPermissions) ? grantedPermissions : [])
|
|
const items = []
|
|
const recent = [...messages].reverse()
|
|
|
|
for (const msg of recent) {
|
|
if (items.length >= limit) break
|
|
const messageRef = String((msg && msg.messageRef) || '').trim()
|
|
if (!messageRef) continue
|
|
if (msg.type === 'image') {
|
|
if (config.enableImageVision && perms.has('ai.vision')) {
|
|
items.push({ op: 'analyzeImage', messageRef })
|
|
} else if (config.enableImageOcr && perms.has('media.ocr')) {
|
|
items.push({ op: 'ocrImage', messageRef })
|
|
}
|
|
} else if (msg.type === 'voice') {
|
|
if (config.enableVoiceTranscribe && perms.has('media.transcribe')) {
|
|
items.push({ op: 'transcribeVoice', messageRef, options: { waitMs: 10_000 } })
|
|
}
|
|
}
|
|
}
|
|
return items
|
|
}
|
|
|
|
function buildDigestPromptMessages(input) {
|
|
const dateLabel = String(input.dateLabel || '').trim() || new Date().toISOString().slice(0, 10)
|
|
const sections = (input.groups || []).map((group) => {
|
|
const lines = (group.lines || []).slice(0, 120).join('\n')
|
|
return `【群聊:${group.name}】(共 ${group.messageCount} 条消息,解析媒体 ${group.mediaResolvedCount} 条)\n${lines || '(暂无有效内容)'}`
|
|
})
|
|
|
|
return [
|
|
{
|
|
role: 'system',
|
|
content: [
|
|
'你是一名简洁高效的中文晨报编辑,负责根据多个微信群最近一天的聊天记录与图片/语音解析结果整理一份结构化「AI 晨报」。',
|
|
'请严格输出纯 JSON,不要包含 Markdown 代码块包裹:',
|
|
'{"headline":"一句话总览(<=28字)","highlights":["重点1","重点2"],"actionItems":["待办或约定1"],"groupBriefs":[{"groupName":"群名","summary":"该群简述(<=80字)"}]}'
|
|
].join('\n')
|
|
},
|
|
{
|
|
role: 'user',
|
|
content: `日期:${dateLabel}\n\n${sections.join('\n\n')}`
|
|
}
|
|
]
|
|
}
|
|
|
|
function parseDigestSummary(rawText, fallbackGroups = []) {
|
|
const cleaned = String(rawText || '')
|
|
.trim()
|
|
.replace(/^```(?:json)?\s*/i, '')
|
|
.replace(/\s*```$/i, '')
|
|
.trim()
|
|
try {
|
|
const parsed = JSON.parse(cleaned)
|
|
if (parsed && typeof parsed === 'object') {
|
|
const headline = String(parsed.headline || '今日群聊晨报').trim().slice(0, 60)
|
|
const highlights = Array.isArray(parsed.highlights)
|
|
? parsed.highlights.map((x) => String(x || '').trim()).filter(Boolean).slice(0, 6)
|
|
: []
|
|
const actionItems = Array.isArray(parsed.actionItems)
|
|
? parsed.actionItems.map((x) => String(x || '').trim()).filter(Boolean).slice(0, 6)
|
|
: []
|
|
const groupBriefs = Array.isArray(parsed.groupBriefs)
|
|
? parsed.groupBriefs
|
|
.filter((item) => item && typeof item === 'object')
|
|
.map((item) => ({
|
|
groupName: String(item.groupName || '群聊').trim().slice(0, 48),
|
|
summary: String(item.summary || '').trim().slice(0, 200)
|
|
}))
|
|
.filter((item) => item.summary)
|
|
.slice(0, 10)
|
|
: []
|
|
if (headline || highlights.length > 0 || groupBriefs.length > 0) {
|
|
return { headline, highlights, actionItems, groupBriefs }
|
|
}
|
|
}
|
|
} catch {
|
|
// 非 JSON 文本回退为单条摘要展示,不中断渲染。
|
|
}
|
|
return {
|
|
headline: '今日群聊晨报',
|
|
highlights: cleaned ? [cleaned.slice(0, 240)] : ['最近周期内暂无重点讨论'],
|
|
actionItems: [],
|
|
groupBriefs: fallbackGroups.map((g) => ({
|
|
groupName: g.name,
|
|
summary: `共采集 ${g.messageCount} 条消息,解析媒体 ${g.mediaResolvedCount} 条。`
|
|
}))
|
|
}
|
|
}
|
|
|
|
const DIGEST_CSS = `
|
|
* { box-sizing: border-box; }
|
|
body {
|
|
margin: 0;
|
|
padding: 20px;
|
|
background: #f4f6f9;
|
|
color: #18212f;
|
|
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
|
|
}
|
|
.digest-card {
|
|
background: #ffffff;
|
|
border-radius: 16px;
|
|
padding: 24px;
|
|
border: 1px solid #e5e9f0;
|
|
}
|
|
.digest-kicker {
|
|
font-size: 12px;
|
|
letter-spacing: 0.08em;
|
|
color: #2563eb;
|
|
font-weight: 700;
|
|
margin-bottom: 6px;
|
|
}
|
|
.digest-title {
|
|
margin: 0 0 8px;
|
|
font-size: 22px;
|
|
line-height: 1.35;
|
|
}
|
|
.digest-meta {
|
|
font-size: 12px;
|
|
color: #64748b;
|
|
margin-bottom: 18px;
|
|
}
|
|
.digest-section {
|
|
margin-top: 18px;
|
|
padding-top: 16px;
|
|
border-top: 1px solid #edf0f5;
|
|
}
|
|
.digest-section h2 {
|
|
margin: 0 0 10px;
|
|
font-size: 15px;
|
|
color: #0f172a;
|
|
}
|
|
.digest-list {
|
|
margin: 0;
|
|
padding-left: 18px;
|
|
line-height: 1.65;
|
|
font-size: 14px;
|
|
}
|
|
.digest-group {
|
|
background: #f8fafc;
|
|
border-radius: 10px;
|
|
padding: 12px 14px;
|
|
margin-bottom: 10px;
|
|
}
|
|
.digest-group-name {
|
|
font-size: 13px;
|
|
font-weight: 700;
|
|
color: #1e293b;
|
|
margin-bottom: 4px;
|
|
}
|
|
.digest-group-summary {
|
|
margin: 0;
|
|
font-size: 13px;
|
|
line-height: 1.6;
|
|
color: #334155;
|
|
}
|
|
.digest-footer {
|
|
margin-top: 18px;
|
|
padding-top: 12px;
|
|
border-top: 1px dashed #e2e8f0;
|
|
font-size: 11px;
|
|
color: #94a3b8;
|
|
}
|
|
`
|
|
|
|
/** 构建纯静态、无脚本、无外链的晨报 HTML,满足 HtmlRenderService 的严格安全校验。 */
|
|
function buildDigestHtml(data) {
|
|
const dateLabel = escapeHtml(data.dateLabel || '')
|
|
const headline = escapeHtml(data.headline || '今日群聊晨报')
|
|
const totalMessages = Number(data.totalMessages) || 0
|
|
const totalMedia = Number(data.totalMediaResolved) || 0
|
|
const groupCount = Number(data.groupCount) || 0
|
|
|
|
const highlightsHtml = (data.highlights || [])
|
|
.map((item) => `<li>${escapeHtml(item)}</li>`)
|
|
.join('')
|
|
const actionsHtml = (data.actionItems || [])
|
|
.map((item) => `<li>${escapeHtml(item)}</li>`)
|
|
.join('')
|
|
const briefsHtml = (data.groupBriefs || [])
|
|
.map(
|
|
(item) =>
|
|
`<div class="digest-group"><div class="digest-group-name">${escapeHtml(item.groupName)}</div><p class="digest-group-summary">${escapeHtml(item.summary)}</p></div>`
|
|
)
|
|
.join('')
|
|
|
|
return `<main class="digest-card">
|
|
<div class="digest-kicker">TRACEMEMO AI 晨报 · ${dateLabel}</div>
|
|
<h1 class="digest-title">${headline}</h1>
|
|
<div class="digest-meta">覆盖 ${groupCount} 个群聊 · 采样 ${totalMessages} 条消息 · 解析 ${totalMedia} 条图片/语音</div>
|
|
${highlightsHtml ? `<section class="digest-section"><h2>今日重点</h2><ul class="digest-list">${highlightsHtml}</ul></section>` : ''}
|
|
${actionsHtml ? `<section class="digest-section"><h2>待办与约定</h2><ul class="digest-list">${actionsHtml}</ul></section>` : ''}
|
|
${briefsHtml ? `<section class="digest-section"><h2>各群速览</h2>${briefsHtml}</section>` : ''}
|
|
<footer class="digest-footer">由 TraceMemo 扩展「AI 晨报」离线生成</footer>
|
|
</main>`
|
|
}
|
|
|
|
module.exports = {
|
|
DEFAULT_CONFIG,
|
|
DIGEST_CSS,
|
|
normalizeConfig,
|
|
escapeHtml,
|
|
selectMediaBatchItems,
|
|
buildDigestPromptMessages,
|
|
parseDigestSummary,
|
|
buildDigestHtml
|
|
}
|