From 4e21604e2dc067f8bc6ab04ce7d1fda7cbd28bd9 Mon Sep 17 00:00:00 2001 From: lizheming Date: Thu, 26 Nov 2026 23:47:28 +0800 Subject: [PATCH 1/2] feat(say): automatically merge compatible recent messages --- packages/say/README.md | 6 ++++ packages/say/lib/publish-feedback.js | 2 +- packages/say/lib/say-service.js | 28 +++++++++++++++++++ packages/say/plugin.js | 1 + packages/say/test/admin-settings.test.js | 2 +- packages/say/test/say-service.test.js | 35 ++++++++++++++++++++++-- 6 files changed, 70 insertions(+), 4 deletions(-) diff --git a/packages/say/README.md b/packages/say/README.md index 31d23e7..1a07b2e 100644 --- a/packages/say/README.md +++ b/packages/say/README.md @@ -651,3 +651,9 @@ QQ 附件下载失败时,参考编号对应日志中的 `download` 会记录 此示例只排版文字,图片/语音/链接等可按 `kind` 自行渲染,或继续使用完整的 `html.items`。 链接规则保持兼容:详情始终为 `/says/ID`,标签链接为 URL 编码后的 `/says/tag/标签`;分页保留当前列表路径,并保留既有 `page` 和 `tag` 查询参数。`/says?tag=标签` 的分页仍指向 `/says?page=N&tag=标签`,不会被改成标签路径。主题直接使用提供的 URL,无需自行编码标签或猜测相邻条目。 + +### 自动合并连续发布 + +后台“自动合并间隔”默认 10 秒,可设置为 0 关闭(最大 86400 秒)。新发布内容与历史最新一条碎语的原始发布时间相差不超过该值时,按现有手动合并规则尝试合并;例如文字加图片、连续图片、文字加语音或位置。两条纯文字不会自动拼接。 + +仅同作者、同来源、同可见性和同评论开关的内容参与自动合并;已有评论或合并后超过 20 张图片时正常新增。不跳过最新记录向更早的记录查找。合并保留原 ID 和发布时间,后续消息仍以该发布时间计算间隔;渠道回复显示合并后的 ID。此设置适用于后台、API 和各渠道的统一创建入口。 diff --git a/packages/say/lib/publish-feedback.js b/packages/say/lib/publish-feedback.js index 469122e..eb6a6e3 100644 --- a/packages/say/lib/publish-feedback.js +++ b/packages/say/lib/publish-feedback.js @@ -153,7 +153,7 @@ function reference(key) { } function success(item, action = 'publish') { - return action === 'merge' ? `✅ 已合并为碎语 #${item.id}。` : `✅ 发布成功,碎语 #${item.id}。`; + return action === 'merge' || item.autoMerged ? `✅ 已合并为碎语 #${item.id}。` : `✅ 发布成功,碎语 #${item.id}。`; } function failure(error, key, logger) { diff --git a/packages/say/lib/say-service.js b/packages/say/lib/say-service.js index 14ff276..3479ce9 100644 --- a/packages/say/lib/say-service.js +++ b/packages/say/lib/say-service.js @@ -9,6 +9,7 @@ const STATUSES = new Set(['public', 'private', 'hidden']); const DEFAULT_SETTINGS = Object.freeze({ enabled: true, pageSize: 10, + autoMergeSeconds: 10, apiKey: '', authorId: 1, amapKey: '', @@ -66,6 +67,7 @@ function normalizeSettings(value = {}, previous = {}) { ? value.qqAppSecret.trim().slice(0, 256) : prior.qqAppSecret, enabled: typeof value.enabled === 'boolean' ? value.enabled : prior.enabled, pageSize: integer(value.pageSize, prior.pageSize, 1, 100), + autoMergeSeconds: integer(value.autoMergeSeconds, prior.autoMergeSeconds, 0, 86400), apiKey: typeof value.apiKey === 'string' && value.apiKey ? value.apiKey.slice(0, 256) : prior.apiKey, authorId: integer(value.authorId, prior.authorId, 1, Number.MAX_SAFE_INTEGER), amapKey: typeof value.amapKey === 'string' ? value.amapKey.trim().slice(0, 256) : prior.amapKey, @@ -262,6 +264,32 @@ class SayService { async create(input, authorId) { const data = normalize(input); const now = this.now(); + const settings = await this.settings(); + if (settings.autoMergeSeconds > 0) { + const rows = await this.model().setRelation(false).where({type: SAY_TYPE}) + .order('create_time DESC, id DESC').limit(1).select(); + const latest = rows[0]; + if (latest) { + const previous = decode(latest); + const elapsed = new Date(now).getTime() - new Date(latest.create_time).getTime(); + if (elapsed >= 0 && elapsed <= settings.autoMergeSeconds * 1000 && + Number(latest.user_id) === integer(authorId, 1, 1, Number.MAX_SAFE_INTEGER) && + previous.status === data.status && previous.source === data.source && + previous.allowComments === data.allowComments) { + let merged; + try { + await this.assertNoComments([latest.id]); + merged = mergeData([previous, data]); + } catch (error) { + if (![400, 409].includes(error.status)) throw error; + } + if (merged && (merged.images || []).length <= 20) { + const item = await this.update(latest.id, merged); + return {...item, autoMerged: true}; + } + } + } + } const visibility = databaseStatus(data.status); const token = crypto.randomBytes(6).toString('hex'); const options = JSON.stringify({say: data}); diff --git a/packages/say/plugin.js b/packages/say/plugin.js index ad7aaf8..5f17aca 100644 --- a/packages/say/plugin.js +++ b/packages/say/plugin.js @@ -541,6 +541,7 @@ module.exports = { ctx.admin.registerForm({id: 'say-basic-settings', page: 'settings', title: '碎语设置', submitLabel: '保存全部设置', fields: [ {name: 'enabled', type: 'switch', label: '启用公开列表和消息发布'}, + {name: 'autoMergeSeconds', type: 'number', label: '自动合并间隔(秒,默认 10,0 关闭,最大 86400)'}, {name: 'pageSize', type: 'number', label: '每页数量', required: true}, {name: 'authorId', type: 'number', label: '发布作者 ID', required: true, description: '外部 API、企业微信、微信公众号、飞书和 QQ 发布的碎语都会归属到这个用户。'}, diff --git a/packages/say/test/admin-settings.test.js b/packages/say/test/admin-settings.test.js index 3a8d55d..58bcec3 100644 --- a/packages/say/test/admin-settings.test.js +++ b/packages/say/test/admin-settings.test.js @@ -9,7 +9,7 @@ function setup(t) { const forms = []; const pages = []; const noop = () => {}; - const settings = {enabled: true, pageSize: 20, authorId: 1, amapKey: 'private-map-key', + const settings = {enabled: true, autoMergeSeconds: 10, pageSize: 20, authorId: 1, amapKey: 'private-map-key', apiKey: 'private-api-key-123456', wecomCorpId: 'corp', wecomCorpSecret: 'private-corp-secret', wecomToken: 'private-corp-token', wecomEncodingAESKey: 'a'.repeat(43), wechatAppId: 'wx_app', wechatAppSecret: 'private-wx-secret', wechatToken: 'private-wx-token', diff --git a/packages/say/test/say-service.test.js b/packages/say/test/say-service.test.js index 4feb698..69d36f7 100644 --- a/packages/say/test/say-service.test.js +++ b/packages/say/test/say-service.test.js @@ -23,7 +23,7 @@ function matches(row, where = {}) { function fixture() { const rows = []; const comments = []; - const options = new Map(); + const options = new Map([['plugin_say_settings', JSON.stringify({autoMergeSeconds: 0})]]); let nextId = 1; class PostModel { setRelation() { return this } @@ -82,7 +82,7 @@ test('normalizes content, tags, URLs and settings', () => { assert.throws(() => normalize({kind: 'unknown', text: 'content'}), /Invalid say kind/); assert.throws(() => normalize({status: 'privte', text: 'content'}), /Invalid say status/); assert.deepEqual(normalizeSettings({pageSize: 999, apiKey: ''}, {apiKey: 'keep'}), - {enabled: true, pageSize: 100, apiKey: 'keep', authorId: 1, amapKey: '', wecomCorpId: '', + {enabled: true, autoMergeSeconds: 10, pageSize: 100, apiKey: 'keep', authorId: 1, amapKey: '', wecomCorpId: '', wecomCorpSecret: '', wecomToken: '', wecomEncodingAESKey: '', wechatAppId: '', wechatAppSecret: '', wechatToken: '', wechatEncodingAESKey: '', wechatAllowedOpenIds: '', feishuAppId: '', feishuAppSecret: '', feishuVerificationToken: '', feishuEncryptKey: '', @@ -236,3 +236,34 @@ test('detail navigation renders only available anchors before comments', () => { assert.doesNotMatch(renderSayPage(result, {navigation: {previous: null, next: null}}), /相邻微博/); assert.doesNotMatch(renderSayPage(result, {navigation: {previous: null, next: 4}}), /rel="prev"/); }); + + +test('automatically merges compatible recent messages and respects the configured window', async() => { + const {service} = fixture(); + await service.saveSettings({autoMergeSeconds: 10}); + const first = await service.create({text: 'caption'}, 1); + service.now = () => '2026-10-14 12:00:10'; + const merged = await service.create({kind: 'image', images: ['https://example.test/a.jpg']}, 1); + assert.equal(merged.id, first.id); + assert.equal(merged.autoMerged, true); + assert.equal(merged.kind, 'textpic'); + service.now = () => '2026-10-14 12:00:11'; + const separate = await service.create({kind: 'image', images: ['https://example.test/b.jpg']}, 1); + assert.notEqual(separate.id, first.id); +}); + +test('auto merge skips disabled, incompatible, commented and differently owned messages', async() => { + for (const mode of ['disabled', 'kind', 'comments', 'author', 'source', 'status', 'future']) { + const {service, comments} = fixture(); + await service.saveSettings({autoMergeSeconds: mode === 'disabled' ? 0 : 10}); + const first = await service.create({text: 'caption'}, 1); + if (mode === 'comments') comments.push({post_id: first.id}); + if (mode === 'future') service.now = () => '2026-10-14 11:59:59'; + const input = mode === 'kind' ? {text: 'another text'} : + {kind: 'image', images: ['https://example.test/a.jpg']}; + if (mode === 'source') input.source = 'QQ'; + if (mode === 'status') input.status = 'private'; + const second = await service.create(input, mode === 'author' ? 2 : 1); + assert.notEqual(second.id, first.id, mode); + } +}); From 5b42754360921acc02b64836130c8fae717e9b34 Mon Sep 17 00:00:00 2001 From: lizheming Date: Thu, 26 Nov 2026 23:55:21 +0800 Subject: [PATCH 2/2] fix(say): prevent concurrent automatic merges from losing content --- packages/say/README.md | 2 ++ packages/say/lib/say-service.js | 29 +++++++++++++++++++++++-- packages/say/test/say-service.test.js | 31 +++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/packages/say/README.md b/packages/say/README.md index 1a07b2e..2c398fa 100644 --- a/packages/say/README.md +++ b/packages/say/README.md @@ -657,3 +657,5 @@ QQ 附件下载失败时,参考编号对应日志中的 `download` 会记录 后台“自动合并间隔”默认 10 秒,可设置为 0 关闭(最大 86400 秒)。新发布内容与历史最新一条碎语的原始发布时间相差不超过该值时,按现有手动合并规则尝试合并;例如文字加图片、连续图片、文字加语音或位置。两条纯文字不会自动拼接。 仅同作者、同来源、同可见性和同评论开关的内容参与自动合并;已有评论或合并后超过 20 张图片时正常新增。不跳过最新记录向更早的记录查找。合并保留原 ID 和发布时间,后续消息仍以该发布时间计算间隔;渠道回复显示合并后的 ID。此设置适用于后台、API 和各渠道的统一创建入口。 + +自动合并使用数据库条件更新保护读取到的原记录;若并发发布或编辑已修改该记录,本次消息改为独立发布,不覆盖其他请求已保存的内容。 diff --git a/packages/say/lib/say-service.js b/packages/say/lib/say-service.js index 3479ce9..0851cd3 100644 --- a/packages/say/lib/say-service.js +++ b/packages/say/lib/say-service.js @@ -284,8 +284,33 @@ class SayService { if (![400, 409].includes(error.status)) throw error; } if (merged && (merged.images || []).length <= 20) { - const item = await this.update(latest.id, merged); - return {...item, autoMerged: true}; + const combined = normalize(merged); + // Compare the stored snapshot in the UPDATE itself. A timestamp alone + // is insufficient: multiple publications can arrive in one second. + const changed = await this.model().where({ + id: latest.id, + type: SAY_TYPE, + options: latest.options, + user_id: latest.user_id, + status: latest.status, + is_public: latest.is_public, + allow_comment: latest.allow_comment, + comment_num: latest.comment_num, + update_time: latest.update_time + }).update({ + title: combined.kind, + summary: combined.text.slice(0, 200), + markdown_content: combined.text, + content: combined.text, + update_time: now, + options: JSON.stringify({say: combined}) + }); + if (Number(changed) === 1) { + return {...combined, id: Number(latest.id), createdAt: latest.create_time, + updatedAt: now, autoMerged: true}; + } + // Another writer won. Insert this publication independently below; + // never acknowledge it as merged or overwrite the winning update. } } } diff --git a/packages/say/test/say-service.test.js b/packages/say/test/say-service.test.js index 69d36f7..119894a 100644 --- a/packages/say/test/say-service.test.js +++ b/packages/say/test/say-service.test.js @@ -267,3 +267,34 @@ test('auto merge skips disabled, incompatible, commented and differently owned m assert.notEqual(second.id, first.id, mode); } }); + + +test('concurrent automatic merges preserve every acknowledged image', async() => { + const {service} = fixture(); + await service.saveSettings({autoMergeSeconds: 10}); + const caption = await service.create({text: 'caption'}, 1); + const images = ['https://example.test/a.jpg', 'https://example.test/b.jpg']; + const results = await Promise.all(images.map(image => + service.create({kind: 'image', images: [image]}, 1))); + assert.equal(results.filter(item => item.autoMerged).length, 1); + assert.equal(new Set(results.map(item => item.id)).size, 2); + const stored = await service.all(); + assert.deepEqual(stored.flatMap(item => item.images).sort(), images); + assert.equal(stored.find(item => item.id === caption.id).text, 'caption'); + for (const result of results) { + assert.ok(stored.some(item => item.id === result.id)); + } +}); + + +test('independent service instances cannot overwrite each other during auto merge', async() => { + const {service} = fixture(); + const other = new SayService({getModel: service.getModel, now: service.now}); + await service.saveSettings({autoMergeSeconds: 10}); + await service.create({text: 'caption'}, 1); + const images = ['https://example.test/one.jpg', 'https://example.test/two.jpg']; + const results = await Promise.all([service, other].map((instance, index) => + instance.create({kind: 'image', images: [images[index]]}, 1))); + assert.equal(results.filter(item => item.autoMerged).length, 1); + assert.deepEqual((await service.all()).flatMap(item => item.images).sort(), images); +});