mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: 新增拓展中心功能, 提供 关键词回复 去水印模板
This commit is contained in:
1 parent
aca103cb96
commit
b9ad4e1d71
85 files changed
+14750
-106
No files matched your search
@@ -0,0 +1,37 @@
|
||||
# 扩展示例
|
||||
|
||||
两个可直接安装的示例,用来验证扩展中心从安装到发送的完整链路。
|
||||
|
||||
| 目录 | 用途 | 申请权限 |
|
||||
| --- | --- | --- |
|
||||
| `keyword-bot/` | 消息事件、关键词匹配、Gateway 发送、自动化动作 | `messages.subscribe`、`contacts.list`、`wechat.send.text`、`storage`、`automation.action` |
|
||||
| `douyin-sender/` | @我 发抖音链接 → 解析 → 下载 → 发回视频;配置页可测试发送 | `messages.subscribe`、`contacts.list`、`wechat.send.video`、`wechat.send.text`、`storage` |
|
||||
|
||||
## 安装
|
||||
|
||||
TraceMemo → 左侧「扩展」→「安装目录」,选择对应目录即可。
|
||||
|
||||
安装后扩展默认**未启用**:
|
||||
|
||||
- `keyword-bot` 的 `enabled` 为 `false`,需要在配置页手动打开才会回复;
|
||||
- `douyin-sender` 依赖本机的 `python3`、Chrome 和抖音解析脚本,安装前先看它自己的 README。
|
||||
|
||||
## 测试建议
|
||||
|
||||
- 关键词机器人默认监听全部群聊 + 私聊;想只对某个群生效,在「监听范围」里搜索并多选群聊。
|
||||
- 冷却时间按「会话 + 规则」计算,避免同一句话连续刷屏。
|
||||
- 扩展的发送走 `tm.wechat.send`,最终仍由 TraceMemo Gateway 做权限、授权校验、限流与审计。
|
||||
|
||||
## 开发
|
||||
|
||||
扩展目录里只需要 `manifest.json` 与入口文件:
|
||||
|
||||
```text
|
||||
my-extension/
|
||||
manifest.json
|
||||
ui/index.html
|
||||
background/index.js
|
||||
```
|
||||
|
||||
`background/index.js` 导出 `activate(tm)`(或 `module.exports = { activate }`)。页面通过
|
||||
`postMessage` 与宿主通信,协议见 `docs/extensions/api-reference.md`。
|
||||
@@ -0,0 +1,143 @@
|
||||
# 抖音视频搬运
|
||||
|
||||
被 @ 且消息里带抖音分享链接时,解析作品、下载视频,并发回原会话。
|
||||
|
||||
判定范围由扩展自己控制:只有**真正 @ 到当前登录账号**的文本消息才会进入流程
|
||||
(`subscriptions.requireMentionMe: true`),普通消息直接忽略。
|
||||
|
||||
## 前置条件
|
||||
|
||||
- 本机有 `python3`(3.10 及以上)。
|
||||
- 本机装了 Chrome:解析脚本用真实浏览器打开作品页、拦截页面自己发出的 `aweme/detail` 响应,
|
||||
不自造签名。
|
||||
- 解析脚本已存在于本机(默认 `scripts/douyin.py`,相对于扩展目录,也可在配置页指定自定义路径)。
|
||||
- 首次运行时脚本会在 `~/Library/Caches/douyin-video/venv`(Windows 落在 `%LOCALAPPDATA%`)
|
||||
自建 venv 并安装 `playwright` / `requests`,约 30 秒;之后复用,不再安装。
|
||||
|
||||
## 安装
|
||||
|
||||
TraceMemo → 左侧「扩展」→「安装目录」,选择本目录 `douyin-sender/`。
|
||||
|
||||
安装完成后:
|
||||
|
||||
1. 打开「抖音解析设置」页面,确认 Python 路径与脚本路径;
|
||||
2. 打开总开关,保存;
|
||||
3. 在「测试发送」里选目标群、粘贴抖音分享文案,点「测试发送」验证;
|
||||
或在微信里 @ 自己发一条带抖音分享链接的文本消息。
|
||||
|
||||
扩展默认 `enabled: false`,安装后不会自动对外发送。
|
||||
|
||||
配置页的群列表来自本机通讯录,对应权限 `contacts.list`(只读群名与会话 id,不含聊天内容)。
|
||||
|
||||
升级同 id 的扩展会替换代码并保留配置;如果新版本**新增了权限**(例如从 image 换成 video),
|
||||
升级后请「停用 → 启用」一次,让宿主按新 manifest 重新授权。
|
||||
|
||||
## 测试发送(配置页)
|
||||
|
||||
配置页底部有独立的「测试发送」:
|
||||
|
||||
1. 下拉选择目标群(列表来自 `contacts.listGroups`,需要 `contacts.list` 权限);
|
||||
2. 粘贴抖音链接或整段分享文案(命令行脚本不需要手动截取 URL);
|
||||
3. 点「测试发送」,页面会轮询进度,解析完成后把去水印视频发到该群;
|
||||
4. 测试路径**不发回执**,避免测试时多一条消息;
|
||||
5. 测试任务同样计入统计,进度显示在「当前任务」。
|
||||
|
||||
设置页可选使用「抖音 Cookie」面板粘贴并保存 Cookie header。宿主通过系统安全存储加密后保存在本机,页面只展示是否已配置,不会回显内容;测试发送与自动解析时在后台使用该 Cookie,未配置时也可回退读取本机 `douyin-cookie` 文件。
|
||||
|
||||
## 配置字段
|
||||
|
||||
| 字段 | 默认值 | 说明 |
|
||||
| ----------------- | ------------------------ | ---------------------------------------------------------------------- |
|
||||
| `enabled` | `false` | 总开关;关闭时任何消息都不处理 |
|
||||
| `pythonPath` | `python3` | Python 可执行文件,支持 `~` |
|
||||
| `scriptPath` | `scripts/douyin.py` | 解析脚本路径(默认相对于扩展目录,支持 `~` 与绝对路径) |
|
||||
| `quality` | `720` | `''` 最高 / `1080` / `720` / `540`;其他值收敛到 `720` |
|
||||
| `showUi` | `false` | 排障开关:显示浏览器窗口以观察最终页面;不保证改变平台响应 |
|
||||
| 抖音 Cookie | 未配置 | 配置页输入后由 Electron `safeStorage` 加密保存 |
|
||||
| `ackText` | `收到,正在解析,请稍候…`| 命中后先回复的文本;留空表示不回执 |
|
||||
| `errorReply` | `true` | 失败时是否在原会话回一条简短说明 |
|
||||
| `includeDirect` | `false` | 是否同时处理私聊 |
|
||||
| `groups` | `[]` | 群白名单;空数组表示全部群 |
|
||||
| `cooldownSeconds` | `60` | 按会话计的冷却,0–3600 |
|
||||
| `maxFileMB` | `100` | 单文件上限,1–100,不能超过宿主 100 MB 硬限制 |
|
||||
|
||||
保存时写入 `configVersion: 1`;后台最多 1 秒内读到新配置(配置缓存 TTL 1000 ms)。
|
||||
|
||||
## 处理流程
|
||||
|
||||
1. `message.received` → 判定顺序:总开关 → 自己发的 → 非 text → 未 @我 → 提取链接 → 会话范围 → 冷却。
|
||||
2. 命中后先回执(`ackText`,默认「收到,正在解析,请稍候…」;留空关闭),再进入解析。
|
||||
3. `python3 <script> "<链接>" -o <dataDir>/downloads --wait 40 --download-timeout 90 --json --video-only --download`,单次打开作品页并完成解析、下载;图集只返回类型、不下载;进程总超时 420 秒,输出上限 8 MB,`cwd` 为扩展数据目录。
|
||||
4. 从 JSON 结果中读取作品元数据与 `saved` 绝对路径;校验文件存在、是普通文件、未超过上限。
|
||||
5. 若结果为图集,记为 `IMAGE_SET` 并按配置处理失败提示;若解析/下载失败,保留脚本返回的错误原因。
|
||||
6. 发送视频,`dedupeKey = eventId + ':video'`(不再额外发送作品标题文本)。
|
||||
7. 每个阶段都写 `progress` 快照并记一条日志;配置页每 2 秒刷新一次进度。
|
||||
8. 无论成败写一条统计(成功/失败分别计数);失败只记阶段、错误码与去掉 URL / 路径的短原因。
|
||||
9. 冷却只在**视频发送成功后**写入。
|
||||
|
||||
同一会话同时只跑一个任务;同一条消息重复投递时按 `会话 + 链接` 去重。启动时会清理
|
||||
`<dataDir>/downloads`:只保留最近 20 个文件,并删除 7 天前的文件。
|
||||
|
||||
失败文案固定为三种,原因截断到 60 字且不含路径:
|
||||
|
||||
- `解析失败:<短原因>`
|
||||
- `视频过大(<N>MB),已跳过`
|
||||
- `暂不支持图集`
|
||||
|
||||
## 发送通道
|
||||
|
||||
视频走宿主的 **video 通道**:`tm.wechat.send({ type: 'video', to, path })`。
|
||||
原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交,所以 `permissions` 里申请的是 `wechat.send.video`。
|
||||
|
||||
媒体文件必须落在扩展数据目录或系统临时目录内(宿主会用 `realpath` 复核),扩展名必须是
|
||||
`mp4/mov/m4v`,大小 1 B–100 MB。所有发送仍要过 Gateway 的权限、
|
||||
授权与限流:同一扩展 60 秒最多 10 条,两条之间至少 2 秒。
|
||||
|
||||
## 限制
|
||||
|
||||
- 只处理视频;图集(`type: 'image'`)不下载,按配置回「暂不支持图集」。
|
||||
- 单个文件 ≤ 100 MB,超过不发送。
|
||||
- 冷却按会话计,冷却期内同一会话的新链接会被忽略。
|
||||
- 事件投递是「至多一次」:TraceMemo 未运行期间的消息不会补发。
|
||||
- 脚本路径必须在本机真实存在;路径错误时错误文案会提示检查 Python 路径。
|
||||
- 解析依赖抖音页面结构,脚本自身失效时扩展只能报「解析失败」。
|
||||
|
||||
## 排障:`页面已加载(NNNKB)但未发出 detail 请求`
|
||||
|
||||
这是浏览器打开了页面,但没有捕获到 `aweme/detail` 的作品数据。仅凭这一条错误不能判断作品已删除;页面也可能是作品壳、推荐页或平台验证状态。先看 `--debug` 现场中的页面标题、地址和截图。扩展不会并发启动第二次解析;测试发送失败时会在页面显示阶段、错误码和去掉 URL / 本地路径后的短原因。
|
||||
|
||||
仍需手动复试时:
|
||||
|
||||
1. 先等一会儿再尝试,避免同一作品短时间内重复请求;
|
||||
2. 配置页勾选「显示浏览器窗口」后重新测试,观察最终停留页面;
|
||||
3. 命令行单独验证时使用同一份脚本,避免与扩展并发运行:
|
||||
|
||||
```bash
|
||||
python3 scripts/douyin.py \
|
||||
"https://v.douyin.com/xxxxxx/" --json --wait 40 --show-ui
|
||||
```
|
||||
|
||||
## 进度与统计
|
||||
|
||||
- 回执:命中后先发一条 `ackText`,默认「收到,正在解析,请稍候…」;留空则不回。
|
||||
- 进度:存储键 `progress`,结构 `{stage,status,startedAt,updatedAt,awemeId,errorType,errorMessage}`。
|
||||
配置页每 2 秒读取一次,显示「已接收 / 解析 / 下载 / 发送 / 补发文案 / 完成」,
|
||||
失败时显示失败所在阶段与错误码。
|
||||
- 统计:存储键 `stats`,结构 `{dateKey,todayTotal,todaySuccess,todayFailure,lastJobs[]}`;
|
||||
失败也计数,`lastJobs` 保留最近 20 条(含阶段与错误码)。
|
||||
- 页面顶部「统计」显示今日总计 / 成功 / 失败;表格展示最近 8 条。
|
||||
|
||||
## 隐私
|
||||
|
||||
- 分享链接会交给本机脚本,由脚本访问抖音页面;扩展本身不向任何第三方发请求。
|
||||
- 下载的视频存放在扩展数据目录 `downloads/` 下,发送后不自动删除(按上面的规则轮转清理)。
|
||||
- 统计只保存时间、作品 id、阶段、成败、错误码,**不含** URL、标题、作者、会话 id。
|
||||
- 日志只写阶段与错误类型。
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
node --test examples/extensions/douyin-sender/tests/douyin.test.mjs
|
||||
```
|
||||
|
||||
用例全部离线:不联网、不启动 python、不读写真实文件。
|
||||
@@ -0,0 +1,766 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* 抖音视频搬运 —— 后台入口。
|
||||
*
|
||||
* 链路:`message.received` → 纯函数判定 → 解析并下载脚本 →
|
||||
* 经宿主 `wechat.send` 的 video 通道发回原会话。
|
||||
*
|
||||
* 这个文件跑在宿主的扩展子进程里,**只**用 `tm` 暴露的能力:
|
||||
* 没有 socket、没有 dylib、没有直接读写微信数据目录。
|
||||
*/
|
||||
|
||||
const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
const fsSync = require('node:fs')
|
||||
const fs = require('node:fs/promises')
|
||||
const { execFile } = require('node:child_process')
|
||||
const { promisify } = require('node:util')
|
||||
|
||||
const {
|
||||
normalizeConfig,
|
||||
extractDouyinUrl,
|
||||
parseDownloadedResult,
|
||||
shouldHandle,
|
||||
isFileTooLarge
|
||||
} = require('../lib/douyin')
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const CONFIG_KEY = 'config'
|
||||
const STATS_KEY = 'stats'
|
||||
const PROGRESS_KEY = 'progress'
|
||||
const TEST_RESULT_KEY = 'testResult'
|
||||
const CONFIG_TTL_MS = 1000
|
||||
|
||||
/** 配置页「测试发送」的轮询间隔;页面只负责写请求、读结果。 */
|
||||
|
||||
/** 阶段名只用于展示与日志,不参与判断。 */
|
||||
const STAGE_LABELS = {
|
||||
accepted: '已接收',
|
||||
resolve: '解析',
|
||||
resolveDownload: '解析并下载',
|
||||
download: '下载',
|
||||
send: '发送',
|
||||
caption: '补发文案',
|
||||
done: '完成',
|
||||
failed: '失败'
|
||||
}
|
||||
|
||||
/** 脚本内部等待抖音接口的秒数,解析与下载共用。 */
|
||||
const SCRIPT_WAIT_SECONDS = '40'
|
||||
const DOWNLOAD_AND_RESOLVE_TIMEOUT_MS = 420_000
|
||||
const MAX_OUTPUT_BYTES = 8 * 1024 * 1024
|
||||
|
||||
/** 宿主限制:同一扩展两次发送之间至少 2 秒,这里留 200ms 余量。 */
|
||||
const SEND_GAP_MS = 2200
|
||||
|
||||
const KEEP_RECENT_FILES = 20
|
||||
const MAX_FILE_AGE_MS = 7 * 24 * 60 * 60 * 1000
|
||||
const MAX_JOB_HISTORY = 20
|
||||
const COOLDOWN_MAP_LIMIT = 500
|
||||
|
||||
let tm = null
|
||||
let cachedConfig = null
|
||||
let cachedAt = 0
|
||||
let cachedStats = null
|
||||
let cachedProgress = null
|
||||
|
||||
/** 会话 → 冷却截止时间(epoch 毫秒)。 */
|
||||
const cooldownUntil = new Map()
|
||||
/** 正在处理的会话:同一会话同时只跑一个任务。 */
|
||||
const activeConversations = new Set()
|
||||
/** 正在处理的 `会话|链接`:避免同一条消息被重复投递时跑两遍。 */
|
||||
const activeJobs = new Set()
|
||||
|
||||
function safeLog(level, message) {
|
||||
try {
|
||||
const writer = tm && tm.log && tm.log[level]
|
||||
if (typeof writer === 'function') writer.call(tm.log, String(message))
|
||||
} catch {
|
||||
// 日志通道本身不可用时不能影响发送流程。
|
||||
}
|
||||
}
|
||||
|
||||
/** 错误类型化:日志只保留阶段与错误码,不写 URL、路径、标题。 */
|
||||
function errorType(error) {
|
||||
if (!error) return 'UNKNOWN'
|
||||
if (error.killed || error.signal) return 'TIMEOUT'
|
||||
// 数字退出码单独标成 EXIT_n,避免统计里只看到一个「2」。
|
||||
if (typeof error.code === 'number') return `EXIT_${error.code}`
|
||||
if (typeof error.code === 'string' && /^[A-Z0-9_]+$/.test(error.code)) return error.code
|
||||
if (error.name === 'Error') return 'ERROR'
|
||||
return String(error.name || 'ERROR')
|
||||
}
|
||||
|
||||
/** 去掉换行、链接与路径,只留 ≤60 字的短原因。 */
|
||||
function shortReason(input) {
|
||||
let text = String(input === null || input === undefined ? '' : input)
|
||||
.replace(/https?:\/\/\S+/gi, ' ')
|
||||
.replace(/[\r\n\t]+/g, ' ')
|
||||
.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s"'))]+)+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
text = text.replace(/^[::,,。;;-]+/, '').trim()
|
||||
text = text.replace(/title=[^,,))]+/gi, 'title=已隐藏')
|
||||
if (!text) return '未知原因'
|
||||
return text.slice(0, 60)
|
||||
}
|
||||
|
||||
function parseFailure(cause, type) {
|
||||
return { ok: false, message: `解析失败:${shortReason(cause)}`, errorType: type || 'PARSE' }
|
||||
}
|
||||
|
||||
function tooLargeMessage(sizeBytes) {
|
||||
const megabytes = Math.max(1, Math.ceil(Number(sizeBytes) / (1024 * 1024)))
|
||||
return `视频过大(${megabytes}MB),已跳过`
|
||||
}
|
||||
|
||||
function expandHome(value) {
|
||||
const raw = String(value || '').trim()
|
||||
if (!raw) return ''
|
||||
if (raw === '~') return os.homedir()
|
||||
if (raw.startsWith('~/') || raw.startsWith('~' + path.sep)) {
|
||||
return path.join(os.homedir(), raw.slice(2))
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
function downloadsDir() {
|
||||
return path.join(tm.extension.dataDir, 'downloads')
|
||||
}
|
||||
|
||||
async function loadConfig() {
|
||||
if (cachedConfig && Date.now() - cachedAt < CONFIG_TTL_MS) return cachedConfig
|
||||
let stored = null
|
||||
try {
|
||||
stored = await tm.storage.get(CONFIG_KEY)
|
||||
} catch (error) {
|
||||
safeLog('warn', `读取配置失败:${errorType(error)}`)
|
||||
}
|
||||
cachedConfig = normalizeConfig(stored)
|
||||
cachedAt = Date.now()
|
||||
return cachedConfig
|
||||
}
|
||||
|
||||
function dateKey(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${month}-${day}`
|
||||
}
|
||||
|
||||
function normalizeStats(raw) {
|
||||
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
||||
const lastJobs = Array.isArray(input.lastJobs)
|
||||
? input.lastJobs
|
||||
.filter((job) => job && typeof job === 'object')
|
||||
.slice(0, MAX_JOB_HISTORY)
|
||||
.map((job) => ({
|
||||
at: Number(job.at) || 0,
|
||||
awemeId: String(job.awemeId || '').slice(0, 32),
|
||||
ok: job.ok === true,
|
||||
stage: String(job.stage || '').slice(0, 20),
|
||||
errorType: String(job.errorType || '').slice(0, 24)
|
||||
}))
|
||||
: []
|
||||
const total = Math.max(0, Math.trunc(Number(input.todayTotal ?? input.todayCount) || 0))
|
||||
return {
|
||||
dateKey: typeof input.dateKey === 'string' ? input.dateKey.slice(0, 10) : '',
|
||||
todayTotal: total,
|
||||
todaySuccess: Math.max(0, Math.trunc(Number(input.todaySuccess) || 0)),
|
||||
todayFailure: Math.max(0, Math.trunc(Number(input.todayFailure) || 0)),
|
||||
lastJobs
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
if (cachedStats) return cachedStats
|
||||
let stored = null
|
||||
try {
|
||||
stored = await tm.storage.get(STATS_KEY)
|
||||
} catch (error) {
|
||||
safeLog('warn', `读取统计失败:${errorType(error)}`)
|
||||
}
|
||||
cachedStats = normalizeStats(stored)
|
||||
return cachedStats
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加一条任务记录。
|
||||
*
|
||||
* 统计里只允许出现 awemeId / 时间 / 阶段 / 成败 / 错误类型;URL、标题、作者、
|
||||
* 会话 id 都不写,避免把聊天内容沉淀成扩展数据。
|
||||
*/
|
||||
async function recordJob(job) {
|
||||
const now = Date.now()
|
||||
const current = await loadStats()
|
||||
const key = dateKey(now)
|
||||
const sameDay = current.dateKey === key
|
||||
const next = {
|
||||
dateKey: key,
|
||||
todayTotal: (sameDay ? current.todayTotal : 0) + 1,
|
||||
todaySuccess: (sameDay ? current.todaySuccess : 0) + (job.ok === true ? 1 : 0),
|
||||
todayFailure: (sameDay ? current.todayFailure : 0) + (job.ok === true ? 0 : 1),
|
||||
lastJobs: [
|
||||
{
|
||||
at: now,
|
||||
awemeId: String(job.awemeId || '').slice(0, 32),
|
||||
ok: job.ok === true,
|
||||
stage: String(job.stage || '').slice(0, 20),
|
||||
errorType: String(job.errorType || '').slice(0, 24)
|
||||
},
|
||||
...current.lastJobs
|
||||
].slice(0, MAX_JOB_HISTORY)
|
||||
}
|
||||
cachedStats = next
|
||||
try {
|
||||
await tm.storage.set(STATS_KEY, next)
|
||||
} catch (error) {
|
||||
safeLog('warn', `写入统计失败:${errorType(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写「当前任务」快照,供配置页展示进度。
|
||||
*
|
||||
* 只保留一条最近任务:jobId 用事件 id(不可逆哈希),不含会话与正文。
|
||||
* 写失败只 warn,不能因为展示层异常影响发送。
|
||||
*/
|
||||
async function setProgress(patch) {
|
||||
const now = Date.now()
|
||||
const next = {
|
||||
...(cachedProgress || {}),
|
||||
...patch,
|
||||
updatedAt: now
|
||||
}
|
||||
if (!next.startedAt) next.startedAt = now
|
||||
cachedProgress = next
|
||||
const label = STAGE_LABELS[next.stage] || next.stage || ''
|
||||
safeLog('info', `任务进度:${label}${next.awemeId ? `(${next.awemeId})` : ''}`)
|
||||
try {
|
||||
await tm.storage.set(PROGRESS_KEY, next)
|
||||
} catch (error) {
|
||||
safeLog('warn', `写入进度失败:${errorType(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function markCooldown(conversationId, seconds) {
|
||||
if (!conversationId || !(seconds > 0)) return
|
||||
cooldownUntil.set(conversationId, Date.now() + seconds * 1000)
|
||||
if (cooldownUntil.size > COOLDOWN_MAP_LIMIT) {
|
||||
const now = Date.now()
|
||||
for (const [key, until] of cooldownUntil) {
|
||||
if (until <= now) cooldownUntil.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(milliseconds) {
|
||||
return new Promise((resolve) => setTimeout(resolve, milliseconds))
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 Apple Silicon macOS 上,若宿主的默认 python3 是 x86_64(Rosetta 2),
|
||||
* 直接启动会把 P_TRANSLATED 标志遗传给子进程 Google Chrome,导致抖音页面卡在加载中。
|
||||
* 这里优先选用缓存 venv 的原生 Python,并通过 /usr/bin/arch -arm64 强制切换为原生 arm64。
|
||||
*/
|
||||
function resolvePythonInvocation(pythonPath, scriptPath, args) {
|
||||
if (process.platform !== 'darwin') {
|
||||
return { file: pythonPath, args: [scriptPath, ...args] }
|
||||
}
|
||||
let resolvedPython = pythonPath
|
||||
if (pythonPath === 'python3') {
|
||||
const venvPython = path.join(
|
||||
os.homedir(),
|
||||
'Library',
|
||||
'Caches',
|
||||
'douyin-video',
|
||||
'venv',
|
||||
'bin',
|
||||
'python'
|
||||
)
|
||||
try {
|
||||
if (fsSync.existsSync(venvPython)) resolvedPython = venvPython
|
||||
} catch {
|
||||
// 缓存 venv 不可读时退回配置里的 pythonPath。
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (fsSync.existsSync('/usr/bin/arch')) {
|
||||
return {
|
||||
file: '/usr/bin/arch',
|
||||
args: ['-arm64', resolvedPython, scriptPath, ...args]
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 非标准系统环境缺少 /usr/bin/arch 时直接调用解释器。
|
||||
}
|
||||
return { file: resolvedPython, args: [scriptPath, ...args] }
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析可用的抖音 Cookie:
|
||||
* 1. 优先使用调用方显式传入的 cookieHeader(测试发送 / 测试下载);
|
||||
* 2. 尝试向宿主读取已保存的 Cookie(若宿主暴露接口);
|
||||
* 3. 回退读取扩展私有目录或桌面上的 `douyin-cookie` 文件(供 @我自己 自动回复链路使用)。
|
||||
*/
|
||||
async function resolveCookieHeader(explicitHeader) {
|
||||
const direct = String(explicitHeader || '').trim()
|
||||
if (direct) return direct
|
||||
if (tm && tm.douyin && typeof tm.douyin.getCookie === 'function') {
|
||||
try {
|
||||
const fromHost = String((await tm.douyin.getCookie()) || '').trim()
|
||||
if (fromHost) return fromHost
|
||||
} catch {
|
||||
// 宿主未提供或读取失败时继续尝试本地文件。
|
||||
}
|
||||
}
|
||||
const candidates = [
|
||||
path.join(tm.extension.dataDir, 'douyin-cookie.txt'),
|
||||
path.join(os.homedir(), 'Desktop', 'douyin-cookie'),
|
||||
path.join(os.homedir(), 'Desktop', 'douyin-cookie.txt')
|
||||
]
|
||||
for (const file of candidates) {
|
||||
try {
|
||||
const content = String(await fs.readFile(file, 'utf8')).trim()
|
||||
if (content) return content
|
||||
} catch {
|
||||
// 文件不存在或无权限时跳过。
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function resolveScriptPath(value) {
|
||||
const expanded = expandHome(value)
|
||||
if (!expanded) return path.resolve(__dirname, '..', 'scripts', 'douyin.py')
|
||||
if (path.isAbsolute(expanded)) return expanded
|
||||
return path.resolve(__dirname, '..', expanded)
|
||||
}
|
||||
|
||||
/** 统一封装脚本调用:固定 cwd、超时、输出上限、UTF-8 与 macOS 原生 arm64 执行。 */
|
||||
async function runPython(args, timeoutMs, config) {
|
||||
// 首次启用时 dataDir 可能还没被创建;execFile 的 cwd 不存在会直接 ENOENT。
|
||||
await fs.mkdir(tm.extension.dataDir, { recursive: true })
|
||||
const pythonPath = expandHome(config.pythonPath)
|
||||
const scriptPath = resolveScriptPath(config.scriptPath)
|
||||
const invocation = resolvePythonInvocation(pythonPath, scriptPath, args)
|
||||
return execFileAsync(invocation.file, invocation.args, {
|
||||
cwd: tm.extension.dataDir,
|
||||
timeout: timeoutMs,
|
||||
maxBuffer: MAX_OUTPUT_BYTES,
|
||||
env: {
|
||||
...process.env,
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUNBUFFERED: '1',
|
||||
DOUYIN_ARM64_READY: '1'
|
||||
},
|
||||
windowsHide: true
|
||||
})
|
||||
}
|
||||
|
||||
function describeExecError(error) {
|
||||
if (!error) return '失败'
|
||||
if (error.code === 'ENOENT') return '找不到 Python 可执行文件,请检查 Python 路径'
|
||||
if (error.killed || error.signal) return '超时'
|
||||
if (typeof error.code === 'number') return `脚本退出码 ${error.code}`
|
||||
if (typeof error.code === 'string' && /^E[A-Z]+$/.test(error.code)) {
|
||||
return `失败(${error.code})`
|
||||
}
|
||||
return '失败'
|
||||
}
|
||||
|
||||
async function resolveAndDownloadVideo(url, config, options = {}) {
|
||||
const dir = downloadsDir()
|
||||
try {
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
} catch (error) {
|
||||
return parseFailure('下载目录不可用(' + errorType(error) + ')', errorType(error))
|
||||
}
|
||||
|
||||
const args = [
|
||||
url,
|
||||
'-o',
|
||||
dir,
|
||||
'--wait',
|
||||
SCRIPT_WAIT_SECONDS,
|
||||
'--download-timeout',
|
||||
'90',
|
||||
'--json',
|
||||
'--debug',
|
||||
'--video-only',
|
||||
'--download'
|
||||
]
|
||||
if (config.quality) args.push('-q', config.quality)
|
||||
if (config.showUi) args.push('--show-ui')
|
||||
const cookieHeader = await resolveCookieHeader(options.cookieHeader)
|
||||
let temporaryCookieFile = ''
|
||||
let stdout = ''
|
||||
try {
|
||||
if (cookieHeader) {
|
||||
await fs.mkdir(tm.extension.dataDir, { recursive: true })
|
||||
temporaryCookieFile = path.join(
|
||||
tm.extension.dataDir,
|
||||
`.douyin-cookie-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`
|
||||
)
|
||||
await fs.writeFile(temporaryCookieFile, cookieHeader, { mode: 0o600, flag: 'wx' })
|
||||
await fs.chmod(temporaryCookieFile, 0o600)
|
||||
args.push('--cookie-file', temporaryCookieFile)
|
||||
}
|
||||
|
||||
const result = await runPython(args, DOWNLOAD_AND_RESOLVE_TIMEOUT_MS, config)
|
||||
stdout = String(result.stdout || '')
|
||||
} catch (error) {
|
||||
stdout = String((error && error.stdout) || '')
|
||||
if (!stdout.trim()) {
|
||||
return parseFailure(
|
||||
temporaryCookieFile ? 'Cookie 文件不可用或解析超时' : describeExecError(error),
|
||||
temporaryCookieFile ? 'COOKIE_OR_TIMEOUT' : errorType(error)
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
if (temporaryCookieFile) {
|
||||
try {
|
||||
await fs.unlink(temporaryCookieFile)
|
||||
} catch {
|
||||
// 解析结束后清除临时凭证文件。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = parseDownloadedResult(stdout)
|
||||
if (!parsed) {
|
||||
const failure = /✗\s*(?:失败[::])?\s*(.+)/.exec(stdout)
|
||||
return parseFailure(failure ? failure[1] : '脚本输出无法识别', 'INVALID_OUTPUT')
|
||||
}
|
||||
if (!parsed.ok) return parseFailure(parsed.message, parsed.errorType)
|
||||
|
||||
let stat = null
|
||||
try {
|
||||
stat = await fs.stat(parsed.path)
|
||||
} catch {
|
||||
return parseFailure('下载文件不存在', 'MISSING_FILE')
|
||||
}
|
||||
if (!stat.isFile()) return parseFailure('下载结果不是文件', 'NOT_A_FILE')
|
||||
if (isFileTooLarge(stat.size, config.maxFileMB)) {
|
||||
return { ok: false, message: tooLargeMessage(stat.size), errorType: 'TOO_LARGE' }
|
||||
}
|
||||
return { ok: true, path: parsed.path, size: stat.size, meta: parsed.meta }
|
||||
}
|
||||
|
||||
let lastSendAt = 0
|
||||
|
||||
async function waitSendSlot() {
|
||||
const elapsed = Date.now() - lastSendAt
|
||||
if (lastSendAt > 0 && elapsed < SEND_GAP_MS) {
|
||||
await sleep(SEND_GAP_MS - elapsed)
|
||||
}
|
||||
lastSendAt = Date.now()
|
||||
}
|
||||
|
||||
async function sendText(to, text, dedupeKey, stage) {
|
||||
try {
|
||||
await waitSendSlot()
|
||||
await tm.wechat.send({ to, text, dedupeKey })
|
||||
lastSendAt = Date.now()
|
||||
return true
|
||||
} catch (error) {
|
||||
safeLog('warn', `未完成:阶段=${stage || 'text'} 错误=${errorType(error)}`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 发视频:走宿主 video 通道,`dedupeKey` 保证同一条消息只发一次。 */
|
||||
async function sendVideo(event, filePath) {
|
||||
try {
|
||||
await waitSendSlot()
|
||||
await tm.wechat.send({
|
||||
type: 'video',
|
||||
to: event.conversationId,
|
||||
path: filePath,
|
||||
dedupeKey: `${event.eventId}:video`
|
||||
})
|
||||
lastSendAt = Date.now()
|
||||
return true
|
||||
} catch (error) {
|
||||
safeLog('warn', `未完成:阶段=send 错误=${errorType(error)}`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function reportFailure(event, config, message) {
|
||||
if (!config.errorReply) return
|
||||
await sendText(event.conversationId, message, `${event.eventId}:error`, 'reply')
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次完整任务。
|
||||
*
|
||||
* `stage` 记录失败发生的位置:`resolveDownload` / `send` / `done`。
|
||||
* 进度快照与统计都会落盘;失败原因只保留错误类型,不写 URL / 路径 / 标题。
|
||||
*/
|
||||
async function processLink(event, config, url, options = {}) {
|
||||
const jobId = event.eventId
|
||||
let awemeId = ''
|
||||
let stage = 'accepted'
|
||||
let ok = false
|
||||
let failureCode = ''
|
||||
let failureMessage = ''
|
||||
|
||||
try {
|
||||
stage = 'resolveDownload'
|
||||
await setProgress({ jobId, awemeId, stage, status: 'running' })
|
||||
const downloaded = await resolveAndDownloadVideo(url, config, options)
|
||||
if (!downloaded.ok) {
|
||||
failureCode = downloaded.errorType || 'DOWNLOAD_FAILED'
|
||||
failureMessage = downloaded.message
|
||||
return
|
||||
}
|
||||
const meta = downloaded.meta
|
||||
awemeId = String(meta.aweme_id || '')
|
||||
|
||||
stage = 'send'
|
||||
await setProgress({ jobId, awemeId, stage, status: 'running' })
|
||||
const sent = await sendVideo(event, downloaded.path)
|
||||
if (!sent) {
|
||||
failureCode = 'SEND_FAILED'
|
||||
failureMessage = '视频发送失败'
|
||||
return
|
||||
}
|
||||
|
||||
ok = true
|
||||
stage = 'done'
|
||||
// 冷却只在视频真正发出去之后才写入,失败不占用下一次机会。
|
||||
markCooldown(event.conversationId, config.cooldownSeconds)
|
||||
} catch (error) {
|
||||
failureCode = errorType(error)
|
||||
failureMessage = '处理异常'
|
||||
safeLog('warn', `处理异常:阶段=${stage} 错误=${failureCode}`)
|
||||
} finally {
|
||||
if (ok) {
|
||||
await setProgress({ jobId, awemeId, stage: 'done', status: 'done', errorType: '' })
|
||||
} else {
|
||||
if (failureMessage && options.replyOnFailure !== false) {
|
||||
await reportFailure(event, config, failureMessage)
|
||||
}
|
||||
await setProgress({
|
||||
jobId,
|
||||
awemeId,
|
||||
stage: stage === 'accepted' ? 'resolve' : stage,
|
||||
status: 'failed',
|
||||
errorType: failureCode || 'FAILED',
|
||||
errorMessage: failureMessage ? shortReason(failureMessage) : ''
|
||||
})
|
||||
safeLog('warn', `未完成:阶段=${stage} 错误=${failureCode || 'FAILED'}`)
|
||||
}
|
||||
await recordJob({
|
||||
awemeId,
|
||||
ok,
|
||||
stage: ok ? 'done' : stage,
|
||||
errorType: ok ? '' : failureCode || 'FAILED'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function handleEvent(event) {
|
||||
try {
|
||||
const config = await loadConfig()
|
||||
const decision = shouldHandle(event, config, cooldownUntil, Date.now())
|
||||
if (!decision.handle) return
|
||||
|
||||
const conversationId = event.conversationId
|
||||
const jobKey = `${conversationId}|${decision.url}`
|
||||
if (activeConversations.has(conversationId) || activeJobs.has(jobKey)) return
|
||||
|
||||
activeConversations.add(conversationId)
|
||||
activeJobs.add(jobKey)
|
||||
try {
|
||||
await setProgress({
|
||||
jobId: event.eventId,
|
||||
stage: 'accepted',
|
||||
status: 'running',
|
||||
startedAt: Date.now(),
|
||||
awemeId: '',
|
||||
errorType: '',
|
||||
errorMessage: ''
|
||||
})
|
||||
// 先回执再干活:解析/下载要十几秒,用户不该靠猜。
|
||||
if (config.ackText) {
|
||||
await sendText(conversationId, config.ackText, `${event.eventId}:ack`, 'ack')
|
||||
}
|
||||
await processLink(event, config, decision.url)
|
||||
} finally {
|
||||
activeConversations.delete(conversationId)
|
||||
activeJobs.delete(jobKey)
|
||||
}
|
||||
} catch (error) {
|
||||
safeLog('warn', `事件处理失败:${errorType(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
let lastTestRequestId = ''
|
||||
let testInFlight = false
|
||||
let pendingTestRequest = null
|
||||
|
||||
async function writeTestResult(result) {
|
||||
try {
|
||||
await tm.storage.set(TEST_RESULT_KEY, result)
|
||||
} catch (error) {
|
||||
safeLog('warn', `写入测试结果失败:${errorType(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置页「测试发送」。
|
||||
*
|
||||
* 测试请求通过宿主一次性送达,不落入扩展持久化存储。
|
||||
*/
|
||||
async function pollTestRequest() {
|
||||
if (testInFlight) return
|
||||
const request = pendingTestRequest
|
||||
pendingTestRequest = null
|
||||
if (!request || typeof request !== 'object') return
|
||||
const id = String(request.id || '').trim()
|
||||
if (!id || id === lastTestRequestId) return
|
||||
lastTestRequestId = id
|
||||
const to = String(request.to || '').trim()
|
||||
const text = String(request.text || '').trim()
|
||||
|
||||
if (!to || !text) {
|
||||
await writeTestResult({
|
||||
id,
|
||||
status: 'failed',
|
||||
message: '测试请求缺少群聊或链接',
|
||||
at: Date.now()
|
||||
})
|
||||
return
|
||||
}
|
||||
if (activeConversations.has(to)) {
|
||||
await writeTestResult({
|
||||
id,
|
||||
status: 'failed',
|
||||
message: '该群正在执行其他任务,请稍后重试',
|
||||
at: Date.now()
|
||||
})
|
||||
return
|
||||
}
|
||||
const url = extractDouyinUrl(text)
|
||||
if (!url) {
|
||||
await writeTestResult({ id, status: 'failed', message: '没有识别到抖音链接', at: Date.now() })
|
||||
return
|
||||
}
|
||||
|
||||
const config = await loadConfig()
|
||||
const cookieHeader = request.cookieHeader ? String(request.cookieHeader) : ''
|
||||
testInFlight = true
|
||||
activeConversations.add(to)
|
||||
try {
|
||||
await writeTestResult({ id, status: 'running', message: '已开始解析…', at: Date.now() })
|
||||
await setProgress({
|
||||
jobId: `test:${id}`,
|
||||
stage: 'accepted',
|
||||
status: 'running',
|
||||
startedAt: Date.now(),
|
||||
awemeId: '',
|
||||
errorType: '',
|
||||
errorMessage: ''
|
||||
})
|
||||
// 测试路径不发回执:结果直接显示在配置页,视频发到目标群。
|
||||
await processLink(
|
||||
{
|
||||
eventId: `test:${id}`,
|
||||
conversationId: to,
|
||||
isGroup: to.endsWith('@chatroom'),
|
||||
isSelf: false,
|
||||
type: 'text',
|
||||
text,
|
||||
mentionsMe: true
|
||||
},
|
||||
config,
|
||||
url,
|
||||
{ replyOnFailure: false, cookieHeader }
|
||||
)
|
||||
const progress = cachedProgress || {}
|
||||
if (progress.status === 'done') {
|
||||
await writeTestResult({
|
||||
id,
|
||||
status: 'done',
|
||||
message: '测试发送完成:视频已发到该群',
|
||||
at: Date.now()
|
||||
})
|
||||
} else {
|
||||
const label = STAGE_LABELS[progress.stage] || progress.stage || '未知阶段'
|
||||
await writeTestResult({
|
||||
id,
|
||||
status: 'failed',
|
||||
message: `测试发送失败:${label}${progress.errorType ? `(${progress.errorType})` : ''}${progress.errorMessage ? `:${progress.errorMessage}` : ''}`,
|
||||
at: Date.now()
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
await writeTestResult({
|
||||
id,
|
||||
status: 'failed',
|
||||
message: `测试发送异常:${errorType(error)}`,
|
||||
at: Date.now()
|
||||
})
|
||||
} finally {
|
||||
activeConversations.delete(to)
|
||||
testInFlight = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理下载目录:只保留最近 20 个文件,并删除 7 天前的文件。
|
||||
*
|
||||
* 清理失败不影响发送能力,逐条 try/catch,最坏情况是目录继续变大。
|
||||
*/
|
||||
async function cleanupDownloads() {
|
||||
const dir = downloadsDir()
|
||||
let entries = []
|
||||
try {
|
||||
entries = await fs.readdir(dir, { withFileTypes: true })
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
const files = []
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile()) continue
|
||||
const full = path.join(dir, entry.name)
|
||||
try {
|
||||
const stat = await fs.stat(full)
|
||||
files.push({ full, mtime: stat.mtimeMs })
|
||||
} catch {
|
||||
// 枚举期间被删除或无法访问,跳过即可。
|
||||
}
|
||||
}
|
||||
|
||||
files.sort((left, right) => right.mtime - left.mtime)
|
||||
const now = Date.now()
|
||||
for (let index = 0; index < files.length; index += 1) {
|
||||
const fresh = now - files[index].mtime <= MAX_FILE_AGE_MS
|
||||
if (index < KEEP_RECENT_FILES && fresh) continue
|
||||
try {
|
||||
await fs.unlink(files[index].full)
|
||||
} catch {
|
||||
// 单个文件删不掉就留着,下一次启动再试。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = function activate(api) {
|
||||
tm = api
|
||||
// 宿主对 handler 有 10 秒超时;脚本可能要跑几分钟,所以这里只排队不等待。
|
||||
tm.events.on('message.received', (event) => {
|
||||
void handleEvent(event)
|
||||
})
|
||||
void cleanupDownloads()
|
||||
globalThis.__tmTestSend = async (request) => {
|
||||
pendingTestRequest = request
|
||||
await pollTestRequest()
|
||||
return { accepted: true }
|
||||
}
|
||||
tm.log.info('抖音搬运已加载')
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* 抖音分享链接解析的纯函数层。
|
||||
*
|
||||
* 这一层不碰文件系统、不启子进程、不读时钟:所有输入都从参数进来,
|
||||
* 所有输出都可序列化,便于在 `node:test` 里离线断言。
|
||||
*
|
||||
* 单位约定:
|
||||
* - 时间一律 epoch 毫秒;
|
||||
* - 文件大小一律字节,配置里的上限单位是 MB(1 MB = 1024 * 1024 B)。
|
||||
*/
|
||||
|
||||
/** 宿主发送通道的硬上限:单个媒体文件 100 MB,配置不允许突破。 */
|
||||
const HOST_MAX_FILE_MB = 100
|
||||
|
||||
/** 解析脚本的默认位置(相对于扩展目录,支持自定义绝对路径或 `~/`)。 */
|
||||
const DEFAULT_SCRIPT_PATH = 'scripts/douyin.py'
|
||||
|
||||
/** 画质白名单;空串表示「最高」,不传 `-q` 给脚本。 */
|
||||
const QUALITY_VALUES = ['', '1080', '720', '540']
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
configVersion: 1,
|
||||
enabled: false,
|
||||
pythonPath: 'python3',
|
||||
scriptPath: DEFAULT_SCRIPT_PATH,
|
||||
quality: '720',
|
||||
/** 排障开关:显示浏览器窗口以观察实际页面状态。 */
|
||||
showUi: false,
|
||||
/** 命中后先回一句,避免用户不知道是否收到;空串表示不回复。 */
|
||||
ackText: '收到,正在解析,请稍候…',
|
||||
sendCaption: false,
|
||||
captionTemplate: '{author}:{title}',
|
||||
errorReply: true,
|
||||
includeDirect: false,
|
||||
groups: [],
|
||||
cooldownSeconds: 60,
|
||||
maxFileMB: HOST_MAX_FILE_MB
|
||||
}
|
||||
|
||||
/** 分享链接只认这三种形态;短链的 id 是字母数字,长链只认数字作品 id。 */
|
||||
const DOUYIN_URL_PATTERN =
|
||||
/https?:\/\/(?:v\.douyin\.com\/[A-Za-z0-9_-]{1,64}|(?:www\.)?douyin\.com\/(?:video|note)\/\d{1,32})/i
|
||||
|
||||
/** 中文文案里链接后面常跟这些符号,属于分隔符不属于链接。 */
|
||||
const TRAILING_PUNCTUATION = /[)\]}>,.;:!?'"`。,、;:!?…)】》〉」』”’]+$/
|
||||
|
||||
const CAPTION_MAX_LENGTH = 200
|
||||
const GROUP_MAX_COUNT = 200
|
||||
|
||||
function clampInt(value, min, max, fallback) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return fallback
|
||||
const rounded = Math.trunc(numeric)
|
||||
if (rounded < min) return min
|
||||
if (rounded > max) return max
|
||||
return rounded
|
||||
}
|
||||
|
||||
function normalizeQuality(value) {
|
||||
if (value === null || value === undefined) return DEFAULT_CONFIG.quality
|
||||
const text = String(value).trim()
|
||||
// 数值型画质(720)与字符串画质('720')同义;`''` 表示最高。
|
||||
if (text === '') return ''
|
||||
return QUALITY_VALUES.includes(text) ? text : DEFAULT_CONFIG.quality
|
||||
}
|
||||
|
||||
function normalizeGroups(value) {
|
||||
const list = Array.isArray(value) ? value : typeof value === 'string' ? value.split(/[\s,]+/) : []
|
||||
const result = []
|
||||
for (const item of list) {
|
||||
const id = String(item === null || item === undefined ? '' : item).trim()
|
||||
if (!id) continue
|
||||
if (result.includes(id)) continue
|
||||
result.push(id.slice(0, 128))
|
||||
if (result.length >= GROUP_MAX_COUNT) break
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function normalizeText(value, fallback, maxLength) {
|
||||
const text = typeof value === 'string' ? value.trim() : ''
|
||||
return (text || fallback).slice(0, maxLength)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把任意来源(存储、表单、旧版本)的配置收敛成可执行形态。
|
||||
*
|
||||
* 契约:**永不抛错**,字段缺失或非法时回落到默认值;返回对象永远是全新的,
|
||||
* 调用方可以直接持有并修改,不会污染 `DEFAULT_CONFIG`。
|
||||
*/
|
||||
function normalizeConfig(raw) {
|
||||
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
||||
return {
|
||||
configVersion: 1,
|
||||
enabled: input.enabled === true,
|
||||
pythonPath: normalizeText(input.pythonPath, DEFAULT_CONFIG.pythonPath, 512),
|
||||
scriptPath: normalizeText(input.scriptPath, DEFAULT_SCRIPT_PATH, 512),
|
||||
quality: normalizeQuality(input.quality),
|
||||
showUi: input.showUi === true,
|
||||
ackText:
|
||||
input.ackText === undefined
|
||||
? DEFAULT_CONFIG.ackText
|
||||
: String(input.ackText).trim().slice(0, 200),
|
||||
sendCaption: input.sendCaption === true,
|
||||
captionTemplate: normalizeText(input.captionTemplate, DEFAULT_CONFIG.captionTemplate, 200),
|
||||
errorReply: input.errorReply !== false,
|
||||
includeDirect: input.includeDirect === true,
|
||||
groups: normalizeGroups(input.groups),
|
||||
cooldownSeconds: clampInt(input.cooldownSeconds, 0, 3600, DEFAULT_CONFIG.cooldownSeconds),
|
||||
maxFileMB: clampInt(input.maxFileMB, 1, HOST_MAX_FILE_MB, DEFAULT_CONFIG.maxFileMB)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从一段文本里取第一个抖音分享链接。
|
||||
*
|
||||
* 输入可能是裸链接,也可能是「复制打开抖音…」整段文案;返回值已去掉尾随标点,
|
||||
* 查询串与 fragment 一并丢弃(短链换长链由脚本完成,扩展不参与)。
|
||||
*
|
||||
* 返回 `null` 表示没有可识别的抖音作品链接;`javascript:` / `ftp:` / 非抖音域名
|
||||
* 一律不匹配。
|
||||
*/
|
||||
function extractDouyinUrl(text) {
|
||||
const source = typeof text === 'string' ? text : ''
|
||||
if (!source) return null
|
||||
const matched = DOUYIN_URL_PATTERN.exec(source)
|
||||
if (!matched) return null
|
||||
const cleaned = matched[0].replace(TRAILING_PUNCTUATION, '')
|
||||
return cleaned || null
|
||||
}
|
||||
|
||||
/** 从 `start` 处的 `[` 找到配对的 `]`,跳过字符串字面量与转义;失败返回 -1。 */
|
||||
function findArrayEnd(text, start) {
|
||||
let depth = 0
|
||||
let inString = false
|
||||
let escaped = false
|
||||
for (let index = start; index < text.length; index += 1) {
|
||||
const char = text[index]
|
||||
if (inString) {
|
||||
if (escaped) escaped = false
|
||||
else if (char === '\\') escaped = true
|
||||
else if (char === '"') inString = false
|
||||
continue
|
||||
}
|
||||
if (char === '"') {
|
||||
inString = true
|
||||
continue
|
||||
}
|
||||
if (char === '[') {
|
||||
depth += 1
|
||||
continue
|
||||
}
|
||||
if (char === ']') {
|
||||
depth -= 1
|
||||
if (depth === 0) return index
|
||||
if (depth < 0) return -1
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
function isResolveResultList(value) {
|
||||
if (!Array.isArray(value) || value.length === 0) return false
|
||||
return value.every(
|
||||
(item) =>
|
||||
item &&
|
||||
typeof item === 'object' &&
|
||||
typeof item.url === 'string' &&
|
||||
typeof item.ok === 'boolean'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 stdout 中取第一个结构合法的结果数组。
|
||||
*
|
||||
* 按结构判定(非空数组、每项含 `url:string` 与 `ok:boolean`),跳过进度行里的
|
||||
* `[1]` 与嵌套的 `quality_options`;空数组与非法 JSON 返回 `null`。
|
||||
*/
|
||||
function parseResolveJson(stdout) {
|
||||
const text = typeof stdout === 'string' ? stdout : ''
|
||||
if (!text) return null
|
||||
for (let start = 0; start < text.length; start += 1) {
|
||||
if (text[start] !== '[') continue
|
||||
const end = findArrayEnd(text, start)
|
||||
if (end < 0) continue
|
||||
try {
|
||||
const value = JSON.parse(text.slice(start, end + 1))
|
||||
if (isResolveResultList(value)) return value
|
||||
} catch {
|
||||
// 这个 `[` 不是数组起点(可能在字符串里),继续向后找。
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 从下载输出里取最后一个 `✅` 后面的绝对路径。
|
||||
*
|
||||
* 脚本对视频打印 ` ✅ /abs/xxx.mp4`,对图集打印目录后面再跟一段「(N 个文件)」。
|
||||
* 路径里可能含空格(作者名与标题),所以只按行首标记切分,不按空白切分。
|
||||
*
|
||||
* 返回 `null` 表示没有可用的绝对路径。
|
||||
*/
|
||||
function parseSavedPath(stdout) {
|
||||
const text = typeof stdout === 'string' ? stdout : ''
|
||||
if (!text) return null
|
||||
const lines = text.split(/\r?\n/)
|
||||
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
||||
const marker = lines[index].indexOf('✅')
|
||||
if (marker < 0) continue
|
||||
let rest = lines[index].slice(marker + 1).trim()
|
||||
// 去掉尾部的「(N 个文件)」之类附注,它不属于路径。
|
||||
rest = rest.replace(/\s*[((][^(())]*[))]\s*$/, '').trim()
|
||||
if (!rest) continue
|
||||
if (rest[0] !== '/') continue
|
||||
return rest
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function parseDownloadedResult(stdout) {
|
||||
const results = parseResolveJson(stdout)
|
||||
const video = pickVideoResult(results)
|
||||
if (video) {
|
||||
const saved = Array.isArray(video.saved)
|
||||
? video.saved.find((value) => typeof value === 'string' && value.startsWith('/'))
|
||||
: null
|
||||
if (saved) return { ok: true, meta: video, path: saved }
|
||||
if (video.error) return { ok: false, message: video.error, errorType: 'DOWNLOAD_FAILED' }
|
||||
return null
|
||||
}
|
||||
|
||||
const image = results && results.find((item) => item && item.ok === true && item.type === 'image')
|
||||
if (image) return { ok: false, message: '暂不支持图集', errorType: 'IMAGE_SET' }
|
||||
|
||||
const failure = results && results.find((item) => item && item.ok === false)
|
||||
if (failure && failure.error) {
|
||||
return {
|
||||
ok: false,
|
||||
message: failure.error,
|
||||
errorType: failure.aweme_id ? 'DOWNLOAD_FAILED' : 'RESOLVE_FAILED'
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 按模板渲染文案。
|
||||
*
|
||||
* 已知变量 `{author}` / `{title}` / `{awemeId}` 会被替换;未知变量原样保留,
|
||||
* 让用户能看见自己写错了什么。结果 trim 后截断到 200 字。
|
||||
*/
|
||||
function renderCaption(template, meta) {
|
||||
const source = typeof template === 'string' ? template : ''
|
||||
const data = meta && typeof meta === 'object' ? meta : {}
|
||||
const values = {
|
||||
author: data.author === null || data.author === undefined ? '' : String(data.author),
|
||||
title: data.title === null || data.title === undefined ? '' : String(data.title),
|
||||
awemeId: data.awemeId === null || data.awemeId === undefined ? '' : String(data.awemeId)
|
||||
}
|
||||
// 已知变量即使取不到值也替换成空串:正文里留下 `{author}` 会被当成程序缺陷。
|
||||
const rendered = source.replace(/\{(author|title|awemeId)\}/g, (whole, name) => values[name])
|
||||
return rendered.trim().slice(0, CAPTION_MAX_LENGTH)
|
||||
}
|
||||
|
||||
function inScope(event, config) {
|
||||
if (event.isGroup) {
|
||||
return config.groups.length === 0 || config.groups.includes(event.conversationId)
|
||||
}
|
||||
return config.includeDirect === true
|
||||
}
|
||||
|
||||
function readCooldown(cooldownUntil, conversationId) {
|
||||
if (!cooldownUntil || !conversationId) return 0
|
||||
const value =
|
||||
typeof cooldownUntil.get === 'function'
|
||||
? cooldownUntil.get(conversationId)
|
||||
: cooldownUntil[conversationId]
|
||||
const numeric = Number(value)
|
||||
return Number.isFinite(numeric) && numeric > 0 ? numeric : 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一条事件是否该进入处理流程。
|
||||
*
|
||||
* 判定顺序固定:总开关 → 自己发的 → 非 text → 未 @我 → 提取链接 → 会话范围 → 冷却。
|
||||
* `reason` 的取值集合固定为
|
||||
* `disabled | self | type | mention | no_link | scope | cooldown | ok`。
|
||||
*
|
||||
* `url` 只要提取成功就会返回,即使后续被范围或冷却拦下,便于调用方写日志。
|
||||
*/
|
||||
function shouldHandle(event, config, cooldownUntil, now) {
|
||||
const settings = normalizeConfig(config)
|
||||
if (!settings.enabled) return { handle: false, url: null, reason: 'disabled' }
|
||||
if (!event || typeof event !== 'object') return { handle: false, url: null, reason: 'no_link' }
|
||||
if (event.isSelf) return { handle: false, url: null, reason: 'self' }
|
||||
if (event.type !== 'text') return { handle: false, url: null, reason: 'type' }
|
||||
if (!event.mentionsMe) return { handle: false, url: null, reason: 'mention' }
|
||||
|
||||
const url = extractDouyinUrl(event.text)
|
||||
if (!url) return { handle: false, url: null, reason: 'no_link' }
|
||||
if (!inScope(event, settings)) return { handle: false, url, reason: 'scope' }
|
||||
|
||||
const until = readCooldown(cooldownUntil, event.conversationId)
|
||||
const timestamp = Number.isFinite(Number(now)) ? Number(now) : Date.now()
|
||||
if (timestamp < until) return { handle: false, url, reason: 'cooldown' }
|
||||
|
||||
return { handle: true, url, reason: 'ok' }
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件是否不该发送。
|
||||
*
|
||||
* 返回 true 的三种情况:超过配置上限、字节数非法、文件为空。
|
||||
* 上限本身被收敛到 1–100 MB,宿主 100 MB 的硬限制不会被配置绕过。
|
||||
*/
|
||||
function isFileTooLarge(sizeBytes, maxFileMB) {
|
||||
const limitMB = clampInt(maxFileMB, 1, HOST_MAX_FILE_MB, DEFAULT_CONFIG.maxFileMB)
|
||||
const size = Number(sizeBytes)
|
||||
if (!Number.isFinite(size) || size <= 0) return true
|
||||
return size > limitMB * 1024 * 1024
|
||||
}
|
||||
|
||||
/**
|
||||
* 从解析结果里挑第一条可下载的视频。
|
||||
*
|
||||
* 图集(`type === 'image'`)与失败项都不算;没有视频时返回 `null`,
|
||||
* 由调用方决定回复「暂不支持图集」还是通用失败文案。
|
||||
*/
|
||||
function pickVideoResult(results) {
|
||||
if (!Array.isArray(results)) return null
|
||||
for (const item of results) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
if (item.ok !== true) continue
|
||||
if (item.type !== 'video') continue
|
||||
return item
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_CONFIG,
|
||||
normalizeConfig,
|
||||
extractDouyinUrl,
|
||||
parseResolveJson,
|
||||
parseSavedPath,
|
||||
parseDownloadedResult,
|
||||
renderCaption,
|
||||
shouldHandle,
|
||||
isFileTooLarge,
|
||||
pickVideoResult
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.douyin-sender",
|
||||
"name": "抖音视频搬运",
|
||||
"version": "1.0.3",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.6.0",
|
||||
"description": "被 @ 且消息里带抖音分享链接时,解析视频并发送回原会话。",
|
||||
"author": "TraceMemo Examples",
|
||||
"permissions": [
|
||||
"messages.subscribe",
|
||||
"contacts.list",
|
||||
"wechat.send.video",
|
||||
"wechat.send.text",
|
||||
"storage"
|
||||
],
|
||||
"entrypoints": {
|
||||
"page": "ui/index.html",
|
||||
"background": "background/index.js"
|
||||
},
|
||||
"subscriptions": {
|
||||
"messageTypes": ["text"],
|
||||
"conversationIds": [],
|
||||
"requireMentionMe": true,
|
||||
"includeSelf": false
|
||||
},
|
||||
"contributions": {
|
||||
"pages": [
|
||||
{
|
||||
"id": "settings",
|
||||
"title": "抖音解析设置"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* 纯函数层测试:不联网、不启动 python、不读真实文件。
|
||||
* 运行:node --test examples/extensions/douyin-sender/tests/douyin.test.mjs
|
||||
*/
|
||||
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import douyin from '../lib/douyin.js'
|
||||
|
||||
const {
|
||||
DEFAULT_CONFIG,
|
||||
normalizeConfig,
|
||||
extractDouyinUrl,
|
||||
parseResolveJson,
|
||||
parseSavedPath,
|
||||
parseDownloadedResult,
|
||||
renderCaption,
|
||||
shouldHandle,
|
||||
isFileTooLarge,
|
||||
pickVideoResult
|
||||
} = douyin
|
||||
|
||||
const SHORT_URL = 'https://v.douyin.com/fixture123'
|
||||
const SHORT_TEXT_URL = 'https://v.douyin.com/fixture123/'
|
||||
const VIDEO_URL = 'https://www.douyin.com/video/7300000000000000001'
|
||||
const NOTE_URL = 'https://douyin.com/note/7300000000000000002'
|
||||
|
||||
function makeEvent(overrides = {}) {
|
||||
return {
|
||||
eventId: 'message:fixture-1',
|
||||
accountId: 'wxid_fixture',
|
||||
conversationId: 'fixture-room@chatroom',
|
||||
messageId: 'local-1',
|
||||
senderId: 'wxid_fixture',
|
||||
senderName: '张三',
|
||||
isGroup: true,
|
||||
isSelf: false,
|
||||
type: 'text',
|
||||
text: `@李四 ${SHORT_TEXT_URL}`,
|
||||
mentionsMe: true,
|
||||
timestamp: 0,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function makeConfig(overrides = {}) {
|
||||
return normalizeConfig({ enabled: true, ...overrides })
|
||||
}
|
||||
|
||||
test('从裸短链里提取链接', () => {
|
||||
assert.equal(extractDouyinUrl(SHORT_TEXT_URL), SHORT_URL)
|
||||
})
|
||||
|
||||
test('从长链 video 里提取链接', () => {
|
||||
assert.equal(extractDouyinUrl(VIDEO_URL), VIDEO_URL)
|
||||
})
|
||||
|
||||
test('从 note 链接里提取链接', () => {
|
||||
assert.equal(extractDouyinUrl(NOTE_URL), NOTE_URL)
|
||||
})
|
||||
|
||||
test('从整段分享文案里提取链接', () => {
|
||||
const text =
|
||||
'7.89 复制打开抖音,看看【张三的作品】很有意思 https://v.douyin.com/fixture123/ 01/02 abc:/'
|
||||
assert.equal(extractDouyinUrl(text), SHORT_URL)
|
||||
})
|
||||
|
||||
test('去掉链接尾随的中文标点', () => {
|
||||
assert.equal(extractDouyinUrl('看这个 https://v.douyin.com/fixture123/。'), SHORT_URL)
|
||||
})
|
||||
|
||||
test('拒绝非抖音域名', () => {
|
||||
assert.equal(extractDouyinUrl('https://example.com/video/7300000000000000001'), null)
|
||||
assert.equal(extractDouyinUrl('https://douyin.com.evil.test/video/1'), null)
|
||||
assert.equal(extractDouyinUrl('https://foo.douyin.com/video/1'), null)
|
||||
})
|
||||
|
||||
test('拒绝 javascript: 与 ftp:', () => {
|
||||
assert.equal(extractDouyinUrl('javascript://v.douyin.com/fixture123/'), null)
|
||||
assert.equal(extractDouyinUrl('ftp://v.douyin.com/fixture123/'), null)
|
||||
})
|
||||
|
||||
test('没有链接时返回 null', () => {
|
||||
assert.equal(extractDouyinUrl('今天天气不错'), null)
|
||||
assert.equal(extractDouyinUrl(''), null)
|
||||
assert.equal(extractDouyinUrl(undefined), null)
|
||||
})
|
||||
|
||||
test('JSON 前后有噪声也能解析出数组', () => {
|
||||
const stdout = [
|
||||
'共 1 个链接',
|
||||
'▶ https://v.douyin.com/fixture123/',
|
||||
' ✓ 解析成功:video | 张三 | 标题',
|
||||
'',
|
||||
'[{"url":"https://v.douyin.com/fixture123/","ok":true,"type":"video","aweme_id":"730"}]',
|
||||
'',
|
||||
'完成:1/1 成功'
|
||||
].join('\n')
|
||||
const parsed = parseResolveJson(stdout)
|
||||
assert.ok(Array.isArray(parsed))
|
||||
assert.equal(parsed.length, 1)
|
||||
assert.equal(parsed[0].aweme_id, '730')
|
||||
})
|
||||
|
||||
test('缩进的多行 JSON 数组按真实输出解析', () => {
|
||||
const stdout = [
|
||||
' ✓ 解析成功:video | 张三 | 标题',
|
||||
'==================================================',
|
||||
'完成:1/1 成功',
|
||||
'[',
|
||||
' {',
|
||||
' "url": "https://v.douyin.com/fixture123/",',
|
||||
' "ok": true,',
|
||||
' "type": "video",',
|
||||
' "quality_options": [',
|
||||
' {"gear": "720p", "rank": 720}',
|
||||
' ]',
|
||||
' }',
|
||||
']'
|
||||
].join('\n')
|
||||
const parsed = parseResolveJson(stdout)
|
||||
assert.ok(Array.isArray(parsed))
|
||||
assert.equal(parsed[0].quality_options[0].rank, 720)
|
||||
})
|
||||
|
||||
test('非法 JSON 返回 null', () => {
|
||||
assert.equal(parseResolveJson('不是 JSON'), null)
|
||||
assert.equal(parseResolveJson('[{"ok":true,'), null)
|
||||
assert.equal(parseResolveJson(''), null)
|
||||
})
|
||||
|
||||
test('进度行里的方括号不会被误认为结果数组', () => {
|
||||
const stdout = [
|
||||
' [1] 跳过(无地址)',
|
||||
' ✅ /tmp/fixture-folder (2 个文件)',
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"image","aweme_id":"730"}]'
|
||||
].join('\n')
|
||||
const parsed = parseResolveJson(stdout)
|
||||
assert.ok(Array.isArray(parsed))
|
||||
assert.equal(parsed.length, 1)
|
||||
assert.equal(parsed[0].type, 'image')
|
||||
})
|
||||
|
||||
test('空数组视为无效结果', () => {
|
||||
assert.equal(parseResolveJson('[]'), null)
|
||||
})
|
||||
|
||||
test('合法 JSON 但不是数组时返回 null', () => {
|
||||
assert.equal(parseResolveJson('{"ok":true}'), null)
|
||||
})
|
||||
|
||||
test('下载输出里能取到绝对路径', () => {
|
||||
const stdout = [
|
||||
' ✓ 解析成功:video | 张三 | 标题',
|
||||
' 下载中 → 张三 - 标题 - 730.mp4',
|
||||
' ✅ /tmp/fixture/downloads/张三 - 标题 - 730.mp4',
|
||||
' 5.2MB | MP4'
|
||||
].join('\n')
|
||||
assert.equal(parseSavedPath(stdout), '/tmp/fixture/downloads/张三 - 标题 - 730.mp4')
|
||||
})
|
||||
|
||||
test('多条 ✅ 时取最后一个', () => {
|
||||
const stdout = [' ✅ /tmp/one.mp4', ' ✅ /tmp/two.mp4', ' 1.0MB | MP4'].join('\n')
|
||||
assert.equal(parseSavedPath(stdout), '/tmp/two.mp4')
|
||||
})
|
||||
|
||||
test('从 JSON 下载结果同时提取作品元数据和保存路径', () => {
|
||||
const parsed = parseDownloadedResult(
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"video","aweme_id":"730","saved":["/tmp/fixture-video.mp4"]}]'
|
||||
)
|
||||
assert.deepEqual(parsed, {
|
||||
ok: true,
|
||||
meta: {
|
||||
url: 'https://v.douyin.com/fixture123',
|
||||
ok: true,
|
||||
type: 'video',
|
||||
aweme_id: '730',
|
||||
saved: ['/tmp/fixture-video.mp4']
|
||||
},
|
||||
path: '/tmp/fixture-video.mp4'
|
||||
})
|
||||
assert.equal(
|
||||
parseDownloadedResult(
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"video","saved":["relative.mp4"]}]'
|
||||
),
|
||||
null
|
||||
)
|
||||
})
|
||||
|
||||
test('JSON 下载失败保留脚本错误,图集保持不支持状态', () => {
|
||||
assert.deepEqual(
|
||||
parseDownloadedResult(
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":false,"error":"fixture platform error"}]'
|
||||
),
|
||||
{ ok: false, message: 'fixture platform error', errorType: 'RESOLVE_FAILED' }
|
||||
)
|
||||
assert.deepEqual(
|
||||
parseDownloadedResult(
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":true,"type":"image","images":[]}]'
|
||||
),
|
||||
{ ok: false, message: '暂不支持图集', errorType: 'IMAGE_SET' }
|
||||
)
|
||||
})
|
||||
|
||||
test('下载阶段失败时标记为下载错误', () => {
|
||||
assert.deepEqual(
|
||||
parseDownloadedResult(
|
||||
'[{"url":"https://v.douyin.com/fixture123","ok":false,"aweme_id":"730","error":"fixture CDN timeout"}]'
|
||||
),
|
||||
{ ok: false, message: 'fixture CDN timeout', errorType: 'DOWNLOAD_FAILED' }
|
||||
)
|
||||
})
|
||||
|
||||
test('图集目录后面的附注被剥离', () => {
|
||||
const stdout = [' ✅ /tmp/fixture-folder (5 个文件)'].join('\n')
|
||||
assert.equal(parseSavedPath(stdout), '/tmp/fixture-folder')
|
||||
})
|
||||
|
||||
test('没有 ✅ 行时返回 null', () => {
|
||||
assert.equal(parseSavedPath(' ✗ 失败:超时\n完成:0/1 成功'), null)
|
||||
assert.equal(parseSavedPath(''), null)
|
||||
})
|
||||
|
||||
test('模板替换三个已知变量', () => {
|
||||
const caption = renderCaption('{author}:{title}({awemeId})', {
|
||||
author: '张三',
|
||||
title: '测试标题',
|
||||
awemeId: '730'
|
||||
})
|
||||
assert.equal(caption, '张三:测试标题(730)')
|
||||
})
|
||||
|
||||
test('未知变量原样保留', () => {
|
||||
const caption = renderCaption('{author} {unknownVar}', { author: '张三' })
|
||||
assert.equal(caption, '张三 {unknownVar}')
|
||||
})
|
||||
|
||||
test('超长文案截断到 200 字', () => {
|
||||
const caption = renderCaption('{title}', { title: '字'.repeat(400) })
|
||||
assert.equal(caption.length, 200)
|
||||
})
|
||||
|
||||
test('默认配置符合约定', () => {
|
||||
const config = normalizeConfig(undefined)
|
||||
assert.equal(config.configVersion, 1)
|
||||
assert.equal(config.enabled, false)
|
||||
assert.equal(config.pythonPath, 'python3')
|
||||
assert.equal(config.scriptPath, 'scripts/douyin.py')
|
||||
assert.equal(config.quality, '720')
|
||||
assert.equal(config.showUi, false)
|
||||
assert.equal(config.sendCaption, false)
|
||||
assert.equal(config.captionTemplate, '{author}:{title}')
|
||||
assert.equal(config.errorReply, true)
|
||||
assert.equal(config.includeDirect, false)
|
||||
assert.deepEqual(config.groups, [])
|
||||
assert.equal(config.cooldownSeconds, 60)
|
||||
assert.equal(config.maxFileMB, 100)
|
||||
})
|
||||
|
||||
test('常规配置不接纳 Cookie 凭证字段', () => {
|
||||
const config = normalizeConfig({ cookie: 'must-not-persist', cookieFile: '/tmp/fixture-cookie' })
|
||||
assert.equal(Object.hasOwn(config, 'cookie'), false)
|
||||
assert.equal(Object.hasOwn(config, 'cookieFile'), false)
|
||||
})
|
||||
|
||||
test('非法画质收敛到 720,空串表示最高', () => {
|
||||
assert.equal(normalizeConfig({ quality: '4k' }).quality, '720')
|
||||
assert.equal(normalizeConfig({ quality: '' }).quality, '')
|
||||
assert.equal(normalizeConfig({ quality: '1080' }).quality, '1080')
|
||||
})
|
||||
|
||||
test('数值型画质按字符串处理', () => {
|
||||
assert.equal(normalizeConfig({ quality: 540 }).quality, '540')
|
||||
})
|
||||
|
||||
test('showUi 只接受布尔 true', () => {
|
||||
assert.equal(normalizeConfig({ showUi: true }).showUi, true)
|
||||
assert.equal(normalizeConfig({ showUi: 'true' }).showUi, false)
|
||||
assert.equal(normalizeConfig({ showUi: 1 }).showUi, false)
|
||||
})
|
||||
|
||||
test('ackText 默认有回执,空串表示关闭', () => {
|
||||
assert.match(normalizeConfig({}).ackText, /收到/)
|
||||
assert.equal(normalizeConfig({ ackText: '' }).ackText, '')
|
||||
assert.equal(normalizeConfig({ ackText: ' 好的 ' }).ackText, '好的')
|
||||
assert.equal(normalizeConfig({ ackText: 'x'.repeat(300) }).ackText.length, 200)
|
||||
})
|
||||
|
||||
test('冷却与文件上限被夹到合法区间', () => {
|
||||
assert.equal(normalizeConfig({ cooldownSeconds: -10 }).cooldownSeconds, 0)
|
||||
assert.equal(normalizeConfig({ cooldownSeconds: 999999 }).cooldownSeconds, 3600)
|
||||
assert.equal(normalizeConfig({ maxFileMB: 0 }).maxFileMB, 1)
|
||||
assert.equal(normalizeConfig({ maxFileMB: 500 }).maxFileMB, 100)
|
||||
})
|
||||
|
||||
test('群 id 去空、去重并截断上限', () => {
|
||||
const config = normalizeConfig({
|
||||
groups: [' fixture-room@chatroom ', '', 'fixture-room@chatroom']
|
||||
})
|
||||
assert.deepEqual(config.groups, ['fixture-room@chatroom'])
|
||||
})
|
||||
|
||||
test('总开关关闭时拒绝处理', () => {
|
||||
const decision = shouldHandle(makeEvent(), makeConfig({ enabled: false }), new Map(), Date.now())
|
||||
assert.deepEqual(decision, { handle: false, url: null, reason: 'disabled' })
|
||||
})
|
||||
|
||||
test('自己发的消息拒绝处理', () => {
|
||||
const decision = shouldHandle(makeEvent({ isSelf: true }), makeConfig(), new Map(), Date.now())
|
||||
assert.equal(decision.handle, false)
|
||||
assert.equal(decision.reason, 'self')
|
||||
})
|
||||
|
||||
test('非 text 消息拒绝处理', () => {
|
||||
const decision = shouldHandle(makeEvent({ type: 'image' }), makeConfig(), new Map(), Date.now())
|
||||
assert.equal(decision.handle, false)
|
||||
assert.equal(decision.reason, 'type')
|
||||
})
|
||||
|
||||
test('没有真正 @ 我时拒绝处理', () => {
|
||||
const decision = shouldHandle(
|
||||
makeEvent({ mentionsMe: false }),
|
||||
makeConfig(),
|
||||
new Map(),
|
||||
Date.now()
|
||||
)
|
||||
assert.equal(decision.handle, false)
|
||||
assert.equal(decision.reason, 'mention')
|
||||
})
|
||||
|
||||
test('消息里没有链接时拒绝处理', () => {
|
||||
const decision = shouldHandle(
|
||||
makeEvent({ text: '@李四 今天天气不错' }),
|
||||
makeConfig(),
|
||||
new Map(),
|
||||
Date.now()
|
||||
)
|
||||
assert.equal(decision.handle, false)
|
||||
assert.equal(decision.reason, 'no_link')
|
||||
})
|
||||
|
||||
test('群不在白名单里时拒绝处理,但仍返回提取到的链接', () => {
|
||||
const decision = shouldHandle(
|
||||
makeEvent(),
|
||||
makeConfig({ groups: ['other-room@chatroom'] }),
|
||||
new Map(),
|
||||
Date.now()
|
||||
)
|
||||
assert.equal(decision.handle, false)
|
||||
assert.equal(decision.reason, 'scope')
|
||||
assert.equal(decision.url, SHORT_URL)
|
||||
})
|
||||
|
||||
test('群在白名单里时允许处理', () => {
|
||||
const decision = shouldHandle(
|
||||
makeEvent(),
|
||||
makeConfig({ groups: ['fixture-room@chatroom'] }),
|
||||
new Map(),
|
||||
Date.now()
|
||||
)
|
||||
assert.deepEqual(decision, { handle: true, url: SHORT_URL, reason: 'ok' })
|
||||
})
|
||||
|
||||
test('私聊默认不处理,开启后处理', () => {
|
||||
const direct = makeEvent({ isGroup: false, conversationId: 'wxid_fixture' })
|
||||
assert.equal(shouldHandle(direct, makeConfig(), new Map(), Date.now()).reason, 'scope')
|
||||
assert.equal(
|
||||
shouldHandle(direct, makeConfig({ includeDirect: true }), new Map(), Date.now()).reason,
|
||||
'ok'
|
||||
)
|
||||
})
|
||||
|
||||
test('冷却未过期时拒绝,过期后放行', () => {
|
||||
const now = 1_767_225_600_000
|
||||
const cooldown = new Map([['fixture-room@chatroom', now + 30_000]])
|
||||
assert.equal(shouldHandle(makeEvent(), makeConfig(), cooldown, now).reason, 'cooldown')
|
||||
assert.equal(shouldHandle(makeEvent(), makeConfig(), cooldown, now + 30_001).reason, 'ok')
|
||||
})
|
||||
|
||||
test('图集不算视频', () => {
|
||||
const results = [
|
||||
{ url: SHORT_URL, ok: true, type: 'image', aweme_id: '730' },
|
||||
{ url: VIDEO_URL, ok: true, type: 'video', aweme_id: '731' }
|
||||
]
|
||||
assert.equal(pickVideoResult(results).aweme_id, '731')
|
||||
assert.equal(pickVideoResult([results[0]]), null)
|
||||
})
|
||||
|
||||
test('跳过失败项并容忍非数组输入', () => {
|
||||
assert.equal(pickVideoResult([{ ok: false, error: '超时' }]), null)
|
||||
assert.equal(pickVideoResult(null), null)
|
||||
assert.equal(pickVideoResult([]), null)
|
||||
})
|
||||
|
||||
test('文件大小判定覆盖上限与非法值', () => {
|
||||
assert.equal(isFileTooLarge(100 * 1024 * 1024, 100), false)
|
||||
assert.equal(isFileTooLarge(100 * 1024 * 1024 + 1, 100), true)
|
||||
assert.equal(isFileTooLarge(2 * 1024 * 1024, 1), true)
|
||||
assert.equal(isFileTooLarge(0, 100), true)
|
||||
assert.equal(isFileTooLarge(Number.NaN, 100), true)
|
||||
assert.equal(isFileTooLarge(1, 100), false)
|
||||
})
|
||||
|
||||
test('DEFAULT_CONFIG 不被 normalizeConfig 修改', () => {
|
||||
const before = JSON.stringify(DEFAULT_CONFIG)
|
||||
const config = normalizeConfig({ enabled: true, groups: ['fixture-room@chatroom'] })
|
||||
config.groups.push('wxid_fixture')
|
||||
assert.equal(JSON.stringify(DEFAULT_CONFIG), before)
|
||||
})
|
||||
@@ -0,0 +1,620 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* 扩展页面桥。
|
||||
*
|
||||
* 页面只能通过宿主白名单能力与宿主通信,
|
||||
* 没有发送能力,也没有 `require`。
|
||||
*/
|
||||
|
||||
const EXTENSION_ID = 'com.example.douyin-sender'
|
||||
const PAGE_SOURCE = 'tracememo-extension-page'
|
||||
const HOST_SOURCE = 'tracememo-extension-host'
|
||||
const CONFIG_KEY = 'config'
|
||||
const STATS_KEY = 'stats'
|
||||
const PROGRESS_KEY = 'progress'
|
||||
const TEST_RESULT_KEY = 'testResult'
|
||||
|
||||
const ALLOWED_METHODS = new Set([
|
||||
'storage.get',
|
||||
'storage.set',
|
||||
'storage.remove',
|
||||
'storage.list',
|
||||
'capabilities.get',
|
||||
'contacts.listGroups',
|
||||
'test.send',
|
||||
'douyin.cookie.get',
|
||||
'douyin.cookie.set',
|
||||
'douyin.cookie.clear',
|
||||
'extension.info'
|
||||
])
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
configVersion: 1,
|
||||
enabled: false,
|
||||
pythonPath: 'python3',
|
||||
scriptPath: 'scripts/douyin.py',
|
||||
quality: '720',
|
||||
showUi: false,
|
||||
ackText: '收到,正在解析,请稍候…',
|
||||
sendCaption: false,
|
||||
captionTemplate: '{author}:{title}',
|
||||
errorReply: true,
|
||||
includeDirect: false,
|
||||
groups: [],
|
||||
cooldownSeconds: 60,
|
||||
maxFileMB: 100
|
||||
}
|
||||
|
||||
const STAGE_LABELS = {
|
||||
accepted: '已接收',
|
||||
resolve: '解析',
|
||||
resolveDownload: '解析并下载',
|
||||
download: '下载',
|
||||
send: '发送',
|
||||
caption: '补发文案',
|
||||
done: '完成',
|
||||
failed: '失败'
|
||||
}
|
||||
|
||||
const pending = new Map()
|
||||
let sequence = 0
|
||||
let config = clone(DEFAULT_CONFIG)
|
||||
|
||||
function clone(value) {
|
||||
return JSON.parse(JSON.stringify(value))
|
||||
}
|
||||
|
||||
function callHost(method, params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!ALLOWED_METHODS.has(method)) {
|
||||
reject(new Error(`不支持的调用:${method}`))
|
||||
return
|
||||
}
|
||||
const requestId = `req-${++sequence}`
|
||||
pending.set(requestId, { resolve, reject })
|
||||
window.parent.postMessage(
|
||||
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params },
|
||||
'*'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
const data = event.data
|
||||
if (!data || data.source !== HOST_SOURCE) return
|
||||
const entry = pending.get(data.requestId)
|
||||
if (!entry) return
|
||||
pending.delete(data.requestId)
|
||||
if (data.ok) entry.resolve(data.result)
|
||||
else entry.reject(new Error((data.error && data.error.message) || '调用失败'))
|
||||
})
|
||||
|
||||
const status = document.getElementById('status')
|
||||
const rows = document.getElementById('job-rows')
|
||||
const todayTotal = document.getElementById('today-total')
|
||||
const todaySuccess = document.getElementById('today-success')
|
||||
const todayFailure = document.getElementById('today-failure')
|
||||
const progressBadge = document.getElementById('progress-badge')
|
||||
const progressStage = document.getElementById('progress-stage')
|
||||
const progressTime = document.getElementById('progress-time')
|
||||
const progressDetail = document.getElementById('progress-detail')
|
||||
const testGroup = document.getElementById('test-group')
|
||||
const testUrl = document.getElementById('test-url')
|
||||
const cookieHeader = document.getElementById('cookie-header')
|
||||
const cookieState = document.getElementById('cookie-state')
|
||||
const testResult = document.getElementById('test-result')
|
||||
const groupPicker = document.getElementById('group-picker')
|
||||
const groupChips = document.getElementById('group-chips')
|
||||
const groupSearch = document.getElementById('group-search')
|
||||
const groupOptions = document.getElementById('group-options')
|
||||
|
||||
let allGroups = []
|
||||
let selectedGroupIds = new Set()
|
||||
let groupLoadError = ''
|
||||
|
||||
function setStatus(text, kind) {
|
||||
status.textContent = text
|
||||
status.dataset.kind = kind || ''
|
||||
}
|
||||
|
||||
function clampInt(value, fallback, min, max) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return fallback
|
||||
return Math.max(min, Math.min(Math.trunc(numeric), max))
|
||||
}
|
||||
|
||||
function normalizeConfig(raw) {
|
||||
const input = raw && typeof raw === 'object' ? raw : {}
|
||||
const quality = ['', '1080', '720', '540'].includes(String(input.quality))
|
||||
? String(input.quality)
|
||||
: DEFAULT_CONFIG.quality
|
||||
return {
|
||||
configVersion: 1,
|
||||
enabled: input.enabled === true,
|
||||
pythonPath: String(input.pythonPath || DEFAULT_CONFIG.pythonPath).trim(),
|
||||
scriptPath: String(input.scriptPath || DEFAULT_CONFIG.scriptPath).trim(),
|
||||
quality,
|
||||
showUi: input.showUi === true,
|
||||
ackText:
|
||||
input.ackText === undefined
|
||||
? DEFAULT_CONFIG.ackText
|
||||
: String(input.ackText).trim().slice(0, 200),
|
||||
sendCaption: false,
|
||||
captionTemplate: String(input.captionTemplate || DEFAULT_CONFIG.captionTemplate).slice(0, 200),
|
||||
errorReply: input.errorReply !== false,
|
||||
includeDirect: input.includeDirect === true,
|
||||
groups: Array.isArray(input.groups)
|
||||
? input.groups
|
||||
.map((id) => String(id).trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, 200)
|
||||
: [],
|
||||
cooldownSeconds: clampInt(input.cooldownSeconds, DEFAULT_CONFIG.cooldownSeconds, 0, 3600),
|
||||
maxFileMB: clampInt(input.maxFileMB, DEFAULT_CONFIG.maxFileMB, 1, 100)
|
||||
}
|
||||
}
|
||||
|
||||
function syncForm() {
|
||||
document.getElementById('enabled').checked = config.enabled === true
|
||||
document.getElementById('python-path').value = config.pythonPath
|
||||
document.getElementById('script-path').value = config.scriptPath
|
||||
document.getElementById('quality').value = config.quality
|
||||
document.getElementById('show-ui').checked = config.showUi === true
|
||||
document.getElementById('ack-text').value = config.ackText
|
||||
document.getElementById('error-reply').checked = config.errorReply === true
|
||||
selectedGroupIds = new Set(config.groups)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
document.getElementById('include-direct').checked = config.includeDirect === true
|
||||
document.getElementById('cooldown').value = String(config.cooldownSeconds)
|
||||
document.getElementById('max-file-mb').value = String(config.maxFileMB)
|
||||
}
|
||||
|
||||
function readForm() {
|
||||
config.enabled = document.getElementById('enabled').checked
|
||||
config.pythonPath = document.getElementById('python-path').value.trim()
|
||||
config.scriptPath = document.getElementById('script-path').value.trim()
|
||||
config.quality = document.getElementById('quality').value
|
||||
config.showUi = document.getElementById('show-ui').checked
|
||||
config.ackText = document.getElementById('ack-text').value.trim().slice(0, 200)
|
||||
config.sendCaption = false
|
||||
config.errorReply = document.getElementById('error-reply').checked
|
||||
config.groups = [...selectedGroupIds].slice(0, 200)
|
||||
config.includeDirect = document.getElementById('include-direct').checked
|
||||
config.cooldownSeconds = clampInt(
|
||||
document.getElementById('cooldown').value,
|
||||
DEFAULT_CONFIG.cooldownSeconds,
|
||||
0,
|
||||
3600
|
||||
)
|
||||
config.maxFileMB = clampInt(
|
||||
document.getElementById('max-file-mb').value,
|
||||
DEFAULT_CONFIG.maxFileMB,
|
||||
1,
|
||||
100
|
||||
)
|
||||
config.configVersion = 1
|
||||
}
|
||||
|
||||
function formatTime(value) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric) || numeric <= 0) return '—'
|
||||
const date = new Date(numeric)
|
||||
const pad = (part) => String(part).padStart(2, '0')
|
||||
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
||||
}
|
||||
|
||||
function renderStats(raw) {
|
||||
const stats = raw && typeof raw === 'object' ? raw : {}
|
||||
const jobs = Array.isArray(stats.lastJobs) ? stats.lastJobs.slice(0, 8) : []
|
||||
const total = Math.max(0, Math.trunc(Number(stats.todayTotal ?? stats.todayCount) || 0))
|
||||
todayTotal.textContent = String(total)
|
||||
todaySuccess.textContent = String(Math.max(0, Math.trunc(Number(stats.todaySuccess) || 0)))
|
||||
todayFailure.textContent = String(Math.max(0, Math.trunc(Number(stats.todayFailure) || 0)))
|
||||
rows.textContent = ''
|
||||
if (!jobs.length) {
|
||||
const row = document.createElement('tr')
|
||||
const cell = document.createElement('td')
|
||||
cell.colSpan = 5
|
||||
cell.className = 'empty'
|
||||
cell.textContent = '暂无记录'
|
||||
row.append(cell)
|
||||
rows.append(row)
|
||||
return
|
||||
}
|
||||
for (const job of jobs) {
|
||||
const row = document.createElement('tr')
|
||||
const time = document.createElement('td')
|
||||
time.textContent = formatTime(job && job.at)
|
||||
const id = document.createElement('td')
|
||||
id.className = 'mono'
|
||||
id.textContent = (job && job.awemeId) || '—'
|
||||
const stage = document.createElement('td')
|
||||
stage.textContent = STAGE_LABELS[job && job.stage] || (job && job.stage) || '—'
|
||||
const result = document.createElement('td')
|
||||
const ok = job && job.ok === true
|
||||
result.textContent = ok ? '成功' : '失败'
|
||||
result.className = ok ? 'ok' : 'fail'
|
||||
const error = document.createElement('td')
|
||||
error.className = 'mono'
|
||||
error.textContent = (job && job.errorType) || '—'
|
||||
row.append(time, id, stage, result, error)
|
||||
rows.append(row)
|
||||
}
|
||||
}
|
||||
|
||||
/** 进度:运行中显示阶段与已用时间;失败显示失败阶段与错误码。 */
|
||||
function renderProgress(raw) {
|
||||
const progress = raw && typeof raw === 'object' ? raw : null
|
||||
if (!progress || !progress.stage) {
|
||||
progressBadge.textContent = '空闲'
|
||||
progressBadge.dataset.status = 'idle'
|
||||
progressStage.textContent = '暂无任务'
|
||||
progressTime.textContent = ''
|
||||
progressDetail.textContent = '触发后这里会显示解析、下载、发送进行到哪一步。'
|
||||
return
|
||||
}
|
||||
const status =
|
||||
progress.status === 'failed' ? 'failed' : progress.status === 'done' ? 'done' : 'running'
|
||||
progressBadge.textContent = status === 'failed' ? '失败' : status === 'done' ? '完成' : '进行中'
|
||||
progressBadge.dataset.status = status
|
||||
progressStage.textContent =
|
||||
status === 'failed'
|
||||
? `失败于:${STAGE_LABELS[progress.stage] || progress.stage}`
|
||||
: status === 'done'
|
||||
? '已完成'
|
||||
: `正在${STAGE_LABELS[progress.stage] || progress.stage}`
|
||||
const startedAt = Number(progress.startedAt)
|
||||
// 运行中用当前时间计算,脚本卡住时秒数也会继续走,不会看起来停在 0s。
|
||||
const updatedAt = status === 'running' ? Date.now() : Number(progress.updatedAt) || Date.now()
|
||||
const elapsed =
|
||||
Number.isFinite(startedAt) && startedAt > 0
|
||||
? Math.max(0, Math.round((updatedAt - startedAt) / 1000))
|
||||
: null
|
||||
progressTime.textContent = elapsed === null ? '' : `· ${elapsed}s`
|
||||
const parts = []
|
||||
if (progress.awemeId) parts.push(`作品 ${progress.awemeId}`)
|
||||
if (status === 'failed' && progress.errorType) parts.push(`错误 ${progress.errorType}`)
|
||||
if (status === 'failed' && progress.errorMessage) parts.push(progress.errorMessage)
|
||||
if (status === 'done') parts.push('视频已发送')
|
||||
progressDetail.textContent = parts.join(' · ') || ''
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
try {
|
||||
const stored = await callHost('storage.get', { key: STATS_KEY })
|
||||
renderStats(stored)
|
||||
} catch (error) {
|
||||
renderStats(null)
|
||||
setStatus(`统计读取失败:${error.message}`, 'error')
|
||||
}
|
||||
}
|
||||
|
||||
async function loadProgress() {
|
||||
try {
|
||||
const stored = await callHost('storage.get', { key: PROGRESS_KEY })
|
||||
renderProgress(stored)
|
||||
} catch {
|
||||
renderProgress(null)
|
||||
}
|
||||
}
|
||||
|
||||
let testPollTimer = null
|
||||
let activeTestId = ''
|
||||
|
||||
function setTestResult(text, kind) {
|
||||
testResult.textContent = text
|
||||
testResult.dataset.kind = kind || ''
|
||||
}
|
||||
|
||||
function groupDisplayName(group) {
|
||||
if (!group) return ''
|
||||
return group.name && group.name !== group.id ? `${group.name}(${group.id})` : group.id
|
||||
}
|
||||
|
||||
function emptyGroupOption(text) {
|
||||
const empty = document.createElement('div')
|
||||
empty.className = 'group-option-empty'
|
||||
empty.textContent = text
|
||||
return empty
|
||||
}
|
||||
|
||||
function renderGroupChips() {
|
||||
groupChips.textContent = ''
|
||||
groupChips.hidden = selectedGroupIds.size === 0
|
||||
for (const id of selectedGroupIds) {
|
||||
const group = allGroups.find((item) => item.id === id)
|
||||
const chip = document.createElement('span')
|
||||
chip.className = 'group-chip'
|
||||
const name = document.createElement('span')
|
||||
name.textContent = group ? group.name || id : id
|
||||
name.title = id
|
||||
const remove = document.createElement('button')
|
||||
remove.type = 'button'
|
||||
remove.className = 'group-chip-remove'
|
||||
remove.textContent = '×'
|
||||
remove.setAttribute('aria-label', `移除 ${group ? group.name || id : id}`)
|
||||
remove.addEventListener('click', (event) => {
|
||||
event.stopPropagation()
|
||||
selectedGroupIds.delete(id)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
})
|
||||
chip.append(name, remove)
|
||||
groupChips.append(chip)
|
||||
}
|
||||
}
|
||||
|
||||
function renderGroupOptions() {
|
||||
if (groupOptions.hidden) return
|
||||
const query = groupSearch.value.trim().toLowerCase()
|
||||
groupOptions.textContent = ''
|
||||
if (groupLoadError) {
|
||||
groupOptions.append(emptyGroupOption(groupLoadError))
|
||||
return
|
||||
}
|
||||
if (!allGroups.length) {
|
||||
groupOptions.append(emptyGroupOption('未读取到群列表(请先连接微信数据库)'))
|
||||
return
|
||||
}
|
||||
const matches = allGroups.filter((group) => {
|
||||
if (!query) return true
|
||||
return group.id.toLowerCase().includes(query) || group.name.toLowerCase().includes(query)
|
||||
})
|
||||
if (!matches.length) {
|
||||
groupOptions.append(emptyGroupOption('没有匹配的群聊'))
|
||||
return
|
||||
}
|
||||
for (const group of matches.slice(0, 200)) {
|
||||
const option = document.createElement('label')
|
||||
option.className = 'group-option'
|
||||
const checkbox = document.createElement('input')
|
||||
checkbox.type = 'checkbox'
|
||||
checkbox.checked = selectedGroupIds.has(group.id)
|
||||
checkbox.addEventListener('change', () => {
|
||||
if (checkbox.checked) selectedGroupIds.add(group.id)
|
||||
else selectedGroupIds.delete(group.id)
|
||||
renderGroupChips()
|
||||
})
|
||||
const text = document.createElement('span')
|
||||
text.textContent = groupDisplayName(group)
|
||||
option.append(checkbox, text)
|
||||
groupOptions.append(option)
|
||||
}
|
||||
}
|
||||
|
||||
function openGroupOptions() {
|
||||
groupOptions.hidden = false
|
||||
renderGroupOptions()
|
||||
}
|
||||
|
||||
function closeGroupOptions() {
|
||||
groupOptions.hidden = true
|
||||
groupSearch.value = ''
|
||||
}
|
||||
|
||||
groupSearch.addEventListener('focus', openGroupOptions)
|
||||
groupSearch.addEventListener('input', openGroupOptions)
|
||||
groupSearch.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape') {
|
||||
closeGroupOptions()
|
||||
groupSearch.blur()
|
||||
}
|
||||
})
|
||||
document.addEventListener('click', (event) => {
|
||||
if (!groupPicker.contains(event.target)) closeGroupOptions()
|
||||
})
|
||||
|
||||
/** 群列表来自宿主通讯录;数据库未连接时给出明确空态,而不是假装有选项。 */
|
||||
async function loadGroups() {
|
||||
const current = testGroup.value
|
||||
try {
|
||||
const result = await callHost('contacts.listGroups', {})
|
||||
allGroups = result && Array.isArray(result.groups) ? result.groups : []
|
||||
groupLoadError = ''
|
||||
testGroup.textContent = ''
|
||||
if (!allGroups.length) {
|
||||
const option = document.createElement('option')
|
||||
option.value = ''
|
||||
option.textContent = '未读取到群列表(请先连接微信数据库)'
|
||||
testGroup.append(option)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
return
|
||||
}
|
||||
const placeholder = document.createElement('option')
|
||||
placeholder.value = ''
|
||||
placeholder.textContent = '请选择群聊'
|
||||
testGroup.append(placeholder)
|
||||
for (const group of allGroups) {
|
||||
const option = document.createElement('option')
|
||||
option.value = group.id
|
||||
option.textContent = groupDisplayName(group)
|
||||
testGroup.append(option)
|
||||
}
|
||||
const saved = await callHost('storage.get', { key: 'testGroup' }).catch(() => null)
|
||||
const target = current || (typeof saved === 'string' ? saved : '')
|
||||
if (target && allGroups.some((group) => group.id === target)) testGroup.value = target
|
||||
} catch (error) {
|
||||
allGroups = []
|
||||
groupLoadError = `群列表读取失败:${error.message}`
|
||||
testGroup.textContent = ''
|
||||
const option = document.createElement('option')
|
||||
option.value = ''
|
||||
option.textContent = groupLoadError
|
||||
testGroup.append(option)
|
||||
}
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
}
|
||||
|
||||
/** 轮询后台写入的测试结果;只认本次请求的 id,避免串台。 */
|
||||
async function pollTestResult() {
|
||||
if (!activeTestId) return
|
||||
window.clearTimeout(testPollTimer)
|
||||
try {
|
||||
const result = await callHost('storage.get', { key: TEST_RESULT_KEY })
|
||||
if (result && result.id === activeTestId) {
|
||||
if (result.status === 'running') {
|
||||
setTestResult(result.message || '处理中…', 'running')
|
||||
} else if (result.status === 'done') {
|
||||
setTestResult(result.message || '测试发送完成', 'ok')
|
||||
activeTestId = ''
|
||||
return
|
||||
} else if (result.status === 'failed') {
|
||||
setTestResult(result.message || '测试发送失败', 'error')
|
||||
activeTestId = ''
|
||||
return
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 单次读取失败继续重试。
|
||||
}
|
||||
testPollTimer = window.setTimeout(() => {
|
||||
void pollTestResult()
|
||||
}, 1500)
|
||||
}
|
||||
|
||||
async function loadConfig() {
|
||||
const stored = await callHost('storage.get', { key: CONFIG_KEY })
|
||||
config = normalizeConfig(stored)
|
||||
syncForm()
|
||||
}
|
||||
|
||||
async function loadCookieState() {
|
||||
try {
|
||||
const result = await callHost('douyin.cookie.get', {})
|
||||
cookieState.textContent =
|
||||
result && result.configured ? '已保存 Cookie(内容不可回显)' : '未配置'
|
||||
} catch {
|
||||
cookieState.textContent = '安全存储不可用,无法读取状态'
|
||||
}
|
||||
}
|
||||
void loadCookieState()
|
||||
|
||||
async function checkCapabilities() {
|
||||
try {
|
||||
const snapshot = await callHost('capabilities.get', {})
|
||||
const send = snapshot && snapshot.send ? snapshot.send : null
|
||||
if (!send || !send.canSendVideo) {
|
||||
setStatus('当前环境未就绪:视频发送通道不可用,配置仍可保存。', 'error')
|
||||
return true
|
||||
}
|
||||
} catch {
|
||||
// 能力查询失败不阻塞配置编辑。
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
testGroup.addEventListener('change', () => {
|
||||
void callHost('storage.set', { key: 'testGroup', value: testGroup.value }).catch(() => undefined)
|
||||
})
|
||||
|
||||
document.getElementById('test-refresh').addEventListener('click', () => {
|
||||
void loadGroups()
|
||||
})
|
||||
|
||||
document.getElementById('test-send').addEventListener('click', async () => {
|
||||
const to = testGroup.value
|
||||
const text = testUrl.value.trim()
|
||||
if (!to) {
|
||||
setTestResult('请先选择目标群聊。', 'error')
|
||||
return
|
||||
}
|
||||
if (!text) {
|
||||
setTestResult('请粘贴抖音分享链接或整段分享文案。', 'error')
|
||||
return
|
||||
}
|
||||
activeTestId = `test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
|
||||
setTestResult('已提交,等待后台开始解析…', 'running')
|
||||
try {
|
||||
const submitted = callHost('test.send', {
|
||||
id: activeTestId,
|
||||
to,
|
||||
text,
|
||||
at: Date.now()
|
||||
})
|
||||
void pollTestResult()
|
||||
await submitted
|
||||
} catch (error) {
|
||||
activeTestId = ''
|
||||
setTestResult(`提交失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('cookie-save').addEventListener('click', async () => {
|
||||
const value = cookieHeader.value.trim()
|
||||
if (!value) {
|
||||
setStatus('请先粘贴抖音 Cookie。', 'error')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await callHost('douyin.cookie.set', { cookieHeader: value })
|
||||
cookieHeader.value = ''
|
||||
await loadCookieState()
|
||||
setStatus('Cookie 已安全保存。', 'ok')
|
||||
} catch (error) {
|
||||
setStatus(`Cookie 保存失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('cookie-clear').addEventListener('click', async () => {
|
||||
try {
|
||||
await callHost('douyin.cookie.clear', {})
|
||||
cookieHeader.value = ''
|
||||
await loadCookieState()
|
||||
setStatus('Cookie 已清除。', 'ok')
|
||||
} catch (error) {
|
||||
setStatus(`Cookie 清除失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('save').addEventListener('click', async () => {
|
||||
readForm()
|
||||
if (!config.pythonPath) {
|
||||
setStatus('Python 可执行文件不能为空。', 'error')
|
||||
return
|
||||
}
|
||||
if (!config.scriptPath) {
|
||||
setStatus('解析脚本路径不能为空。', 'error')
|
||||
return
|
||||
}
|
||||
if (!config.captionTemplate.trim() && config.sendCaption) {
|
||||
setStatus('已开启标题文案,模板不能为空。', 'error')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: config })
|
||||
setStatus('配置已保存,后台 1 秒内生效', 'ok')
|
||||
} catch (error) {
|
||||
setStatus(`保存失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('reload').addEventListener('click', async () => {
|
||||
try {
|
||||
await loadConfig()
|
||||
await loadStats()
|
||||
await loadProgress()
|
||||
setStatus('已重新读取配置。', 'ok')
|
||||
} catch (error) {
|
||||
setStatus(`读取失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
async function boot() {
|
||||
await loadConfig()
|
||||
await Promise.all([loadStats(), loadProgress(), loadGroups()])
|
||||
const blocked = await checkCapabilities()
|
||||
if (!blocked) setStatus('配置已读取。默认不启用,避免安装后立即对外发送。')
|
||||
// 页面打开期间轮询进度,任务跑到哪一步不用猜;统计低频刷新即可。
|
||||
window.setInterval(() => {
|
||||
void loadProgress()
|
||||
}, 2000)
|
||||
window.setInterval(() => {
|
||||
void loadStats()
|
||||
}, 6000)
|
||||
}
|
||||
|
||||
boot().catch((error) => setStatus(`加载失败:${error.message}`, 'error'))
|
||||
@@ -0,0 +1,192 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>抖音视频搬运</title>
|
||||
<link rel="stylesheet" href="./style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>抖音视频搬运</h1>
|
||||
<p>
|
||||
被 @ 且消息里带抖音分享链接时,解析视频并发回原会话。本页只写配置,发送全部由后台经
|
||||
TraceMemo Gateway 完成。
|
||||
</p>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input id="enabled" type="checkbox" />
|
||||
<span>启用</span>
|
||||
</label>
|
||||
</header>
|
||||
|
||||
<section class="panel">
|
||||
<h2>运行环境</h2>
|
||||
<label class="field">
|
||||
<span>Python 可执行文件</span>
|
||||
<input id="python-path" type="text" placeholder="python3" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>解析脚本路径(默认相对于扩展目录,支持 <code>~</code>,首次运行会在缓存目录创建 venv)</span>
|
||||
<input
|
||||
id="script-path"
|
||||
type="text"
|
||||
placeholder="scripts/douyin.py"
|
||||
/>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>画质</span>
|
||||
<select id="quality">
|
||||
<option value="">最高</option>
|
||||
<option value="1080">1080</option>
|
||||
<option value="720">720</option>
|
||||
<option value="540">540</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="check">
|
||||
<input id="show-ui" type="checkbox" />
|
||||
<span>显示浏览器窗口(排障用;可观察作品页实际停留状态,不保证改变平台响应)</span>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>抖音 Cookie</h2>
|
||||
<label class="field">
|
||||
<span>Cookie(安全加密保存;仅本机使用)</span>
|
||||
<input
|
||||
id="cookie-header"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
spellcheck="false"
|
||||
placeholder="粘贴抖音 Cookie header"
|
||||
/>
|
||||
</label>
|
||||
<p id="cookie-state" class="muted">未配置</p>
|
||||
<div class="row">
|
||||
<button id="cookie-save" type="button" class="primary">保存 Cookie</button>
|
||||
<button id="cookie-clear" type="button" class="ghost">清除 Cookie</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>回复与文案</h2>
|
||||
<label class="field">
|
||||
<span>触发后先回复一句(留空表示不回复)</span>
|
||||
<input id="ack-text" type="text" maxlength="200" placeholder="收到,正在解析,请稍候…" />
|
||||
</label>
|
||||
<label class="check"
|
||||
><input id="error-reply" type="checkbox" /><span
|
||||
>失败时在原会话回一条简短说明</span
|
||||
></label
|
||||
>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>监听范围</h2>
|
||||
<div class="field">
|
||||
<span>只处理这些群(可多选、可搜索;留空表示全部群)</span>
|
||||
<div id="group-picker" class="group-picker">
|
||||
<div id="group-chips" class="group-chips" hidden></div>
|
||||
<input
|
||||
id="group-search"
|
||||
type="text"
|
||||
placeholder="搜索群聊名称或 id…"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<div id="group-options" class="group-options" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="check"
|
||||
><input id="include-direct" type="checkbox" /><span>同时处理私聊</span></label
|
||||
>
|
||||
</div>
|
||||
<div class="grid-2">
|
||||
<label class="field">
|
||||
<span>冷却秒数(0–3600,按会话计)</span>
|
||||
<input id="cooldown" type="number" min="0" max="3600" step="1" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>文件大小上限(MB,1–100)</span>
|
||||
<input id="max-file-mb" type="number" min="1" max="100" step="1" />
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>测试发送</h2>
|
||||
<label class="field">
|
||||
<span>目标群聊</span>
|
||||
<select id="test-group">
|
||||
<option value="">加载中…</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>抖音分享链接或整段分享文案</span>
|
||||
<textarea
|
||||
id="test-url"
|
||||
rows="3"
|
||||
placeholder="https://v.douyin.com/xxxxxx/ 复制打开抖音…"
|
||||
></textarea>
|
||||
</label>
|
||||
<div class="row">
|
||||
<button id="test-send" type="button" class="primary">测试发送</button>
|
||||
<button id="test-refresh" type="button" class="ghost">刷新群列表</button>
|
||||
</div>
|
||||
<p id="test-result" class="status">
|
||||
选择群聊、粘贴链接后点「测试发送」,解析完成后视频会直接发到该群。已保存的 Cookie
|
||||
自动用于测试。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>当前任务</h2>
|
||||
<span id="progress-badge" class="badge">空闲</span>
|
||||
</div>
|
||||
<p class="progress-line">
|
||||
<strong id="progress-stage">暂无任务</strong>
|
||||
<span id="progress-time" class="muted"></span>
|
||||
</p>
|
||||
<p id="progress-detail" class="muted">触发后这里会显示解析、下载、发送进行到哪一步。</p>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>统计</h2>
|
||||
<span class="muted"
|
||||
>今日 总计 <strong id="today-total">0</strong> · 成功
|
||||
<strong id="today-success">0</strong> · 失败 <strong id="today-failure">0</strong></span
|
||||
>
|
||||
</div>
|
||||
<table class="stats">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>时间</th>
|
||||
<th>作品 ID</th>
|
||||
<th>阶段</th>
|
||||
<th>结果</th>
|
||||
<th>错误</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="job-rows">
|
||||
<tr>
|
||||
<td colspan="5" class="empty">暂无记录</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<footer class="page-footer">
|
||||
<div class="row">
|
||||
<button id="save" type="button" class="primary">保存配置</button>
|
||||
<button id="reload" type="button" class="ghost">重新读取</button>
|
||||
</div>
|
||||
<p id="status" class="status" role="status"></p>
|
||||
</footer>
|
||||
</main>
|
||||
<script src="./app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,387 @@
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--bg: #f6f8f7;
|
||||
--card: #ffffff;
|
||||
--text: #1c2622;
|
||||
--muted: #6b7a73;
|
||||
--border: #dfe6e2;
|
||||
--brand: #247a63;
|
||||
--danger: #b4472f;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #161c19;
|
||||
--card: #1e2622;
|
||||
--text: #eef4f1;
|
||||
--muted: #9aaba3;
|
||||
--border: #33403a;
|
||||
--brand: #4bb894;
|
||||
--danger: #e0735a;
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei',
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 720px;
|
||||
margin: 0 auto;
|
||||
padding: 26px 22px 40px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 19px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
header p {
|
||||
margin: 8px 0 0;
|
||||
max-width: 52ch;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 19px;
|
||||
}
|
||||
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--card);
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.field > span {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
input[type='text'],
|
||||
input[type='number'],
|
||||
select,
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.grid-2 {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.check,
|
||||
.switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.switch {
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 6px 11px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.primary {
|
||||
border-color: transparent;
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
button.ghost:hover {
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
.page-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.status {
|
||||
min-height: 18px;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.status[data-kind='ok'] {
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.status[data-kind='error'] {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.muted strong {
|
||||
color: var(--text);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.stats {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stats th {
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.stats td {
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.stats tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
.stats td.empty {
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stats .mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.stats .ok {
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.stats .fail {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
code {
|
||||
padding: 1px 4px;
|
||||
border-radius: 4px;
|
||||
background: var(--bg);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* 当前任务:状态徽标 + 一行阶段 + 一行细节。 */
|
||||
.badge {
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--bg);
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.badge[data-status='running'] {
|
||||
background: color-mix(in srgb, var(--brand) 14%, transparent);
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.badge[data-status='done'] {
|
||||
background: color-mix(in srgb, var(--brand) 14%, transparent);
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.badge[data-status='failed'] {
|
||||
background: color-mix(in srgb, var(--danger) 14%, transparent);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.progress-line {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.progress-line .muted {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* 群聊多选:chips + 搜索框 + 复选下拉。 */
|
||||
.group-picker {
|
||||
position: relative;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--card);
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.group-picker:focus-within {
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
.group-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.group-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
max-width: 100%;
|
||||
padding: 2px 4px 2px 8px;
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.group-chip > span {
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.group-chip-remove {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.group-chip-remove:hover {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.group-picker > input[type='text'] {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
padding: 4px 2px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.group-options {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: calc(100% + 4px);
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
padding: 4px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--card);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.group-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 6px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.group-option:hover {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.group-option input {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.group-option-empty {
|
||||
padding: 8px 6px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
# 关键词回复机器人
|
||||
|
||||
监听微信文本消息,按规则表匹配关键词,命中后经 TraceMemo Gateway 回复。
|
||||
|
||||
两条入口共用同一份配置与同一套判定(`lib/matcher.js`):
|
||||
|
||||
- `message.received` 事件:扩展自己判断范围与冷却,再调用 `tm.wechat.send`;
|
||||
- 自动化动作 `keyword.reply`:只返回回复文本,不发送,发送由宿主的自动化流程完成。
|
||||
|
||||
扩展本身不碰 socket、dylib 或 HTTP,所有发送都经过宿主 Gateway 的权限、授权校验、限流与审计。
|
||||
|
||||
## 目录
|
||||
|
||||
```text
|
||||
keyword-bot/
|
||||
manifest.json 权限、订阅、页面与自动化动作声明
|
||||
background/index.js 事件编排、冷却表、命中统计
|
||||
lib/matcher.js 纯函数:规范化 / 匹配 / 范围 / 模板 / 决策
|
||||
ui/ 配置页(沙箱 iframe,只调用 storage.* / capabilities.get / extension.info)
|
||||
tests/matcher.test.mjs
|
||||
```
|
||||
|
||||
## 功能
|
||||
|
||||
- 规则支持三种匹配方式:`contains`(包含)、`exact`(完全匹配)、`prefix`(以…开头),均不区分大小写;
|
||||
- 每条规则可单独启用/停用,并设置优先级与冷却;
|
||||
- 监听范围可按群限定,可开关私聊,可要求真正 @ 我;
|
||||
- 回复内容支持模板变量;
|
||||
- 配置页展示今日命中数与最近 5 条命中结果。
|
||||
|
||||
## 配置字段
|
||||
|
||||
顶层:
|
||||
|
||||
| 字段 | 类型 | 默认 | 说明 |
|
||||
| ------------------------ | -------- | ------- | ----------------------------------------- |
|
||||
| `configVersion` | number | `2` | 保存时写入;v1(无此字段)读取时自动迁移 |
|
||||
| `enabled` | boolean | `false` | 总开关。缺省关闭,避免安装后立即对外发送 |
|
||||
| `rules` | array | `[]` | 规则表,见下 |
|
||||
| `scope.groups` | string[] | `[]` | 群 id(`xxx@chatroom`);空数组表示全部群 |
|
||||
| `scope.includeDirect` | boolean | `true` | 是否处理私聊 |
|
||||
| `scope.requireMentionMe` | boolean | `false` | 是否只处理真正 @ 登录账号的消息 |
|
||||
|
||||
规则:
|
||||
|
||||
| 字段 | 类型 | 默认 | 约束 |
|
||||
| ----------------- | ------- | ------------- | ------------------------------------------- |
|
||||
| `id` | string | `rule-<序号>` | ≤ 64 字符;冷却键的一部分,尽量稳定 |
|
||||
| `keyword` | string | `''` | ≤ 120 字符;启用中为空的规则会被丢弃 |
|
||||
| `mode` | string | `contains` | `contains` / `exact` / `prefix` |
|
||||
| `reply` | string | `''` | ≤ 2000 字符;启用中为空的规则会被丢弃 |
|
||||
| `cooldownSeconds` | number | `0` | 0–3600,取整到秒 |
|
||||
| `enabled` | boolean | `true` | v1 规则迁移后为 `true`;显式 `false` 才停用 |
|
||||
| `priority` | number | `0` | 0–100 整数,越大越先匹配 |
|
||||
|
||||
配置页保存时只校验**启用中**的规则必须有 `keyword` 与 `reply`;停用的规则允许留空,方便先存草稿。
|
||||
|
||||
## 模板变量
|
||||
|
||||
| 变量 | 含义 |
|
||||
| ----------- | -------------------------------------------------------------------------- |
|
||||
| `{sender}` | 发送者昵称;为空时渲染为「你」。自动化动作路径没有发送者上下文,恒为「你」 |
|
||||
| `{keyword}` | 命中的关键词(规则里的原文) |
|
||||
| `{time}` | 当前本地时间 `HH:mm` |
|
||||
|
||||
未知变量(例如 `{group}`)原样保留,不会被静默删除。渲染结果 trim 后截断到 2000 字符。
|
||||
|
||||
## 优先级与冷却语义
|
||||
|
||||
- 只考虑 `enabled !== false` 的规则;按 `priority` 降序排列,同优先级保持规则在数组中的顺序;
|
||||
- 取**第一个**命中的规则,一条消息最多回复一次(stopOnMatch),不会叠加多条回复;
|
||||
- 冷却键是 `conversationId:ruleId`,即「同一会话 + 同一条规则」各自独立计时;
|
||||
- 冷却只在**发送成功后**写入:发送失败不占用冷却,下一条命中会立刻重试;
|
||||
- 冷却表只存在内存里,扩展进程重启后清空——宁可多回一条,也不跨重启误拦。
|
||||
|
||||
## 统计口径与隐私边界
|
||||
|
||||
存储键 `stats`,结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"dateKey": "2026-11-12",
|
||||
"todayCount": 3,
|
||||
"lastHits": [{ "at": 0, "ruleId": "rule-1", "ok": true }]
|
||||
}
|
||||
```
|
||||
|
||||
- 每条命中记一条,**成功和失败都记**;`todayCount` 统计的是命中的次数(含发送失败);
|
||||
- `lastHits` 最多保留 20 条,配置页只展示最近 5 条;`at` 是 epoch 毫秒;
|
||||
- 跨日后读取会把 `todayCount` 归零,`lastHits` 作为滚动历史保留;
|
||||
- 只记录规则 id、时间与发送结果,**不记录会话 id、消息正文、发送者昵称或群名**;
|
||||
- 统计写入失败只打 warn 日志,不影响回复;
|
||||
- 统计只覆盖事件自动回复,不包含自动化动作 `keyword.reply` 的调用。
|
||||
|
||||
## 测试
|
||||
|
||||
零依赖,Node 内置测试运行器,不安装任何包:
|
||||
|
||||
```bash
|
||||
node --test examples/extensions/keyword-bot/tests/matcher.test.mjs
|
||||
node --check examples/extensions/keyword-bot/lib/matcher.js
|
||||
node --check examples/extensions/keyword-bot/background/index.js
|
||||
node --check examples/extensions/keyword-bot/ui/app.js
|
||||
```
|
||||
|
||||
用例覆盖:三种匹配方式、大小写、空关键词、禁用规则、优先级与稳定性、群范围与私聊开关、@ 要求、自己发的消息、冷却中/过期、模板替换与未知变量、超长截断、v1 迁移、非法规则丢弃、数值越界收敛、决策顺序。
|
||||
|
||||
`tests/matcher.test.mjs` 中的 fixture 全部为占位数据(`张三`、`李四`、`测试群`、`fixture-room@chatroom`、`wxid_fixture`)。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 不回复自己发送的消息(`isSelf` 直接跳过);
|
||||
- 消息事件是「至多一次」投递:扩展进程重启的瞬间可能丢事件,没有补投队列;
|
||||
- 不读取群名,因此没有 `{group}` 变量;需要按群定制时请拆成多条规则并配合「监听范围」;
|
||||
- 配置缓存窗口为 1 秒,保存后最多 1 秒生效;
|
||||
- 冷却表与配置缓存都在扩展后台进程内存中,进程重启即丢失。
|
||||
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* 关键词回复机器人。
|
||||
*
|
||||
* 两条入口共用同一份配置与 `lib/matcher.js` 的同一套判定:
|
||||
* 1. `message.received` 事件 → 自己判断范围 / 冷却 → `tm.wechat.send`;
|
||||
* 2. 自动化动作 `keyword.reply` → 只返回回复内容,由宿主 Gateway 发送。
|
||||
*
|
||||
* 发送**永远**经过宿主:本文件里没有任何 socket、dylib 或 HTTP 调用。
|
||||
* 匹配/规范化逻辑全部在 `lib/matcher.js`,本文件只负责编排与统计。
|
||||
*/
|
||||
|
||||
const { normalizeConfig, pickRule, renderReply, shouldReply } = require('../lib/matcher.js')
|
||||
|
||||
const CONFIG_KEY = 'config'
|
||||
const STATS_KEY = 'stats'
|
||||
/** 配置缓存窗口:配置页保存后最多 1 秒生效,避免每条消息都读一次 storage。 */
|
||||
const CONFIG_TTL_MS = 1000
|
||||
/** 最近命中记录上限;只保留规则 id、时间与结果,不保留任何会话内容。 */
|
||||
const STATS_HISTORY_LIMIT = 20
|
||||
/** 冷却表清理阈值:超过后剔除已过期项,避免长期运行无限增长。 */
|
||||
const COOLDOWN_PRUNE_SIZE = 500
|
||||
|
||||
let tm = null
|
||||
let cachedConfig = null
|
||||
let cachedAt = 0
|
||||
let cachedStats = null
|
||||
const cooldownUntil = new Map()
|
||||
/** 统计写入串行化:并发消息不互相覆盖 `stats` 快照。 */
|
||||
let statsChain = Promise.resolve()
|
||||
|
||||
function loadConfig() {
|
||||
if (cachedConfig && Date.now() - cachedAt < CONFIG_TTL_MS) return Promise.resolve(cachedConfig)
|
||||
return Promise.resolve(tm.storage.get(CONFIG_KEY))
|
||||
.then((stored) => {
|
||||
cachedConfig = normalizeConfig(stored)
|
||||
cachedAt = Date.now()
|
||||
return cachedConfig
|
||||
})
|
||||
.catch((error) => {
|
||||
tm.log.warn(`读取配置失败,本次按未启用处理:${describeError(error)}`)
|
||||
// 读失败也要缓存一小段时间,避免每条消息都打一次失败日志。
|
||||
cachedConfig = normalizeConfig(null)
|
||||
cachedAt = Date.now()
|
||||
return cachedConfig
|
||||
})
|
||||
}
|
||||
|
||||
/** 本地时区的 `YYYY-MM-DD`,用于判定「今日」。 */
|
||||
function statsDateKey(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${month}-${day}`
|
||||
}
|
||||
|
||||
/** 本地时区的 `HH:mm`,模板变量 `{time}` 与统计展示共用。 */
|
||||
function formatClock(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const hour = String(date.getHours()).padStart(2, '0')
|
||||
const minute = String(date.getMinutes()).padStart(2, '0')
|
||||
return `${hour}:${minute}`
|
||||
}
|
||||
|
||||
function emptyStats(timestamp) {
|
||||
return { dateKey: statsDateKey(timestamp), todayCount: 0, lastHits: [] }
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化统计快照。
|
||||
*
|
||||
* 跨日后 `todayCount` 归零;`lastHits` 作为滚动历史保留(它记的是「最近命中」,
|
||||
* 不是「今日命中」)。任何字段缺失或类型不对都退化为空值,统计损坏不能影响回复。
|
||||
*/
|
||||
function normalizeStats(raw, timestamp) {
|
||||
const base = emptyStats(timestamp)
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return base
|
||||
const lastHits = Array.isArray(raw.lastHits)
|
||||
? raw.lastHits
|
||||
.filter((hit) => hit && typeof hit === 'object')
|
||||
.map((hit) => ({
|
||||
at: Number(hit.at),
|
||||
ruleId: String(hit.ruleId == null ? '' : hit.ruleId).slice(0, 64),
|
||||
ok: hit.ok === true
|
||||
}))
|
||||
.filter((hit) => Number.isFinite(hit.at) && hit.at > 0 && hit.ruleId)
|
||||
.slice(-STATS_HISTORY_LIMIT)
|
||||
: []
|
||||
const sameDay = raw.dateKey === base.dateKey
|
||||
const count = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0
|
||||
return { dateKey: base.dateKey, todayCount: count, lastHits }
|
||||
}
|
||||
|
||||
function loadStats() {
|
||||
if (cachedStats) return Promise.resolve(cachedStats)
|
||||
return Promise.resolve(tm.storage.get(STATS_KEY))
|
||||
.then((stored) => {
|
||||
cachedStats = normalizeStats(stored, Date.now())
|
||||
return cachedStats
|
||||
})
|
||||
.catch(() => {
|
||||
cachedStats = emptyStats(Date.now())
|
||||
return cachedStats
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加一条命中记录并落库。
|
||||
*
|
||||
* 成功与失败都记;只写 `ruleId` / `at` / `ok`,绝不写会话 id、正文或昵称。
|
||||
* 写失败只 warn:统计是旁路,不能因为 storage 异常把回复一起吞掉。
|
||||
*/
|
||||
function recordHit(ruleId, ok) {
|
||||
statsChain = statsChain
|
||||
.then(async () => {
|
||||
const stats = await loadStats()
|
||||
const now = Date.now()
|
||||
const dateKey = statsDateKey(now)
|
||||
if (stats.dateKey !== dateKey) {
|
||||
stats.dateKey = dateKey
|
||||
stats.todayCount = 0
|
||||
}
|
||||
stats.todayCount += 1
|
||||
stats.lastHits = stats.lastHits
|
||||
.concat({ at: now, ruleId: String(ruleId || '').slice(0, 64), ok: ok === true })
|
||||
.slice(-STATS_HISTORY_LIMIT)
|
||||
await tm.storage.set(STATS_KEY, stats)
|
||||
})
|
||||
.catch((error) => {
|
||||
tm.log.warn(`命中统计写入失败:${describeError(error)}`)
|
||||
})
|
||||
return statsChain
|
||||
}
|
||||
|
||||
/** 冷却只在真正发送成功后写入;发送失败不占冷却,下一条可以立刻重试。 */
|
||||
function markCooldown(conversationId, rule, timestamp) {
|
||||
const seconds = Number(rule.cooldownSeconds) || 0
|
||||
cooldownUntil.set(`${conversationId}:${rule.id}`, timestamp + seconds * 1000)
|
||||
if (cooldownUntil.size > COOLDOWN_PRUNE_SIZE) {
|
||||
for (const [key, until] of cooldownUntil) {
|
||||
if (until <= timestamp) cooldownUntil.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function describeError(error) {
|
||||
return error && error.message ? error.message : String(error)
|
||||
}
|
||||
|
||||
async function onMessage(event) {
|
||||
try {
|
||||
const config = await loadConfig()
|
||||
const now = Date.now()
|
||||
const verdict = shouldReply(event, config, cooldownUntil, now)
|
||||
if (!verdict.reply || !verdict.rule) return
|
||||
|
||||
const rule = verdict.rule
|
||||
const text = renderReply(rule.reply, {
|
||||
senderName: event.senderName,
|
||||
keyword: rule.keyword,
|
||||
time: formatClock(now)
|
||||
})
|
||||
|
||||
try {
|
||||
await tm.wechat.send({
|
||||
to: event.conversationId,
|
||||
text,
|
||||
// 同一条微信消息在补投/重启后 eventId 不变,交给 Gateway 幂等短路。
|
||||
dedupeKey: event.eventId
|
||||
})
|
||||
} catch (error) {
|
||||
await recordHit(rule.id, false)
|
||||
throw error
|
||||
}
|
||||
|
||||
markCooldown(event.conversationId, rule, Date.now())
|
||||
await recordHit(rule.id, true)
|
||||
tm.log.info(`关键词命中,已发送回复(规则 ${rule.id})`)
|
||||
} catch (error) {
|
||||
tm.log.error(`自动回复失败:${describeError(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = function activate(api) {
|
||||
tm = api
|
||||
tm.events.on('message.received', onMessage)
|
||||
|
||||
tm.automation.registerAction({
|
||||
id: 'keyword.reply',
|
||||
title: '关键词回复',
|
||||
description: '按机器人配置匹配关键词并返回回复内容',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { text: { type: 'string' } },
|
||||
required: ['text']
|
||||
},
|
||||
async handler(input) {
|
||||
const config = await loadConfig()
|
||||
if (!config.enabled) {
|
||||
return { success: false, error: '机器人未启用' }
|
||||
}
|
||||
const rule = pickRule(input.text, config)
|
||||
if (!rule) {
|
||||
return { success: true, output: { matched: false } }
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
output: { matched: true, ruleId: rule.id },
|
||||
// 动作路径没有发送者上下文,`{sender}` 会渲染成「你」。
|
||||
reply: {
|
||||
type: 'text',
|
||||
text: renderReply(rule.reply, {
|
||||
keyword: rule.keyword,
|
||||
time: formatClock(Date.now())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
tm.log.info('关键词回复机器人已加载')
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* 关键词回复的纯函数层:配置规范化、匹配、范围判定、模板渲染、决策。
|
||||
*
|
||||
* 契约:
|
||||
* - 全部函数无副作用、不读写 storage、不打印日志,便于单测与后台进程复用;
|
||||
* - 输入一律容忍 `undefined` / 错误类型,坏配置退化为「不回复」而不是抛错;
|
||||
* - `enabled` 在任何一层都是硬开关:配置损坏时不能自动对外发送。
|
||||
*/
|
||||
|
||||
/** 当前配置结构版本。v1 没有该字段,读取时按 v1 迁移。 */
|
||||
const CONFIG_VERSION = 2
|
||||
|
||||
/** 与 UI、宿主动作输出保持一致的长度上限(字符)。 */
|
||||
const MAX_RULE_ID_LENGTH = 64
|
||||
const MAX_KEYWORD_LENGTH = 120
|
||||
const MAX_REPLY_LENGTH = 2000
|
||||
const MAX_GROUPS = 200
|
||||
|
||||
const MODES = new Set(['contains', 'exact', 'prefix'])
|
||||
|
||||
/**
|
||||
* 把任意来源的配置规范化为 `configVersion: 2`。
|
||||
*
|
||||
* 启用中的空规则丢弃,停用的空规则保留为草稿;顶层 `enabled` 缺省 `false`,
|
||||
* 配置缺失或损坏时宁可静默,也不能自动群发。
|
||||
*
|
||||
* @param {unknown} raw storage 里读出的原始值
|
||||
*/
|
||||
function normalizeConfig(raw) {
|
||||
const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
||||
const sourceRules = Array.isArray(input.rules) ? input.rules : []
|
||||
const rules = sourceRules
|
||||
.filter((rule) => rule && typeof rule === 'object' && !Array.isArray(rule))
|
||||
.map((rule, index) => ({
|
||||
id: String(rule.id || `rule-${index + 1}`).slice(0, MAX_RULE_ID_LENGTH),
|
||||
keyword: String(rule.keyword == null ? '' : rule.keyword).slice(0, MAX_KEYWORD_LENGTH),
|
||||
mode: MODES.has(rule.mode) ? rule.mode : 'contains',
|
||||
reply: String(rule.reply == null ? '' : rule.reply).slice(0, MAX_REPLY_LENGTH),
|
||||
cooldownSeconds: clampNumber(rule.cooldownSeconds, 0, 3600),
|
||||
// v1 规则没有该字段;只有显式 false 才算禁用。
|
||||
enabled: rule.enabled !== false,
|
||||
priority: clampNumber(rule.priority, 0, 100)
|
||||
}))
|
||||
.filter((rule) => rule.enabled === false || (rule.keyword.trim() && rule.reply.trim()))
|
||||
|
||||
const scope = input.scope && typeof input.scope === 'object' ? input.scope : {}
|
||||
return {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: input.enabled === true,
|
||||
rules,
|
||||
scope: {
|
||||
groups: Array.isArray(scope.groups)
|
||||
? scope.groups
|
||||
.map((id) => String(id == null ? '' : id).trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, MAX_GROUPS)
|
||||
: [],
|
||||
includeDirect: scope.includeDirect !== false,
|
||||
requireMentionMe: scope.requireMentionMe === true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条规则是否命中文本:大小写不敏感;`exact` / `prefix` 先 trim,
|
||||
* `contains` 只 trim 关键词;空关键词恒为 false。
|
||||
*
|
||||
* @param {unknown} text 消息正文
|
||||
* @param {{ keyword?: unknown, mode?: unknown }} rule
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function matchRule(text, rule) {
|
||||
const keyword = String((rule && rule.keyword) == null ? '' : rule.keyword)
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
if (!keyword) return false
|
||||
const haystack = String(text == null ? '' : text).toLowerCase()
|
||||
const mode = rule && MODES.has(rule.mode) ? rule.mode : 'contains'
|
||||
if (mode === 'exact') return haystack.trim() === keyword
|
||||
if (mode === 'prefix') return haystack.trim().startsWith(keyword)
|
||||
return haystack.includes(keyword)
|
||||
}
|
||||
|
||||
/**
|
||||
* 选出唯一命中的规则:`priority` 降序、同优先级保持数组顺序,取第一个命中。
|
||||
*
|
||||
* 这就是 stopOnMatch 语义:一条消息最多回复一次,命中即停。
|
||||
* 禁用规则(`enabled === false`)不参与匹配。
|
||||
*
|
||||
* @param {unknown} text
|
||||
* @param {object} config normalizeConfig 的产物
|
||||
*/
|
||||
function pickRule(text, config) {
|
||||
const rules = config && Array.isArray(config.rules) ? config.rules : []
|
||||
const candidates = rules
|
||||
.map((rule, index) => ({ rule, index }))
|
||||
.filter((item) => item.rule && item.rule.enabled !== false)
|
||||
// 显式带下标排序,避免依赖引擎排序稳定性。
|
||||
.sort((a, b) => (b.rule.priority || 0) - (a.rule.priority || 0) || a.index - b.index)
|
||||
for (const item of candidates) {
|
||||
if (matchRule(text, item.rule)) return item.rule
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话是否在生效范围内。
|
||||
*
|
||||
* - 群聊:`groups` 为空表示全部群;非空时必须包含 `event.conversationId`;
|
||||
* - 私聊:只看 `includeDirect`。
|
||||
*
|
||||
* 范围在规则匹配之前判定:范围外的会话连匹配都不做,避免误触统计。
|
||||
*/
|
||||
function inScope(event, config) {
|
||||
const scope = (config && config.scope) || {}
|
||||
if (event && event.isGroup) {
|
||||
const groups = Array.isArray(scope.groups) ? scope.groups : []
|
||||
return groups.length === 0 || groups.includes(event.conversationId)
|
||||
}
|
||||
return scope.includeDirect !== false
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染回复模板。
|
||||
*
|
||||
* 支持 `{sender}`(发送者昵称,空则「你」)、`{keyword}`(命中关键词)、
|
||||
* `{time}`(调用方给的本地时间字符串,缺省空串)。未知 `{xxx}` 原样保留,
|
||||
* 方便用户在模板里写其它占位而不是被静默吃掉。结果 trim 后截断到 2000 字符。
|
||||
*/
|
||||
function renderReply(template, ctx) {
|
||||
const source = String(template == null ? '' : template)
|
||||
const context = ctx && typeof ctx === 'object' ? ctx : {}
|
||||
const sender = String(context.senderName == null ? '' : context.senderName).trim() || '你'
|
||||
const keyword = String(context.keyword == null ? '' : context.keyword)
|
||||
const time = String(context.time == null ? '' : context.time)
|
||||
const rendered = source.replace(/\{(sender|keyword|time)\}/g, (match, token) => {
|
||||
if (token === 'sender') return sender
|
||||
if (token === 'keyword') return keyword
|
||||
if (token === 'time') return time
|
||||
return match
|
||||
})
|
||||
return rendered.trim().slice(0, MAX_REPLY_LENGTH)
|
||||
}
|
||||
|
||||
/**
|
||||
* 综合决策:是否回复、用哪条规则、为什么。
|
||||
*
|
||||
* `reason` 取值固定,可直接用于日志/统计口径:
|
||||
* `disabled` | `self` | `type` | `scope` | `mention` | `no_match` | `cooldown` | `ok`。
|
||||
*
|
||||
* 判断顺序固定为:总开关 → 自己发的 → 消息类型 → 会话范围 → @ 要求 → 规则匹配 → 冷却。
|
||||
* 冷却键为 `conversationId:ruleId`,值为到期时间戳(epoch 毫秒),`now < until` 即冷却中。
|
||||
* 冷却表允许是 `Map` 或普通对象,后台进程重启后自然清空(宁可多回一条,也不跨重启误拦)。
|
||||
*
|
||||
* @param {object} event 宿主的 message.received 事件
|
||||
* @param {object} config normalizeConfig 的产物
|
||||
* @param {Map<string, number>|Record<string, number>} [cooldownUntil]
|
||||
* @param {number} [now] epoch 毫秒,缺省取当前时间
|
||||
*/
|
||||
function shouldReply(event, config, cooldownUntil, now) {
|
||||
if (!config || config.enabled !== true) {
|
||||
return { reply: false, rule: null, reason: 'disabled' }
|
||||
}
|
||||
if (!event || event.isSelf === true) {
|
||||
return { reply: false, rule: null, reason: 'self' }
|
||||
}
|
||||
if (event.type !== 'text') {
|
||||
return { reply: false, rule: null, reason: 'type' }
|
||||
}
|
||||
if (!inScope(event, config)) {
|
||||
return { reply: false, rule: null, reason: 'scope' }
|
||||
}
|
||||
if (config.scope && config.scope.requireMentionMe === true && event.mentionsMe !== true) {
|
||||
return { reply: false, rule: null, reason: 'mention' }
|
||||
}
|
||||
const rule = pickRule(event.text, config)
|
||||
if (!rule) {
|
||||
return { reply: false, rule: null, reason: 'no_match' }
|
||||
}
|
||||
const currentTime = Number.isFinite(now) ? now : Date.now()
|
||||
const key = `${event.conversationId}:${rule.id}`
|
||||
if (currentTime < readCooldown(cooldownUntil, key)) {
|
||||
return { reply: false, rule: null, reason: 'cooldown' }
|
||||
}
|
||||
return { reply: true, rule, reason: 'ok' }
|
||||
}
|
||||
|
||||
/** 冷却表读取:兼容 Map 与普通对象,缺失值按 0(永不冷却)。 */
|
||||
function readCooldown(table, key) {
|
||||
if (!table) return 0
|
||||
const value = table instanceof Map ? table.get(key) : table[key]
|
||||
const until = Number(value)
|
||||
return Number.isFinite(until) ? until : 0
|
||||
}
|
||||
|
||||
/** 收敛到 [min, max] 的整数;非数字 / NaN 一律当 0。 */
|
||||
function clampNumber(value, min, max) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return 0
|
||||
return Math.min(Math.max(Math.round(numeric), min), max)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CONFIG_VERSION,
|
||||
normalizeConfig,
|
||||
matchRule,
|
||||
pickRule,
|
||||
inScope,
|
||||
renderReply,
|
||||
shouldReply
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.keyword-bot",
|
||||
"name": "关键词回复机器人",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.6.0",
|
||||
"description": "监听微信文本消息,命中关键词后经 TraceMemo Gateway 回复。",
|
||||
"author": "TraceMemo Examples",
|
||||
"permissions": [
|
||||
"messages.subscribe",
|
||||
"contacts.list",
|
||||
"wechat.send.text",
|
||||
"storage",
|
||||
"automation.action"
|
||||
],
|
||||
"entrypoints": {
|
||||
"page": "ui/index.html",
|
||||
"background": "background/index.js"
|
||||
},
|
||||
"subscriptions": {
|
||||
"messageTypes": ["text"],
|
||||
"conversationIds": [],
|
||||
"requireMentionMe": false,
|
||||
"includeSelf": false
|
||||
},
|
||||
"contributions": {
|
||||
"pages": [
|
||||
{
|
||||
"id": "settings",
|
||||
"title": "机器人配置"
|
||||
}
|
||||
],
|
||||
"automationActions": [
|
||||
{
|
||||
"id": "keyword.reply",
|
||||
"title": "关键词回复",
|
||||
"description": "按机器人配置匹配关键词并返回回复内容"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import matcher from '../lib/matcher.js'
|
||||
|
||||
const { normalizeConfig, matchRule, pickRule, inScope, renderReply, shouldReply } = matcher
|
||||
|
||||
const GROUP_ID = 'fixture-room@chatroom'
|
||||
const NOW = 1_700_000_000_000
|
||||
|
||||
/** 构造一份启用状态下的最小配置,参数按需覆盖。 */
|
||||
function buildConfig(overrides = {}) {
|
||||
return normalizeConfig({
|
||||
enabled: true,
|
||||
rules: [{ id: 'rule-1', keyword: '关键词', mode: 'contains', reply: '默认回复' }],
|
||||
scope: { groups: [], includeDirect: true, requireMentionMe: false },
|
||||
...overrides
|
||||
})
|
||||
}
|
||||
|
||||
/** 构造一条群聊文本消息事件。 */
|
||||
function buildEvent(overrides = {}) {
|
||||
return {
|
||||
eventId: 'event-fixture-1',
|
||||
accountId: 'account-fixture',
|
||||
conversationId: GROUP_ID,
|
||||
messageId: 'message-fixture-1',
|
||||
senderId: 'wxid_fixture',
|
||||
senderName: '张三',
|
||||
isGroup: true,
|
||||
isSelf: false,
|
||||
type: 'text',
|
||||
text: '你好,关键词',
|
||||
mentionsMe: false,
|
||||
timestamp: NOW,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
test('exact 模式比较 trim 后的完整文本', () => {
|
||||
const rule = { keyword: '关键词', mode: 'exact' }
|
||||
assert.equal(matchRule(' 关键词 ', rule), true)
|
||||
assert.equal(matchRule('你好,关键词', rule), false)
|
||||
})
|
||||
|
||||
test('exact 模式不匹配大小写不同的关键词之外的差异', () => {
|
||||
const rule = { keyword: 'Hello', mode: 'exact' }
|
||||
assert.equal(matchRule('hello', rule), true)
|
||||
assert.equal(matchRule('hello world', rule), false)
|
||||
})
|
||||
|
||||
test('contains 模式匹配任意位置的子串', () => {
|
||||
const rule = { keyword: '关键词', mode: 'contains' }
|
||||
assert.equal(matchRule('前面的关键词后面', rule), true)
|
||||
assert.equal(matchRule('完全无关', rule), false)
|
||||
})
|
||||
|
||||
test('prefix 模式只匹配开头', () => {
|
||||
const rule = { keyword: '你好', mode: 'prefix' }
|
||||
assert.equal(matchRule(' 你好世界', rule), true)
|
||||
assert.equal(matchRule('世界你好', rule), false)
|
||||
})
|
||||
|
||||
test('匹配对大小写不敏感', () => {
|
||||
assert.equal(matchRule('Say HELLO now', { keyword: 'hello', mode: 'contains' }), true)
|
||||
assert.equal(matchRule('HELLO WORLD', { keyword: 'hello', mode: 'prefix' }), true)
|
||||
})
|
||||
|
||||
test('空关键词在任何模式下都不命中', () => {
|
||||
for (const mode of ['contains', 'exact', 'prefix']) {
|
||||
assert.equal(matchRule('任意文本', { keyword: ' ', mode }), false)
|
||||
assert.equal(matchRule('', { keyword: '', mode }), false)
|
||||
}
|
||||
})
|
||||
|
||||
test('pickRule 跳过禁用规则', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'disabled', keyword: '关键词', reply: '不会发送', enabled: false },
|
||||
{ id: 'active', keyword: '关键词', reply: '会发送' }
|
||||
]
|
||||
})
|
||||
const rule = pickRule('关键词', config)
|
||||
assert.equal(rule.id, 'active')
|
||||
})
|
||||
|
||||
test('pickRule 按 priority 降序选择', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'low', keyword: '关键词', reply: '低', priority: 10 },
|
||||
{ id: 'high', keyword: '关键词', reply: '高', priority: 90 }
|
||||
]
|
||||
})
|
||||
assert.equal(pickRule('关键词', config).id, 'high')
|
||||
})
|
||||
|
||||
test('同优先级保持数组顺序(先定义先命中)', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'first', keyword: '关键词', reply: '一', priority: 50 },
|
||||
{ id: 'second', keyword: '关键词', reply: '二', priority: 50 }
|
||||
]
|
||||
})
|
||||
assert.equal(pickRule('关键词', config).id, 'first')
|
||||
})
|
||||
|
||||
test('同一条消息只返回一个规则(stopOnMatch)', () => {
|
||||
const config = buildConfig({
|
||||
rules: [
|
||||
{ id: 'a', keyword: '关键词', reply: '一', priority: 1 },
|
||||
{ id: 'b', keyword: '关键词', reply: '二', priority: 2 }
|
||||
]
|
||||
})
|
||||
const rule = pickRule('关键词 关键词', config)
|
||||
assert.equal(rule.id, 'b')
|
||||
})
|
||||
|
||||
test('群范围命中指定群', () => {
|
||||
const config = buildConfig({ scope: { groups: [GROUP_ID] } })
|
||||
assert.equal(inScope(buildEvent(), config), true)
|
||||
})
|
||||
|
||||
test('群范围排除未列出的群', () => {
|
||||
const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } })
|
||||
assert.equal(inScope(buildEvent(), config), false)
|
||||
})
|
||||
|
||||
test('groups 为空表示全部群聊', () => {
|
||||
const config = buildConfig({ scope: { groups: [] } })
|
||||
assert.equal(inScope(buildEvent(), config), true)
|
||||
})
|
||||
|
||||
test('includeDirect 为 false 时不处理私聊', () => {
|
||||
const closed = buildConfig({ scope: { groups: [], includeDirect: false } })
|
||||
const open = buildConfig({ scope: { groups: [], includeDirect: true } })
|
||||
const direct = buildEvent({ isGroup: false, conversationId: 'wxid_fixture' })
|
||||
assert.equal(inScope(direct, closed), false)
|
||||
assert.equal(inScope(direct, open), true)
|
||||
})
|
||||
|
||||
test('requireMentionMe 只放行真正 @ 我的消息', () => {
|
||||
const config = buildConfig({ scope: { groups: [], requireMentionMe: true } })
|
||||
assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'mention')
|
||||
assert.equal(shouldReply(buildEvent({ mentionsMe: true }), config, new Map(), NOW).reason, 'ok')
|
||||
})
|
||||
|
||||
test('自己发的消息不回复', () => {
|
||||
const verdict = shouldReply(buildEvent({ isSelf: true }), buildConfig(), new Map(), NOW)
|
||||
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'self' })
|
||||
})
|
||||
|
||||
test('非文本消息不回复', () => {
|
||||
const verdict = shouldReply(buildEvent({ type: 'image' }), buildConfig(), new Map(), NOW)
|
||||
assert.equal(verdict.reason, 'type')
|
||||
})
|
||||
|
||||
test('总开关关闭时不回复', () => {
|
||||
const config = buildConfig({ enabled: false })
|
||||
assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'disabled')
|
||||
assert.equal(shouldReply(buildEvent(), null, new Map(), NOW).reason, 'disabled')
|
||||
})
|
||||
|
||||
test('没有命中规则时 reason 为 no_match', () => {
|
||||
const verdict = shouldReply(buildEvent({ text: '无关内容' }), buildConfig(), new Map(), NOW)
|
||||
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'no_match' })
|
||||
})
|
||||
|
||||
test('冷却中不回复', () => {
|
||||
const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW + 30_000]])
|
||||
const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW)
|
||||
assert.deepEqual(verdict, { reply: false, rule: null, reason: 'cooldown' })
|
||||
})
|
||||
|
||||
test('冷却过期后恢复回复', () => {
|
||||
const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW]])
|
||||
const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW)
|
||||
assert.equal(verdict.reply, true)
|
||||
assert.equal(verdict.reason, 'ok')
|
||||
assert.equal(verdict.rule.id, 'rule-1')
|
||||
})
|
||||
|
||||
test('冷却表也支持普通对象', () => {
|
||||
const cooldown = { [`${GROUP_ID}:rule-1`]: NOW + 1 }
|
||||
assert.equal(shouldReply(buildEvent(), buildConfig(), cooldown, NOW).reason, 'cooldown')
|
||||
assert.equal(shouldReply(buildEvent(), buildConfig(), {}, NOW).reason, 'ok')
|
||||
})
|
||||
|
||||
test('模板变量按上下文替换', () => {
|
||||
const text = renderReply('{sender} 说了 {keyword},现在是 {time}', {
|
||||
senderName: '张三',
|
||||
keyword: '关键词',
|
||||
time: '09:05'
|
||||
})
|
||||
assert.equal(text, '张三 说了 关键词,现在是 09:05')
|
||||
})
|
||||
|
||||
test('发送者昵称为空时渲染为「你」', () => {
|
||||
assert.equal(renderReply('{sender}', { senderName: ' ' }), '你')
|
||||
assert.equal(renderReply('{sender}', {}), '你')
|
||||
})
|
||||
|
||||
test('未知变量原样保留', () => {
|
||||
const text = renderReply('{sender} 和 {group}', { senderName: '李四' })
|
||||
assert.equal(text, '李四 和 {group}')
|
||||
})
|
||||
|
||||
test('模板缺失的时间变量渲染为空串', () => {
|
||||
assert.equal(renderReply('[{time}]', {}), '[]')
|
||||
})
|
||||
|
||||
test('渲染结果 trim 后截断到 2000 字符', () => {
|
||||
const input = ` ${'长'.repeat(2100)} `
|
||||
const text = renderReply(input, {})
|
||||
assert.equal(text.length, 2000)
|
||||
assert.equal(text, '长'.repeat(2000))
|
||||
})
|
||||
|
||||
test('v1 配置迁移补齐 enabled / priority 与 configVersion', () => {
|
||||
const config = normalizeConfig({
|
||||
enabled: true,
|
||||
rules: [{ id: 'old', keyword: '关键词', mode: 'contains', reply: '旧规则' }],
|
||||
scope: { groups: ['fixture-room@chatroom'] }
|
||||
})
|
||||
assert.equal(config.configVersion, 2)
|
||||
assert.equal(config.rules.length, 1)
|
||||
assert.equal(config.rules[0].enabled, true)
|
||||
assert.equal(config.rules[0].priority, 0)
|
||||
assert.equal(config.scope.includeDirect, true)
|
||||
assert.equal(config.scope.requireMentionMe, false)
|
||||
})
|
||||
|
||||
test('keyword 或 reply 为空的启用规则被丢弃,停用草稿保留', () => {
|
||||
const config = normalizeConfig({
|
||||
enabled: true,
|
||||
rules: [
|
||||
{ id: 'no-keyword', keyword: ' ', reply: '有回复' },
|
||||
{ id: 'no-reply', keyword: '有词', reply: ' ' },
|
||||
{ id: 'draft', keyword: '', reply: '', enabled: false },
|
||||
{ id: 'ok', keyword: '有词', reply: '有回复' }
|
||||
]
|
||||
})
|
||||
assert.deepEqual(
|
||||
config.rules.map((rule) => rule.id),
|
||||
['draft', 'ok']
|
||||
)
|
||||
})
|
||||
|
||||
test('非对象与缺失字段的配置退化为未启用空配置', () => {
|
||||
for (const raw of [null, undefined, 'broken', 42, []]) {
|
||||
const config = normalizeConfig(raw)
|
||||
assert.equal(config.configVersion, 2)
|
||||
assert.equal(config.enabled, false)
|
||||
assert.deepEqual(config.rules, [])
|
||||
assert.deepEqual(config.scope, { groups: [], includeDirect: true, requireMentionMe: false })
|
||||
}
|
||||
})
|
||||
|
||||
test('越界数值收敛到边界,非法值按 0', () => {
|
||||
const config = normalizeConfig({
|
||||
rules: [
|
||||
{ id: 'clamp-high', keyword: '一', reply: '一', cooldownSeconds: 99_999, priority: 999 },
|
||||
{ id: 'clamp-low', keyword: '二', reply: '二', cooldownSeconds: -5, priority: -5 },
|
||||
{ id: 'nan', keyword: '三', reply: '三', cooldownSeconds: 'oops', priority: 'oops' }
|
||||
]
|
||||
})
|
||||
assert.equal(config.rules[0].cooldownSeconds, 3600)
|
||||
assert.equal(config.rules[0].priority, 100)
|
||||
assert.equal(config.rules[1].cooldownSeconds, 0)
|
||||
assert.equal(config.rules[1].priority, 0)
|
||||
assert.equal(config.rules[2].cooldownSeconds, 0)
|
||||
assert.equal(config.rules[2].priority, 0)
|
||||
})
|
||||
|
||||
test('群范围过滤先于规则匹配,范围外不产生命中', () => {
|
||||
const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } })
|
||||
const verdict = shouldReply(buildEvent(), config, new Map(), NOW)
|
||||
assert.equal(verdict.reason, 'scope')
|
||||
assert.equal(verdict.rule, null)
|
||||
})
|
||||
@@ -0,0 +1,495 @@
|
||||
const EXTENSION_ID = 'com.example.keyword-bot'
|
||||
const PAGE_SOURCE = 'tracememo-extension-page'
|
||||
const HOST_SOURCE = 'tracememo-extension-host'
|
||||
const CONFIG_KEY = 'config'
|
||||
const STATS_KEY = 'stats'
|
||||
const CONFIG_VERSION = 2
|
||||
const MAX_KEYWORD_LENGTH = 120
|
||||
const MAX_REPLY_LENGTH = 2000
|
||||
const STATS_PREVIEW = 5
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: false,
|
||||
rules: [
|
||||
{
|
||||
id: 'rule-1',
|
||||
keyword: '你好',
|
||||
mode: 'contains',
|
||||
reply: '你好呀,{sender}!',
|
||||
cooldownSeconds: 30,
|
||||
enabled: true,
|
||||
priority: 0
|
||||
}
|
||||
],
|
||||
scope: { groups: [], includeDirect: true, requireMentionMe: false }
|
||||
}
|
||||
|
||||
const pending = new Map()
|
||||
let sequence = 0
|
||||
let config = clone(DEFAULT_CONFIG)
|
||||
|
||||
function clone(value) {
|
||||
return JSON.parse(JSON.stringify(value))
|
||||
}
|
||||
|
||||
function callHost(method, params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const requestId = `req-${++sequence}`
|
||||
pending.set(requestId, { resolve, reject })
|
||||
window.parent.postMessage(
|
||||
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params },
|
||||
'*'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
const data = event.data
|
||||
if (!data || data.source !== HOST_SOURCE) return
|
||||
const entry = pending.get(data.requestId)
|
||||
if (!entry) return
|
||||
pending.delete(data.requestId)
|
||||
if (data.ok) entry.resolve(data.result)
|
||||
else entry.reject(new Error((data.error && data.error.message) || '调用失败'))
|
||||
})
|
||||
|
||||
const rulesContainer = document.getElementById('rules')
|
||||
const status = document.getElementById('status')
|
||||
const statsSummary = document.getElementById('stats-summary')
|
||||
const statsList = document.getElementById('stats-list')
|
||||
const groupPicker = document.getElementById('group-picker')
|
||||
const groupChips = document.getElementById('group-chips')
|
||||
const groupSearch = document.getElementById('group-search')
|
||||
const groupOptions = document.getElementById('group-options')
|
||||
|
||||
let allGroups = []
|
||||
let selectedGroupIds = new Set()
|
||||
let groupLoadError = ''
|
||||
|
||||
function groupDisplayName(group) {
|
||||
if (!group) return ''
|
||||
return group.name && group.name !== group.id ? `${group.name}(${group.id})` : group.id
|
||||
}
|
||||
|
||||
function renderGroupChips() {
|
||||
groupChips.textContent = ''
|
||||
groupChips.hidden = selectedGroupIds.size === 0
|
||||
for (const id of selectedGroupIds) {
|
||||
const group = allGroups.find((item) => item.id === id)
|
||||
const chip = document.createElement('span')
|
||||
chip.className = 'group-chip'
|
||||
const name = document.createElement('span')
|
||||
name.textContent = group ? group.name || id : id
|
||||
name.title = id
|
||||
const remove = document.createElement('button')
|
||||
remove.type = 'button'
|
||||
remove.className = 'group-chip-remove'
|
||||
remove.textContent = '×'
|
||||
remove.setAttribute('aria-label', `移除 ${group ? group.name || id : id}`)
|
||||
remove.addEventListener('click', (event) => {
|
||||
event.stopPropagation()
|
||||
selectedGroupIds.delete(id)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
})
|
||||
chip.append(name, remove)
|
||||
groupChips.append(chip)
|
||||
}
|
||||
}
|
||||
|
||||
function renderGroupOptions() {
|
||||
if (groupOptions.hidden) return
|
||||
const query = groupSearch.value.trim().toLowerCase()
|
||||
groupOptions.textContent = ''
|
||||
if (groupLoadError) {
|
||||
groupOptions.append(emptyGroupOption(groupLoadError))
|
||||
return
|
||||
}
|
||||
if (!allGroups.length) {
|
||||
groupOptions.append(emptyGroupOption('未读取到群列表(请先连接微信数据库)'))
|
||||
return
|
||||
}
|
||||
const matches = allGroups.filter((group) => {
|
||||
if (!query) return true
|
||||
return group.id.toLowerCase().includes(query) || group.name.toLowerCase().includes(query)
|
||||
})
|
||||
if (!matches.length) {
|
||||
groupOptions.append(emptyGroupOption('没有匹配的群聊'))
|
||||
return
|
||||
}
|
||||
for (const group of matches.slice(0, 200)) {
|
||||
const option = document.createElement('label')
|
||||
option.className = 'group-option'
|
||||
const checkbox = document.createElement('input')
|
||||
checkbox.type = 'checkbox'
|
||||
checkbox.checked = selectedGroupIds.has(group.id)
|
||||
checkbox.addEventListener('change', () => {
|
||||
if (checkbox.checked) selectedGroupIds.add(group.id)
|
||||
else selectedGroupIds.delete(group.id)
|
||||
renderGroupChips()
|
||||
})
|
||||
const text = document.createElement('span')
|
||||
text.textContent = groupDisplayName(group)
|
||||
option.append(checkbox, text)
|
||||
groupOptions.append(option)
|
||||
}
|
||||
}
|
||||
|
||||
function emptyGroupOption(text) {
|
||||
const empty = document.createElement('div')
|
||||
empty.className = 'group-option-empty'
|
||||
empty.textContent = text
|
||||
return empty
|
||||
}
|
||||
|
||||
function openGroupOptions() {
|
||||
groupOptions.hidden = false
|
||||
renderGroupOptions()
|
||||
}
|
||||
|
||||
function closeGroupOptions() {
|
||||
groupOptions.hidden = true
|
||||
groupSearch.value = ''
|
||||
}
|
||||
|
||||
groupSearch.addEventListener('focus', openGroupOptions)
|
||||
groupSearch.addEventListener('input', openGroupOptions)
|
||||
groupSearch.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape') {
|
||||
closeGroupOptions()
|
||||
groupSearch.blur()
|
||||
}
|
||||
})
|
||||
document.addEventListener('click', (event) => {
|
||||
if (!groupPicker.contains(event.target)) closeGroupOptions()
|
||||
})
|
||||
|
||||
async function loadGroups() {
|
||||
try {
|
||||
const result = await callHost('contacts.listGroups', {})
|
||||
allGroups = result && Array.isArray(result.groups) ? result.groups : []
|
||||
groupLoadError = ''
|
||||
} catch (error) {
|
||||
allGroups = []
|
||||
groupLoadError = `群列表读取失败:${error.message}`
|
||||
}
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
}
|
||||
|
||||
function setStatus(text, kind) {
|
||||
status.textContent = text
|
||||
status.dataset.kind = kind || ''
|
||||
}
|
||||
|
||||
function clampInteger(value, min, max, fallback) {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return fallback
|
||||
return Math.min(Math.max(Math.round(numeric), min), max)
|
||||
}
|
||||
|
||||
function newRuleId() {
|
||||
return `rule-${Date.now().toString(36)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面侧的轻量规范化:只用于展示与回写,真正的判定在后台 lib/matcher.js。
|
||||
* 缺字段一律补默认值,保证 v1 配置打开后能直接编辑。
|
||||
*/
|
||||
function normalizeRule(rule, index) {
|
||||
const source = rule && typeof rule === 'object' ? rule : {}
|
||||
return {
|
||||
id: String(source.id || `rule-${index + 1}`).slice(0, 64),
|
||||
keyword: String(source.keyword == null ? '' : source.keyword).slice(0, MAX_KEYWORD_LENGTH),
|
||||
mode: ['contains', 'exact', 'prefix'].includes(source.mode) ? source.mode : 'contains',
|
||||
reply: String(source.reply == null ? '' : source.reply).slice(0, MAX_REPLY_LENGTH),
|
||||
cooldownSeconds: clampInteger(source.cooldownSeconds, 0, 3600, 0),
|
||||
enabled: source.enabled !== false,
|
||||
priority: clampInteger(source.priority, 0, 100, 0)
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeStoredConfig(stored) {
|
||||
if (!stored || typeof stored !== 'object') return clone(DEFAULT_CONFIG)
|
||||
const scope = stored.scope && typeof stored.scope === 'object' ? stored.scope : {}
|
||||
return {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: stored.enabled === true,
|
||||
rules: Array.isArray(stored.rules)
|
||||
? stored.rules.map(normalizeRule)
|
||||
: clone(DEFAULT_CONFIG.rules),
|
||||
scope: {
|
||||
groups: Array.isArray(scope.groups)
|
||||
? scope.groups.map((id) => String(id).trim()).filter(Boolean)
|
||||
: [],
|
||||
includeDirect: scope.includeDirect !== false,
|
||||
requireMentionMe: scope.requireMentionMe === true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function field(label, control) {
|
||||
const wrapper = document.createElement('label')
|
||||
wrapper.className = 'field'
|
||||
const caption = document.createElement('span')
|
||||
caption.textContent = label
|
||||
wrapper.append(caption, control)
|
||||
return wrapper
|
||||
}
|
||||
|
||||
function renderRules() {
|
||||
rulesContainer.textContent = ''
|
||||
config.rules.forEach((rule, index) => {
|
||||
const card = document.createElement('article')
|
||||
card.className = 'rule-card'
|
||||
if (!rule.enabled) card.classList.add('is-disabled')
|
||||
|
||||
const head = document.createElement('div')
|
||||
head.className = 'rule-head'
|
||||
const title = document.createElement('strong')
|
||||
title.textContent = `规则 ${index + 1}`
|
||||
const toggle = document.createElement('label')
|
||||
toggle.className = 'check'
|
||||
const enabledInput = document.createElement('input')
|
||||
enabledInput.type = 'checkbox'
|
||||
enabledInput.checked = rule.enabled
|
||||
enabledInput.addEventListener('change', () => {
|
||||
rule.enabled = enabledInput.checked
|
||||
card.classList.toggle('is-disabled', !rule.enabled)
|
||||
})
|
||||
const toggleText = document.createElement('span')
|
||||
toggleText.textContent = '启用'
|
||||
toggle.append(enabledInput, toggleText)
|
||||
const remove = document.createElement('button')
|
||||
remove.type = 'button'
|
||||
remove.className = 'ghost danger'
|
||||
remove.textContent = '删除'
|
||||
remove.addEventListener('click', () => {
|
||||
config.rules.splice(index, 1)
|
||||
renderRules()
|
||||
})
|
||||
const headActions = document.createElement('div')
|
||||
headActions.className = 'rule-head-actions'
|
||||
headActions.append(toggle, remove)
|
||||
head.append(title, headActions)
|
||||
|
||||
const keywordInput = document.createElement('input')
|
||||
keywordInput.type = 'text'
|
||||
keywordInput.maxLength = MAX_KEYWORD_LENGTH
|
||||
keywordInput.value = rule.keyword
|
||||
keywordInput.addEventListener('input', () => {
|
||||
rule.keyword = keywordInput.value
|
||||
})
|
||||
|
||||
const modeSelect = document.createElement('select')
|
||||
;[
|
||||
['contains', '包含'],
|
||||
['exact', '完全匹配'],
|
||||
['prefix', '以…开头']
|
||||
].forEach(([value, label]) => {
|
||||
const option = document.createElement('option')
|
||||
option.value = value
|
||||
option.textContent = label
|
||||
option.selected = rule.mode === value
|
||||
modeSelect.append(option)
|
||||
})
|
||||
modeSelect.addEventListener('change', () => {
|
||||
rule.mode = modeSelect.value
|
||||
})
|
||||
|
||||
const replyInput = document.createElement('textarea')
|
||||
replyInput.rows = 2
|
||||
replyInput.maxLength = MAX_REPLY_LENGTH
|
||||
replyInput.value = rule.reply
|
||||
replyInput.addEventListener('input', () => {
|
||||
rule.reply = replyInput.value
|
||||
})
|
||||
const replyBlock = field('回复内容', replyInput)
|
||||
const replyHint = document.createElement('p')
|
||||
replyHint.className = 'hint'
|
||||
replyHint.textContent =
|
||||
'可用变量:{sender}(发送者)、{keyword}(命中词)、{time}(当前时间 HH:mm)'
|
||||
replyBlock.append(replyHint)
|
||||
|
||||
const cooldownInput = document.createElement('input')
|
||||
cooldownInput.type = 'number'
|
||||
cooldownInput.min = '0'
|
||||
cooldownInput.max = '3600'
|
||||
cooldownInput.value = String(rule.cooldownSeconds)
|
||||
cooldownInput.addEventListener('change', () => {
|
||||
rule.cooldownSeconds = clampInteger(cooldownInput.value, 0, 3600, 0)
|
||||
cooldownInput.value = String(rule.cooldownSeconds)
|
||||
})
|
||||
|
||||
const priorityInput = document.createElement('input')
|
||||
priorityInput.type = 'number'
|
||||
priorityInput.min = '0'
|
||||
priorityInput.max = '100'
|
||||
priorityInput.step = '1'
|
||||
priorityInput.value = String(rule.priority)
|
||||
priorityInput.addEventListener('change', () => {
|
||||
rule.priority = clampInteger(priorityInput.value, 0, 100, 0)
|
||||
priorityInput.value = String(rule.priority)
|
||||
})
|
||||
|
||||
const numberRow = document.createElement('div')
|
||||
numberRow.className = 'field-row'
|
||||
const cooldownField = field('冷却时间(秒)', cooldownInput)
|
||||
const priorityField = field('优先级(0–100,越大越先匹配)', priorityInput)
|
||||
numberRow.append(cooldownField, priorityField)
|
||||
|
||||
card.append(
|
||||
head,
|
||||
field('关键词', keywordInput),
|
||||
field('匹配方式', modeSelect),
|
||||
replyBlock,
|
||||
numberRow
|
||||
)
|
||||
rulesContainer.append(card)
|
||||
})
|
||||
}
|
||||
|
||||
function syncForm() {
|
||||
document.getElementById('enabled').checked = config.enabled === true
|
||||
selectedGroupIds = new Set(config.scope.groups)
|
||||
renderGroupChips()
|
||||
renderGroupOptions()
|
||||
document.getElementById('include-direct').checked = config.scope.includeDirect !== false
|
||||
document.getElementById('require-mention').checked = config.scope.requireMentionMe === true
|
||||
renderRules()
|
||||
}
|
||||
|
||||
function readForm() {
|
||||
config.enabled = document.getElementById('enabled').checked
|
||||
config.scope.groups = [...selectedGroupIds].slice(0, 200)
|
||||
config.scope.includeDirect = document.getElementById('include-direct').checked
|
||||
config.scope.requireMentionMe = document.getElementById('require-mention').checked
|
||||
}
|
||||
|
||||
function localDateKey(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${month}-${day}`
|
||||
}
|
||||
|
||||
function formatClock(timestamp) {
|
||||
const date = new Date(timestamp)
|
||||
const hour = String(date.getHours()).padStart(2, '0')
|
||||
const minute = String(date.getMinutes()).padStart(2, '0')
|
||||
return `${hour}:${minute}`
|
||||
}
|
||||
|
||||
/** 统计展示:只读 storage,不参与任何写入。 */
|
||||
function renderStats(raw) {
|
||||
statsList.textContent = ''
|
||||
const now = Date.now()
|
||||
const sameDay = raw && raw.dateKey === localDateKey(now)
|
||||
const todayCount = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0
|
||||
const hits = raw && Array.isArray(raw.lastHits) ? raw.lastHits.filter((hit) => hit && hit.at) : []
|
||||
|
||||
if (!hits.length && todayCount === 0) {
|
||||
statsSummary.textContent = '暂无命中记录'
|
||||
return
|
||||
}
|
||||
statsSummary.textContent = `今日命中 ${todayCount} 次`
|
||||
|
||||
hits
|
||||
.slice(-STATS_PREVIEW)
|
||||
.reverse()
|
||||
.forEach((hit) => {
|
||||
const item = document.createElement('li')
|
||||
item.className = 'stats-item'
|
||||
const time = document.createElement('span')
|
||||
time.textContent = formatClock(Number(hit.at))
|
||||
const ruleId = document.createElement('code')
|
||||
ruleId.textContent = String(hit.ruleId || '未知规则')
|
||||
const result = document.createElement('span')
|
||||
result.className = hit.ok === true ? 'stats-ok' : 'stats-fail'
|
||||
result.textContent = hit.ok === true ? '成功' : '失败'
|
||||
item.append(time, ruleId, result)
|
||||
statsList.append(item)
|
||||
})
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
try {
|
||||
const stored = await callHost('storage.get', { key: STATS_KEY })
|
||||
renderStats(stored)
|
||||
} catch (error) {
|
||||
renderStats(null)
|
||||
setStatus(`统计读取失败:${error.message}`, 'error')
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('add-rule').addEventListener('click', () => {
|
||||
config.rules.push({
|
||||
id: newRuleId(),
|
||||
keyword: '',
|
||||
mode: 'contains',
|
||||
reply: '',
|
||||
cooldownSeconds: 30,
|
||||
enabled: true,
|
||||
priority: 0
|
||||
})
|
||||
renderRules()
|
||||
})
|
||||
|
||||
document.getElementById('save').addEventListener('click', async () => {
|
||||
readForm()
|
||||
// 只有启用中的规则必须有内容:停用的草稿允许留空,方便先存后写。
|
||||
const invalid = config.rules.find(
|
||||
(rule) => rule.enabled && (!rule.keyword.trim() || !rule.reply.trim())
|
||||
)
|
||||
if (invalid) {
|
||||
setStatus('启用中的规则都需要关键词和回复内容;也可以先取消启用再保存。', 'error')
|
||||
return
|
||||
}
|
||||
const payload = {
|
||||
configVersion: CONFIG_VERSION,
|
||||
enabled: config.enabled === true,
|
||||
rules: config.rules.map(normalizeRule),
|
||||
scope: {
|
||||
groups: config.scope.groups.slice(0, 200),
|
||||
includeDirect: config.scope.includeDirect !== false,
|
||||
requireMentionMe: config.scope.requireMentionMe === true
|
||||
}
|
||||
}
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: payload })
|
||||
// 回写规范化结果但保留原对象引用:卡片上的输入事件仍在改这些对象。
|
||||
payload.rules.forEach((rule, index) => Object.assign(config.rules[index], rule))
|
||||
config.configVersion = CONFIG_VERSION
|
||||
setStatus('配置已保存。后台进程会在下一次收到消息时生效。', 'ok')
|
||||
loadStats()
|
||||
} catch (error) {
|
||||
setStatus(`保存失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('reset').addEventListener('click', async () => {
|
||||
config = clone(DEFAULT_CONFIG)
|
||||
syncForm()
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: config })
|
||||
setStatus('已恢复默认配置。', 'ok')
|
||||
} catch (error) {
|
||||
setStatus(`重置失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('refresh-stats').addEventListener('click', () => {
|
||||
loadStats()
|
||||
})
|
||||
|
||||
async function boot() {
|
||||
const stored = await callHost('storage.get', { key: CONFIG_KEY })
|
||||
config = normalizeStoredConfig(stored)
|
||||
syncForm()
|
||||
await loadGroups()
|
||||
setStatus('配置已读取。默认不启用,避免安装后立即对外发送。')
|
||||
loadStats()
|
||||
}
|
||||
|
||||
boot().catch((error) => setStatus(`加载失败:${error.message}`, 'error'))
|
||||
@@ -0,0 +1,71 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>关键词回复机器人</title>
|
||||
<link rel="stylesheet" href="./style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>关键词回复机器人</h1>
|
||||
<p>收到文本消息后按规则匹配,命中即经 TraceMemo Gateway 回复。本页只写配置,不直接发送。</p>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input id="enabled" type="checkbox" />
|
||||
<span>启用机器人</span>
|
||||
</label>
|
||||
</header>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>关键词规则</h2>
|
||||
<button id="add-rule" type="button" class="ghost">添加规则</button>
|
||||
</div>
|
||||
<div id="rules" class="rules"></div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>监听范围</h2>
|
||||
<div class="field">
|
||||
<span>只监听这些群聊(可多选、可搜索;留空表示全部群聊)</span>
|
||||
<div id="group-picker" class="group-picker">
|
||||
<div id="group-chips" class="group-chips" hidden></div>
|
||||
<input
|
||||
id="group-search"
|
||||
type="text"
|
||||
placeholder="搜索群聊名称或 id…"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<div id="group-options" class="group-options" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="check"><input id="include-direct" type="checkbox" /><span>同时处理私聊</span></label>
|
||||
<label class="check"><input id="require-mention" type="checkbox" /><span>只处理真正 @ 我的消息</span></label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-header">
|
||||
<h2>运行统计</h2>
|
||||
<button id="refresh-stats" type="button" class="ghost">刷新</button>
|
||||
</div>
|
||||
<p id="stats-summary" class="stats-summary">暂无命中记录</p>
|
||||
<ul id="stats-list" class="stats-list"></ul>
|
||||
<p class="hint">统计只记录规则编号、命中时间与发送结果,不含会话、昵称与消息正文。</p>
|
||||
</section>
|
||||
|
||||
<footer class="page-footer">
|
||||
<div class="row">
|
||||
<button id="save" type="button" class="primary">保存配置</button>
|
||||
<button id="reset" type="button" class="ghost">恢复默认</button>
|
||||
</div>
|
||||
<p id="status" class="status" role="status"></p>
|
||||
</footer>
|
||||
</main>
|
||||
<script src="./app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,384 @@
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--bg: #f6f8f7;
|
||||
--card: #ffffff;
|
||||
--text: #1c2622;
|
||||
--muted: #6b7a73;
|
||||
--border: #dfe6e2;
|
||||
--brand: #247a63;
|
||||
--danger: #b4472f;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #161c19;
|
||||
--card: #1e2622;
|
||||
--text: #eef4f1;
|
||||
--muted: #9aaba3;
|
||||
--border: #33403a;
|
||||
--brand: #4bb894;
|
||||
--danger: #e0735a;
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei',
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 720px;
|
||||
margin: 0 auto;
|
||||
padding: 26px 22px 40px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 19px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
header p {
|
||||
margin: 8px 0 0;
|
||||
max-width: 52ch;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 19px;
|
||||
}
|
||||
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--card);
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.rules {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.rule-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.rule-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.rule-head-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.rule-card.is-disabled {
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.rule-card.is-disabled .field,
|
||||
.rule-card.is-disabled .field-row {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.field-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
.stats-summary {
|
||||
margin: 0;
|
||||
color: var(--text);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stats-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.stats-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stats-ok {
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.stats-fail {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.field-row {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.field > span {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
input[type='text'],
|
||||
input[type='number'],
|
||||
select,
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.check,
|
||||
.switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.switch {
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 6px 11px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.primary {
|
||||
border-color: transparent;
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
button.ghost:hover {
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
button.danger {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.page-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.status {
|
||||
min-height: 18px;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.status[data-kind='ok'] {
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.status[data-kind='error'] {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
code {
|
||||
padding: 1px 4px;
|
||||
border-radius: 4px;
|
||||
background: var(--bg);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* 群聊多选:chips + 搜索框 + 复选下拉。 */
|
||||
.group-picker {
|
||||
position: relative;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--card);
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.group-picker:focus-within {
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
.group-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.group-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
max-width: 100%;
|
||||
padding: 2px 4px 2px 8px;
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.group-chip > span {
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.group-chip-remove {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.group-chip-remove:hover {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.group-picker > input[type='text'] {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
padding: 4px 2px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.group-options {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: calc(100% + 4px);
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
padding: 4px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--card);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.group-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 6px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.group-option:hover {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.group-option input {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.group-option-empty {
|
||||
padding: 8px 6px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
Reference in new issue
Block a user