Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/say/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -651,3 +651,11 @@ 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 和各渠道的统一创建入口。

自动合并使用数据库条件更新保护读取到的原记录;若并发发布或编辑已修改该记录,本次消息改为独立发布,不覆盖其他请求已保存的内容。
2 changes: 1 addition & 1 deletion packages/say/lib/publish-feedback.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
53 changes: 53 additions & 0 deletions packages/say/lib/say-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: '',
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -262,6 +264,57 @@ 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 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.
}
}
}
}
const visibility = databaseStatus(data.status);
const token = crypto.randomBytes(6).toString('hex');
const options = JSON.stringify({say: data});
Expand Down
1 change: 1 addition & 0 deletions packages/say/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 发布的碎语都会归属到这个用户。'},
Expand Down
2 changes: 1 addition & 1 deletion packages/say/test/admin-settings.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
66 changes: 64 additions & 2 deletions packages/say/test/say-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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: '',
Expand Down Expand Up @@ -236,3 +236,65 @@ 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);
}
});


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);
});
Loading