From 636653dfb1d68f752dff4d4f7cb877074a4ed762 Mon Sep 17 00:00:00 2001 From: Jack Yao Date: Fri, 11 Sep 2026 17:59:15 +0800 Subject: [PATCH 1/4] feat: clean up R2 files with deleted messages --- frontend/src/api.js | 3 + frontend/src/composables/useChatRoom.js | 35 +++++ frontend/src/pages/ChatPage.vue | 50 ++++++- test/message-deletion.test.js | 112 +++++++++++++++ worker/src/api/messages.js | 46 +++++- worker/src/data/messages.js | 40 ++++++ worker/src/data/uploaded-files.js | 7 +- worker/src/do-bridge.js | 9 ++ worker/src/do/ChannelRoom.js | 26 +++- worker/src/gc.js | 177 ++++++++++++++++++++++-- wrangler.example.toml | 1 + 11 files changed, 483 insertions(+), 23 deletions(-) create mode 100644 test/message-deletion.test.js diff --git a/frontend/src/api.js b/frontend/src/api.js index ed82664e..45e760ca 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -128,6 +128,9 @@ export default { } return request(`/messages?${query.toString()}`); }, + deleteMessage(messageId) { + return request(`/messages/${messageId}`, { method: 'DELETE' }); + }, markRoomRead(kind, roomId, messageId) { return request('/messages/read', { method: 'POST', diff --git a/frontend/src/composables/useChatRoom.js b/frontend/src/composables/useChatRoom.js index d47da162..0e2753b9 100644 --- a/frontend/src/composables/useChatRoom.js +++ b/frontend/src/composables/useChatRoom.js @@ -14,7 +14,9 @@ export function useChatRoom({ session, error, onRoomActivity = () => {}, + onRoomMessageDeleted = () => {}, onRoomAccessRevoked = () => {}, + confirmAction = (message) => window.confirm(message), }) { const messages = ref([]); const loading = ref(false); @@ -22,6 +24,7 @@ export function useChatRoom({ const composerText = ref(""); const pendingAttachment = ref(null); const sending = ref(false); + const deletingMessageId = ref(null); const messagesEl = ref(null); const fileInputEl = ref(null); @@ -96,6 +99,14 @@ export function useChatRoom({ applyActiveRoomActivity(payload.message); nextTick().then(scrollToBottom); } + if (payload.type === "message_deleted" && payload.messageId) { + const messageId = Number(payload.messageId); + const nextMessages = messages.value.filter((item) => Number(item.id) !== messageId); + if (nextMessages.length !== messages.value.length) { + messages.value = nextMessages; + onRoomMessageDeleted({ messageId }); + } + } if (payload.type === "error") { error.value = payload.error; } @@ -176,6 +187,28 @@ export function useChatRoom({ } } + async function deleteMessage(message) { + const messageId = Number(message?.id); + if (!Number.isInteger(messageId) || messageId <= 0 || deletingMessageId.value) { + return; + } + if (!confirmAction("确认删除这条消息吗?附件也会在没有其他引用时回收。")) { + return; + } + + deletingMessageId.value = messageId; + error.value = ""; + try { + await api.deleteMessage(messageId); + messages.value = messages.value.filter((item) => Number(item.id) !== messageId); + onRoomMessageDeleted({ messageId }); + } catch (currentError) { + error.value = currentError.message; + } finally { + deletingMessageId.value = null; + } + } + function handleComposerKeydown(event) { if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); @@ -232,6 +265,7 @@ export function useChatRoom({ composerText, pendingAttachment, sending, + deletingMessageId, messagesEl, fileInputEl, isOwnMessage, @@ -239,6 +273,7 @@ export function useChatRoom({ connectSocket, disconnectSocket, sendMessage, + deleteMessage, handleComposerKeydown, openFilePicker, uploadAttachment, diff --git a/frontend/src/pages/ChatPage.vue b/frontend/src/pages/ChatPage.vue index 090631f9..5f16aba7 100644 --- a/frontend/src/pages/ChatPage.vue +++ b/frontend/src/pages/ChatPage.vue @@ -52,14 +52,15 @@ function handleRoomAccessRevoked(room) { const { messages, loading, wsStatus, composerText, pendingAttachment, sending, - messagesEl, fileInputEl, isOwnMessage, - loadMessages, connectSocket, disconnectSocket, sendMessage, handleComposerKeydown, + deletingMessageId, messagesEl, fileInputEl, isOwnMessage, + loadMessages, connectSocket, disconnectSocket, sendMessage, deleteMessage, handleComposerKeydown, openFilePicker, uploadAttachment, clearAttachment, loadOlder } = useChatRoom({ activeRoom, session, error, onRoomActivity: handleRoomActivity, + onRoomMessageDeleted: () => { void refreshSidebar(); }, onRoomAccessRevoked: handleRoomAccessRevoked }); @@ -282,8 +283,19 @@ onBeforeUnmount(() => { {{ msg.sender.displayName }}

{{ msg.content }}

- - {{ formatBubbleTime(msg.createdAt) }} + +
+ {{ formatBubbleTime(msg.createdAt) }} + +
@@ -783,10 +795,19 @@ onBeforeUnmount(() => { margin-bottom: 4px; } -.message-time { +.message-meta { position: absolute; right: 8px; bottom: 6px; + display: flex; + align-items: center; + gap: 6px; +} + +.message-time { + position: absolute; + right: 0; + bottom: 0; font-size: 11px; line-height: 1; color: #667781; @@ -794,6 +815,25 @@ onBeforeUnmount(() => { user-select: none; } +.message-delete { + margin-right: 29px; + padding: 0; + border: 0; + background: transparent; + color: #dc2626; + font-size: 11px; + cursor: pointer; +} + +.message-delete:hover { + text-decoration: underline; +} + +.message-delete:disabled { + cursor: wait; + opacity: 0.6; +} + .message-bubble p { margin: 0; font-size: 14.5px; diff --git a/test/message-deletion.test.js b/test/message-deletion.test.js new file mode 100644 index 00000000..4dfcb714 --- /dev/null +++ b/test/message-deletion.test.js @@ -0,0 +1,112 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; + +import { + deleteMessageById, + getMessageDeletionTarget, +} from '../worker/src/data/messages.js'; + +function read(relativePath) { + return readFileSync(new URL(relativePath, import.meta.url), 'utf8'); +} + +function createFakeDb({ referenced = false } = {}) { + const queries = []; + const deletedRows = []; + return { + queries, + deletedRows, + prepare(sql) { + queries.push(sql); + return { + bind(...bindings) { + return { + async all() { + if (sql.includes('FROM messages m') && sql.includes('channel_kind')) { + return { + results: [{ + id: 8, + channel_id: 3, + sender_id: 7, + attachment_key: '7/voice.webm', + channel_kind: 'dm', + }], + }; + } + if (sql.includes('FROM (')) { + return { results: referenced ? [{ found: 1 }] : [] }; + } + return { results: [] }; + }, + async run() { + if (sql.includes('DELETE FROM messages')) { + return { meta: { changes: 1 } }; + } + if (sql.includes('DELETE FROM uploaded_files')) { + deletedRows.push({ table: 'uploaded_files', bindings }); + } + if (sql.includes('DELETE FROM pending_r2_delete')) { + deletedRows.push({ table: 'pending_r2_delete', bindings }); + } + return { meta: { changes: 1 } }; + }, + }; + }, + }; + }, + async batch() {}, + }; +} + +test('消息删除目标同时返回频道类型和附件 key', async () => { + const db = createFakeDb(); + const target = await getMessageDeletionTarget(db, 8); + + assert.deepEqual(target, { + id: 8, + channel_id: 3, + sender_id: 7, + attachment_key: '7/voice.webm', + channel_kind: 'dm', + }); +}); + +test('删除消息会清理未被其他资源引用的 R2 对象', async () => { + const db = createFakeDb(); + const deletedKeys = []; + const target = await deleteMessageById({ + DB: db, + FILES: { async delete(key) { deletedKeys.push(key); } }, + }, 8); + + assert.equal(target.id, 8); + assert.deepEqual(deletedKeys, ['7/voice.webm']); + assert.deepEqual(db.deletedRows, [ + { table: 'uploaded_files', bindings: ['7/voice.webm'] }, + { table: 'pending_r2_delete', bindings: ['7/voice.webm'] }, + ]); +}); + +test('仍有其他活跃引用时删除消息不会删除 R2 对象', async () => { + const db = createFakeDb({ referenced: true }); + const deletedKeys = []; + await deleteMessageById({ + DB: db, + FILES: { async delete(key) { deletedKeys.push(key); } }, + }, 8); + + assert.deepEqual(deletedKeys, []); + assert.deepEqual(db.deletedRows, []); +}); + +test('消息删除接口和前端删除入口均已声明', () => { + const apiSource = read('../worker/src/api/messages.js'); + const clientSource = read('../frontend/src/api.js'); + const roomSource = read('../frontend/src/composables/useChatRoom.js'); + + assert.match(apiSource, /app\.delete\('\/api\/messages\/:messageId'/); + assert.match(apiSource, /只能删除自己发送的消息/); + assert.match(clientSource, /deleteMessage\(messageId\)/); + assert.match(roomSource, /message_deleted/); +}); diff --git a/worker/src/api/messages.js b/worker/src/api/messages.js index b2706d04..1a1c4650 100644 --- a/worker/src/api/messages.js +++ b/worker/src/api/messages.js @@ -1,9 +1,53 @@ -import { listMessages } from '../data/messages.js'; +import { + deleteMessageById, + getMessageDeletionTarget, + listMessages +} from '../data/messages.js'; import { markRoomRead } from '../data/unread.js'; import { authorizeRoom, isRoomKind } from '../room-access.js'; +import { notifyRoomMessageDeleted } from '../do-bridge.js'; import { errorResponse, parseJsonRequest, sanitizeLimit } from '../utils.js'; export function registerMessageRoutes(app) { + app.delete('/api/messages/:messageId', async (c) => { + const session = c.get('session'); + const messageId = Number(c.req.param('messageId')); + if (!Number.isInteger(messageId) || messageId <= 0) { + return errorResponse('消息不存在', 404); + } + + const target = await getMessageDeletionTarget(c.env.DB, messageId); + if (!target) { + return errorResponse('消息不存在', 404); + } + + const access = await authorizeRoom( + c.env.DB, + session, + target.channel_kind, + target.channel_id, + ); + if (!access.ok) { + return errorResponse('无权删除该消息', 403); + } + if (!session.isAdmin && Number(target.sender_id) !== Number(session.userId)) { + return errorResponse('只能删除自己发送的消息', 403); + } + + const deleted = await deleteMessageById(c.env, messageId); + if (!deleted) { + return errorResponse('消息不存在', 404); + } + + try { + await notifyRoomMessageDeleted(c.env, target.channel_kind, target.channel_id, messageId); + } catch (error) { + console.warn('Failed to broadcast message deletion', error); + } + + return c.json({ ok: true, messageId }); + }); + app.get('/api/messages', async (c) => { const session = c.get('session'); const kind = c.req.query('kind'); diff --git a/worker/src/data/messages.js b/worker/src/data/messages.js index fe7b9fde..e28ee7f3 100644 --- a/worker/src/data/messages.js +++ b/worker/src/data/messages.js @@ -1,4 +1,5 @@ import { decryptMessageContent, encryptMessageContent } from "../encryption.js"; +import { cleanupR2Keys } from "../gc.js"; import { pickAttachment, publicFileUrl } from "../utils.js"; import { fileBelongsToUser } from "./uploaded-files.js"; @@ -44,6 +45,45 @@ const MESSAGE_SELECT = `SELECT u.display_name AS sender_display_name, u.avatar_key AS sender_avatar_key FROM messages m JOIN users u ON u.id = m.sender_id`; +export async function getMessageDeletionTarget(db, messageId) { + const { results } = await db + .prepare( + `SELECT m.id, m.channel_id, m.sender_id, m.attachment_key, + c.kind AS channel_kind + FROM messages m + JOIN channels c ON c.id = m.channel_id + WHERE m.id = ? + AND m.deleted_at IS NULL + LIMIT 1`, + ) + .bind(Number(messageId)) + .all(); + return results[0] || null; +} + +export async function deleteMessageById(env, messageId) { + const target = await getMessageDeletionTarget(env.DB, messageId); + if (!target) { + return null; + } + + const result = await env.DB + .prepare( + `DELETE FROM messages + WHERE id = ? AND deleted_at IS NULL`, + ) + .bind(Number(messageId)) + .run(); + if (Number(result.meta?.changes || 0) !== 1) { + return null; + } + + if (target.attachment_key) { + await cleanupR2Keys(env, [target.attachment_key]); + } + return target; +} + export async function listMessages(env, roomId, before = null, limit = 30) { const filters = ["m.channel_id = ?", "m.deleted_at IS NULL"]; const binds = [Number(roomId)]; diff --git a/worker/src/data/uploaded-files.js b/worker/src/data/uploaded-files.js index 38ad11b1..d284928e 100644 --- a/worker/src/data/uploaded-files.js +++ b/worker/src/data/uploaded-files.js @@ -45,7 +45,12 @@ export async function fileBelongsToUser(db, key, userId) { const { results } = await db .prepare( `SELECT 1 AS found FROM uploaded_files - WHERE object_key = ? AND owner_user_id = ? LIMIT 1`, + WHERE object_key = ? AND owner_user_id = ? + AND NOT EXISTS ( + SELECT 1 FROM pending_r2_delete + WHERE pending_r2_delete.object_key = uploaded_files.object_key + ) + LIMIT 1`, ) .bind(String(key), Number(userId)) .all(); diff --git a/worker/src/do-bridge.js b/worker/src/do-bridge.js index 12d85999..061958f3 100644 --- a/worker/src/do-bridge.js +++ b/worker/src/do-bridge.js @@ -68,3 +68,12 @@ export async function notifyUserInbox(env, userId, payload) { }); return response; } + +export async function notifyRoomMessageDeleted(env, kind, roomId, messageId) { + const stub = getChannelRoomStub(env, kind, roomId); + return stub.fetch(`${INTERNAL_ORIGIN}/broadcast`, { + method: "POST", + headers: createInternalHeaders({ "Content-Type": "application/json" }), + body: JSON.stringify({ type: "message_deleted", messageId: Number(messageId) }), + }); +} diff --git a/worker/src/do/ChannelRoom.js b/worker/src/do/ChannelRoom.js index ec833ce3..4326ca38 100644 --- a/worker/src/do/ChannelRoom.js +++ b/worker/src/do/ChannelRoom.js @@ -2,7 +2,7 @@ import { MessageSubmissionError, submitRoomMessage } from '../message-submission import { authorizeRoom } from '../room-access.js'; import { validateSession } from '../session.js'; import { projectUnreadMessage } from '../unread-projection.js'; -import { parseVerifiedPrincipal } from '../verified-identity.js'; +import { isVerifiedInternalRequest, parseVerifiedPrincipal } from '../verified-identity.js'; const MESSAGE_SIZE_LIMIT = 10 * 1024; @@ -141,6 +141,30 @@ export class ChannelRoom { async fetch(request) { const url = new URL(request.url); + if (url.pathname === '/broadcast') { + if (!isVerifiedInternalRequest(request) || request.method !== 'POST') { + return new Response('Forbidden', { status: 403 }); + } + let payload; + try { + payload = await request.json(); + } catch { + return new Response('Invalid payload', { status: 400 }); + } + if ( + payload?.type !== 'message_deleted' || + !Number.isInteger(Number(payload.messageId)) || + Number(payload.messageId) <= 0 + ) { + return new Response('Invalid payload', { status: 400 }); + } + await this.broadcast(JSON.stringify({ + type: 'message_deleted', + messageId: Number(payload.messageId), + })); + return new Response('ok'); + } + if (request.headers.get('Upgrade') !== 'websocket') { return new Response('Expected websocket', { status: 426 }); } diff --git a/worker/src/gc.js b/worker/src/gc.js index 41b7cad2..3df8d57a 100644 --- a/worker/src/gc.js +++ b/worker/src/gc.js @@ -3,6 +3,7 @@ const DEFAULT_SOFT_DELETE_RETENTION_DAYS = 60; const DEFAULT_BATCH_SIZE = 500; const DEFAULT_MAX_BATCHES_PER_RUN = 20; const DEFAULT_R2_DELETE_MAX_RETRY = 8; +const DEFAULT_ORPHAN_UPLOAD_RETENTION_DAYS = 1; const MAX_ERROR_LENGTH = 500; const DELETE_ALLOWED_IDENTIFIERS = { messages: new Set(['id', 'channel_id', 'sender_id']), @@ -39,6 +40,10 @@ function getGcConfig(env) { r2DeleteMaxRetry: toPositiveInteger( env.R2_DELETE_MAX_RETRY, DEFAULT_R2_DELETE_MAX_RETRY + ), + orphanUploadRetentionDays: toPositiveInteger( + env.ORPHAN_UPLOAD_RETENTION_DAYS, + DEFAULT_ORPHAN_UPLOAD_RETENTION_DAYS ) }; } @@ -84,7 +89,8 @@ function createSummary() { r2Deleted: 0, r2DeleteFailed: 0, r2DeleteQueued: 0, - r2SkippedReferenced: 0 + r2SkippedReferenced: 0, + orphanUploadsDeleted: 0 }; } @@ -112,21 +118,29 @@ async function isR2KeyReferenced(db, key) { .prepare( `SELECT 1 AS found FROM ( - SELECT attachment_key AS object_key - FROM messages - WHERE attachment_key = ? - UNION ALL - SELECT avatar_key AS object_key - FROM users - WHERE avatar_key = ? - UNION ALL - SELECT avatar_key AS object_key - FROM channels - WHERE avatar_key = ? - ) refs + SELECT attachment_key AS object_key + FROM messages + WHERE attachment_key = ? + AND deleted_at IS NULL + UNION ALL + SELECT avatar_key AS object_key + FROM users + WHERE avatar_key = ? + AND deleted_at IS NULL + UNION ALL + SELECT avatar_key AS object_key + FROM channels + WHERE avatar_key = ? + AND deleted_at IS NULL + UNION ALL + SELECT setting_value AS object_key + FROM site_settings + WHERE setting_key = 'site_icon_url' + AND setting_value IN (?, ?) + ) refs LIMIT 1` ) - .bind(key, key, key) + .bind(key, key, key, key, `/files/${encodeURIComponent(key)}`) .all(); return Boolean(results[0]); } @@ -162,6 +176,36 @@ async function removePendingR2Delete(db, key) { .run(); } +async function reserveR2Delete(db, key) { + await db + .prepare( + `INSERT INTO pending_r2_delete ( + object_key, + retry_count, + next_retry_at, + last_error, + created_at, + updated_at + ) + VALUES (?, 0, CURRENT_TIMESTAMP, '', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) + ON CONFLICT(object_key) DO UPDATE + SET next_retry_at = CURRENT_TIMESTAMP, + updated_at = CURRENT_TIMESTAMP` + ) + .bind(key) + .run(); +} + +async function removeUploadedFileMetadata(db, key) { + await db + .prepare( + `DELETE FROM uploaded_files + WHERE object_key = ?` + ) + .bind(key) + .run(); +} + function retryDelayMinutes(nextRetryCount, retryExponentCap) { const exponent = Math.min(Math.max(nextRetryCount, 1), retryExponentCap); const delay = 2 ** exponent; @@ -231,8 +275,19 @@ async function processR2CandidateKeys(env, db, keys, summary) { continue; } + await reserveR2Delete(db, key); + // Mark the key as pending before the final reference check so new messages + // cannot bind an object that is already in the deletion workflow. + if (await isR2KeyReferenced(db, key)) { + await removePendingR2Delete(db, key); + summary.r2SkippedReferenced += 1; + continue; + } + + await removeUploadedFileMetadata(db, key); try { await env.FILES.delete(key); + await removePendingR2Delete(db, key); summary.r2Deleted += 1; } catch (error) { summary.r2DeleteFailed += 1; @@ -279,6 +334,7 @@ async function runRetryQueueStep(env, config, summary) { try { await env.FILES.delete(key); + await removeUploadedFileMetadata(env.DB, key); await removePendingR2Delete(env.DB, key); summary.retryQueueDeleted += 1; summary.r2Deleted += 1; @@ -303,6 +359,87 @@ async function runRetryQueueStep(env, config, summary) { } } +async function collectUploadedFileKeysByOwner(db, userIds) { + if (!userIds.length) { + return []; + } + + const { results } = await db + .prepare( + `SELECT object_key + FROM uploaded_files + WHERE owner_user_id IN (${placeholders(userIds.length)})` + ) + .bind(...userIds) + .all(); + return uniqueKeys(results.map((row) => row.object_key)); +} + +async function deleteUploadedFileMetadataByOwner(db, userIds) { + if (!userIds.length) { + return 0; + } + + const { meta } = await db + .prepare( + `DELETE FROM uploaded_files + WHERE owner_user_id IN (${placeholders(userIds.length)})` + ) + .bind(...userIds) + .run(); + return Number(meta?.changes || 0); +} + +async function runOrphanedUploadsStep(env, config, summary) { + let batches = 0; + + while (batches < config.maxBatchesPerRun) { + const { results } = await env.DB + .prepare( + `SELECT object_key + FROM uploaded_files + WHERE created_at < datetime('now', ?) + AND NOT EXISTS ( + SELECT 1 FROM messages + WHERE messages.attachment_key = uploaded_files.object_key + AND messages.deleted_at IS NULL + ) + AND NOT EXISTS ( + SELECT 1 FROM users + WHERE users.avatar_key = uploaded_files.object_key + AND users.deleted_at IS NULL + ) + AND NOT EXISTS ( + SELECT 1 FROM channels + WHERE channels.avatar_key = uploaded_files.object_key + AND channels.deleted_at IS NULL + ) + ORDER BY created_at ASC + LIMIT ?` + ) + .bind(`-${config.orphanUploadRetentionDays} day`, config.batchSize) + .all(); + + if (!results.length) { + break; + } + + batches += 1; + const before = summary.r2Deleted; + await processR2CandidateKeys( + env, + env.DB, + results.map((row) => row.object_key), + summary + ); + summary.orphanUploadsDeleted += summary.r2Deleted - before; + + if (results.length < config.batchSize) { + break; + } + } +} + async function runExpiredMessagesStep(env, config, summary) { let batches = 0; @@ -492,6 +629,7 @@ async function runHardDeleteUsersStep(env, config, summary) { batches += 1; const userIds = results.map((row) => Number(row.id)); const avatarKeys = results.map((row) => row.avatar_key); + const ownedFileKeys = await collectUploadedFileKeysByOwner(env.DB, userIds); const attachmentKeys = await collectMessageAttachmentsByColumn( env.DB, 'sender_id', @@ -499,6 +637,7 @@ async function runHardDeleteUsersStep(env, config, summary) { ); await clearUserReferences(env, userIds); + await deleteUploadedFileMetadataByOwner(env.DB, userIds); summary.userMessagesDeleted += await deleteRowsByIds( env.DB, 'messages', @@ -521,7 +660,7 @@ async function runHardDeleteUsersStep(env, config, summary) { await processR2CandidateKeys( env, env.DB, - [...attachmentKeys, ...avatarKeys], + [...attachmentKeys, ...avatarKeys, ...ownedFileKeys], summary ); @@ -541,6 +680,7 @@ export async function runScheduledGc(env) { await runHardDeleteInvitesStep(env, config, summary); await runHardDeleteChannelsStep(env, config, summary); await runHardDeleteUsersStep(env, config, summary); + await runOrphanedUploadsStep(env, config, summary); console.log(JSON.stringify({ type: 'scheduled_gc_summary', @@ -550,3 +690,10 @@ export async function runScheduledGc(env) { return summary; } + +export async function cleanupR2Keys(env, keys) { + await ensureGcSchema(env.DB); + const summary = createSummary(); + await processR2CandidateKeys(env, env.DB, keys, summary); + return summary; +} diff --git a/wrangler.example.toml b/wrangler.example.toml index ed407c3c..cf816b65 100644 --- a/wrangler.example.toml +++ b/wrangler.example.toml @@ -11,6 +11,7 @@ SOFT_DELETE_RETENTION_DAYS = "60" GC_BATCH_SIZE = "500" GC_MAX_BATCHES_PER_RUN = "20" R2_DELETE_MAX_RETRY = "8" +ORPHAN_UPLOAD_RETENTION_DAYS = "1" ALLOWED_FILE_TYPES = "image/,video/,application/pdf,text/" MAX_FILE_SIZE = "20971520" From 0d6806cc8e9d4712e29e44cb98347241ec620cbf Mon Sep 17 00:00:00 2001 From: gdz66601 Date: Fri, 11 Sep 2026 22:44:28 +0800 Subject: [PATCH 2/4] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E7=A7=81?= =?UTF-8?q?=E4=BF=A1=E6=8B=89=E9=BB=91=20/=20add=20direct-message=20blocki?= =?UTF-8?q?ng?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/d1-migration-manifest.mjs | 5 + CHANGELOG.md | 4 + README.en.md | 1 + README.ja.md | 1 + README.md | 1 + frontend/src/api.js | 6 ++ frontend/src/composables/useUserBlock.ts | 80 ++++++++++++++ frontend/src/demo/api.js | 24 ++++- frontend/src/demo/fixtures.js | 3 +- frontend/src/demo/realtime.js | 25 ++++- frontend/src/demo/state.js | 48 +++++++-- frontend/src/locales/en-US.js | 7 +- frontend/src/locales/zh-CN.js | 7 +- frontend/src/localized-error.js | 4 +- frontend/src/pages/ChatPage.vue | 37 ++++++- package-lock.json | 4 +- package.json | 2 +- test/chat-page-composables.test.js | 46 ++++++++ test/data-projections.test.js | 4 +- test/demo-runtime.test.js | 45 ++++++++ test/user-blocks.test.js | 105 +++++++++++++++++++ worker/migrations/2026-09-11-user-blocks.sql | 12 +++ worker/schema.sql | 13 +++ worker/src/api/dm.js | 9 +- worker/src/api/user-blocks.ts | 39 +++++++ worker/src/data/dm-queries.js | 5 +- worker/src/data/user-blocks.ts | 99 +++++++++++++++++ worker/src/index.js | 2 + worker/src/message-submission.js | 23 ++++ 29 files changed, 628 insertions(+), 33 deletions(-) create mode 100644 frontend/src/composables/useUserBlock.ts create mode 100644 test/user-blocks.test.js create mode 100644 worker/migrations/2026-09-11-user-blocks.sql create mode 100644 worker/src/api/user-blocks.ts create mode 100644 worker/src/data/user-blocks.ts diff --git a/.github/scripts/d1-migration-manifest.mjs b/.github/scripts/d1-migration-manifest.mjs index 1284a03e..a49d0727 100644 --- a/.github/scripts/d1-migration-manifest.mjs +++ b/.github/scripts/d1-migration-manifest.mjs @@ -147,6 +147,11 @@ export const D1_MIGRATIONS = [ "index:idx_messages_reply_attention", ], }, + { + id: "2026-09-11-user-blocks", + file: "worker/migrations/2026-09-11-user-blocks.sql", + artifacts: ["table:user_blocks", "index:idx_user_blocks_blocked"], + }, ]; // b3f6855 曾发布、0c13e8f 已撤回的迁移:仅识别历史 ledger,不要求新安装创建废弃表,也不删除旧数据。 diff --git a/CHANGELOG.md b/CHANGELOG.md index 87f65a88..07cc26c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ EdgeChat 从 `2.1.2` 起正式采用语义化版本。更早的版本号依据已经完成的主要里程碑补记,用于说明项目演进,不对应历史 Git 标签。 +## 2.2.0 - 2026-09-11 + +- 新增私信用户拉黑与解除拉黑,服务端统一阻断双方发送,并向被拉黑者返回明确拒绝提示。 + ## 2.1.2 - 2026-09-08 - 统一 Web、安装维护页、demo 与 Capacitor 客户端的项目版本来源。 diff --git a/README.en.md b/README.en.md index 61131e1e..fdfc3a42 100644 --- a/README.en.md +++ b/README.en.md @@ -117,6 +117,7 @@ Admins can bind any group in EdgeChat to a Telegram group. Once bound, messages - Public groups, private groups, and direct message conversations - [Two-way Telegram group bridge](#featured-feature-telegram-two-way-message-bridge) — one Bot connects members on both sides - Real-time messaging, paginated history, Telegram-style voice messages, and file messages +- Block or unblock contacts from the direct-message header; direct messages pause in both directions while blocked - The web client supports Telegram-style replies, quoted-message navigation, and reply-aware direct-attention alerts - Web and Android recording, waveform seeking, playback speed controls, and two-way Telegram voice/audio sync - File uploads and avatar management diff --git a/README.ja.md b/README.ja.md index ebc0332c..bdf8e2ec 100644 --- a/README.ja.md +++ b/README.ja.md @@ -117,6 +117,7 @@ EdgeChat は Cloudflare 上にデプロイするチーム向けチャットシ - 公開グループ、プライベートグループ、ダイレクトメッセージの会話に対応 - [Telegram グループ双方向メッセージブリッジ](#注目機能telegram-双方向メッセージブリッジ):1 つの Bot で両側のメンバーをつなぐ - リアルタイムメッセージ、履歴のページング、Telegram 風ボイスメッセージ、ファイルメッセージ +- ダイレクトメッセージのヘッダーから相手をブロック/解除でき、ブロック中は双方の送信を停止 - Web では Telegram 風の返信、引用元へのジャンプ、返信を含む「メンション」優先通知に対応 - Web / Android の録音、波形シーク、倍速再生、Telegram voice/audio の双方向同期 - ファイルアップロードとアバター管理 diff --git a/README.md b/README.md index 04aadbc5..f33413e4 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,7 @@ EdgeChat 是一个部署在 Cloudflare 上的团队聊天系统:账号体系 - 支持公开群组、私有群组与私信会话 - [Telegram 群组双向消息桥接](#特色功能telegram-消息双向桥接),一个 Bot 打通两侧成员 - 实时消息、历史消息分页、Telegram 风格语音消息与文件消息 +- 可在私信顶部拉黑或解除拉黑联系人,拉黑期间双方均无法继续发送私信 - 网页支持 Telegram 风格消息回复、引用跳转,以及将回复纳入「有人@我」优先提醒 - 网页和 Android 均支持录音、波形进度、倍速播放;Telegram voice/audio 可双向同步 - 文件上传与头像管理 diff --git a/frontend/src/api.js b/frontend/src/api.js index 92efd927..10a11cd0 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -172,6 +172,12 @@ export default { listDms() { return request('/dm'); }, + blockUser(userId) { + return request(`/users/${Number(userId)}/block`, { method: 'PUT' }); + }, + unblockUser(userId) { + return request(`/users/${Number(userId)}/block`, { method: 'DELETE' }); + }, uploadFile(file) { const form = new FormData(); form.append('file', file); diff --git a/frontend/src/composables/useUserBlock.ts b/frontend/src/composables/useUserBlock.ts new file mode 100644 index 00000000..7892d9c4 --- /dev/null +++ b/frontend/src/composables/useUserBlock.ts @@ -0,0 +1,80 @@ +import { computed, ref, type Ref } from "vue"; +import api from "../api.js"; +import { t } from "../i18n.js"; + +interface DirectMessage { + id: number; + kind: "dm"; + isBlockedByMe?: boolean; + otherUser: { id: number; displayName?: string }; +} + +interface UserBlockApi { + blockUser(userId: number): Promise<{ blockedByMe: boolean }>; + unblockUser(userId: number): Promise<{ blockedByMe: boolean }>; +} + +export function useUserBlock({ + activeRoom, + dms, + error, + blockApi = api, + confirmBlock = (message: string) => globalThis.confirm(message), +}: { + activeRoom: Ref | null>; + dms: Ref; + error: Ref; + blockApi?: UserBlockApi; + confirmBlock?: (message: string) => boolean; +}) { + const saving = ref(false); + const isBlockedByMe = computed( + () => activeRoom.value?.kind === "dm" && Boolean(activeRoom.value.isBlockedByMe), + ); + + function peerUserId() { + return Number( + activeRoom.value?.kind === "dm" + ? (activeRoom.value as DirectMessage).otherUser?.id + : 0, + ); + } + + function applyBlockState(userId: number, blockedByMe: boolean) { + if (activeRoom.value?.kind === "dm" && peerUserId() === userId) { + activeRoom.value.isBlockedByMe = blockedByMe; + } + const dm = dms.value.find((item) => Number(item.otherUser.id) === userId); + if (dm) dm.isBlockedByMe = blockedByMe; + } + + async function toggleUserBlock() { + if (activeRoom.value?.kind !== "dm" || saving.value) return false; + const room = activeRoom.value as DirectMessage; + const userId = peerUserId(); + const nextBlocked = !room.isBlockedByMe; + if ( + nextBlocked && + !confirmBlock(t("chat.blockUserConfirm", { name: room.otherUser.displayName || "" })) + ) { + return false; + } + + saving.value = true; + error.value = ""; + try { + const result = nextBlocked + ? await blockApi.blockUser(userId) + : await blockApi.unblockUser(userId); + applyBlockState(userId, result.blockedByMe); + return true; + } catch (currentError) { + error.value = currentError instanceof Error ? currentError.message : String(currentError); + return false; + } finally { + saving.value = false; + } + } + + return { isBlockedByMe, saving, toggleUserBlock }; +} diff --git a/frontend/src/demo/api.js b/frontend/src/demo/api.js index d138c684..eb3f8ab4 100644 --- a/frontend/src/demo/api.js +++ b/frontend/src/demo/api.js @@ -8,6 +8,7 @@ import { projectDemoDm, projectDemoUser, roomKey, + setDemoUserBlocked, storeDemoFile } from './state.js'; @@ -52,7 +53,7 @@ function sessionForUser(user) { function bootstrapPayload() { return { channels: demoState.channels.map(projectDemoChannel), - dms: demoState.dms.map(projectDemoDm), + dms: demoState.dms.map((dm) => projectDemoDm(dm, demoState.session.userId)), users: demoState.users .map(projectDemoUser) .filter((user) => Number(user.id) !== Number(demoState.session.userId) && !user.isDisabled) @@ -262,6 +263,16 @@ export async function requestDemo(path, options = {}) { if (method === 'GET' && pathname === '/users') { return { users: bootstrapPayload().users }; } + let match = pathname.match(/^\/users\/(\d+)\/block$/); + if ((method === 'PUT' || method === 'DELETE') && match) { + const userId = Number(match[1]); + if (userId === Number(demoState.session.userId) || !findDemoUser(userId)) { + fail('请选择有效用户'); + } + const blockedByMe = method === 'PUT'; + setDemoUserBlocked(demoState.session.userId, userId, blockedByMe); + return { blockedByMe }; + } if (method === 'GET' && pathname === '/bootstrap') { return bootstrapPayload(); } @@ -274,7 +285,7 @@ export async function requestDemo(path, options = {}) { return { channel: createGroup(body) }; } - let match = pathname.match(/^\/channels\/(\d+)\/join$/); + match = pathname.match(/^\/channels\/(\d+)\/join$/); if (method === 'POST' && match) { const channel = findDemoChannel(match[1]); if (!channel || channel.kind !== 'public') fail('公开群组不存在', 404); @@ -357,7 +368,10 @@ export async function requestDemo(path, options = {}) { if (method === 'POST' && pathname === '/dm/open') { const user = findDemoUser(body.userId); if (!user) fail('用户不存在', 404); - let dm = demoState.dms.find((item) => Number(item.otherUser.id) === Number(user.id)); + let dm = demoState.dms.find( + (item) => item.participantIds.includes(Number(demoState.session.userId)) + && item.participantIds.includes(Number(user.id)) + ); if (!dm) { dm = { id: demoState.nextDmId++, @@ -371,10 +385,10 @@ export async function requestDemo(path, options = {}) { demoState.dms.push(dm); demoState.messages[roomKey('dm', dm.id)] = []; } - return { dm: projectDemoDm(dm) }; + return { dm: projectDemoDm(dm, demoState.session.userId) }; } if (method === 'GET' && pathname === '/dm') { - return { dms: demoState.dms.map(projectDemoDm) }; + return { dms: demoState.dms.map((dm) => projectDemoDm(dm, demoState.session.userId)) }; } if (method === 'POST' && pathname === '/upload') { const file = body.get('file'); diff --git a/frontend/src/demo/fixtures.js b/frontend/src/demo/fixtures.js index 6ccbe0b4..079bcf9a 100644 --- a/frontend/src/demo/fixtures.js +++ b/frontend/src/demo/fixtures.js @@ -350,7 +350,8 @@ export function createDemoFixtures() { users, channels, dms, - messages, + messages, + userBlocks: new Set(), pinnedMessages: { 'public:1': messages['public:1'][1] }, diff --git a/frontend/src/demo/realtime.js b/frontend/src/demo/realtime.js index 93b7fc14..63856386 100644 --- a/frontend/src/demo/realtime.js +++ b/frontend/src/demo/realtime.js @@ -1,4 +1,10 @@ -import { cloneDemo, createDemoMessage, demoState, roomKey } from './state.js'; +import { + cloneDemo, + createDemoMessage, + demoState, + getDemoDirectMessageBlockStatus, + roomKey +} from './state.js'; const roomSockets = new Map(); const inboxSockets = new Set(); @@ -73,9 +79,20 @@ function hasEnabledTelegramMapping(kind, roomId) { } function handleRoomFrame(socket, frame) { - const payload = JSON.parse(frame); - if (payload.type === 'send') { - const message = createDemoMessage({ + const payload = JSON.parse(frame); + if (payload.type === 'send') { + if (socket.kind === 'dm') { + const status = getDemoDirectMessageBlockStatus(socket.roomId, demoState.session.userId); + if (status.blockedByPeer) { + emit(socket, { type: 'error', error: '发送被拒,你已经被拉黑' }); + return; + } + if (status.blockedBySender) { + emit(socket, { type: 'error', error: '请先解除拉黑再发送' }); + return; + } + } + const message = createDemoMessage({ kind: socket.kind, roomId: socket.roomId, content: payload.content, diff --git a/frontend/src/demo/state.js b/frontend/src/demo/state.js index fe5b38f7..ab2150a4 100644 --- a/frontend/src/demo/state.js +++ b/frontend/src/demo/state.js @@ -56,16 +56,44 @@ export function projectDemoChannel(channel) { return cloneDemo(projection); } -export function projectDemoDm(dm) { - if (!dm) return null; - return { - id: dm.id, - kind: 'dm', - otherUser: projectDemoUser(dm.otherUser), - lastMessageAt: dm.lastMessageAt, - unreadCount: dm.unreadCount, - mentionUnreadCount: Number(dm.mentionUnreadCount || 0) - }; +export function projectDemoDm(dm, viewerUserId = demoState.session.userId) { + if (!dm) return null; + const peerUserId = dm.participantIds.find( + (userId) => Number(userId) !== Number(viewerUserId) + ); + const otherUser = findDemoUser(peerUserId) || dm.otherUser; + return { + id: dm.id, + kind: 'dm', + otherUser: projectDemoUser(otherUser), + lastMessageAt: dm.lastMessageAt, + unreadCount: dm.unreadCount, + mentionUnreadCount: Number(dm.mentionUnreadCount || 0), + isBlockedByMe: isDemoUserBlocked(viewerUserId, otherUser.id) + }; +} + +function userBlockKey(blockerId, blockedId) { + return `${Number(blockerId)}:${Number(blockedId)}`; +} + +export function isDemoUserBlocked(blockerId, blockedId) { + return demoState.userBlocks.has(userBlockKey(blockerId, blockedId)); +} + +export function setDemoUserBlocked(blockerId, blockedId, blocked) { + const key = userBlockKey(blockerId, blockedId); + if (blocked) demoState.userBlocks.add(key); + else demoState.userBlocks.delete(key); +} + +export function getDemoDirectMessageBlockStatus(dmId, senderId) { + const dm = demoState.dms.find((item) => Number(item.id) === Number(dmId)); + const peerId = dm?.participantIds.find((userId) => Number(userId) !== Number(senderId)); + return { + blockedBySender: Boolean(peerId && isDemoUserBlocked(senderId, peerId)), + blockedByPeer: Boolean(peerId && isDemoUserBlocked(peerId, senderId)) + }; } export function getDemoMembers(channel) { diff --git a/frontend/src/locales/en-US.js b/frontend/src/locales/en-US.js index 29e57a56..13628aee 100644 --- a/frontend/src/locales/en-US.js +++ b/frontend/src/locales/en-US.js @@ -97,7 +97,12 @@ export default { 'chat.noConversationSelected': 'No conversation selected', 'chat.roomAccessRevokedNamed': 'You no longer have access to "{name}".', 'chat.roomAccessRevoked': 'You no longer have access to this conversation.', - 'chat.deleteMessageConfirm': 'Delete this message? It will disappear for everyone in this conversation.', + 'chat.deleteMessageConfirm': 'Delete this message? It will disappear for everyone in this conversation.', + 'chat.blockUser': 'Block this user', + 'chat.unblockUser': 'Unblock user', + 'chat.block': 'Block', + 'chat.unblock': 'Unblock', + 'chat.blockUserConfirm': 'Block {name}? Neither of you will be able to send direct messages until you unblock them.', 'chat.addPeople': 'Add people', 'chat.loadingConversations': 'Loading...', 'chat.noConversations': 'No conversations', diff --git a/frontend/src/locales/zh-CN.js b/frontend/src/locales/zh-CN.js index b8c7c282..33e6e6d1 100644 --- a/frontend/src/locales/zh-CN.js +++ b/frontend/src/locales/zh-CN.js @@ -97,7 +97,12 @@ export default { 'chat.noConversationSelected': '未选择会话', 'chat.roomAccessRevokedNamed': '你已无法访问“{name}”。', 'chat.roomAccessRevoked': '你已无法访问这个会话。', - 'chat.deleteMessageConfirm': '确认删除这条消息吗?删除后会话中的所有人都将看不到它。', + 'chat.deleteMessageConfirm': '确认删除这条消息吗?删除后会话中的所有人都将看不到它。', + 'chat.blockUser': '拉黑此用户', + 'chat.unblockUser': '解除拉黑', + 'chat.block': '拉黑', + 'chat.unblock': '解除拉黑', + 'chat.blockUserConfirm': '确定要拉黑{name}吗?拉黑后,双方将无法继续发送私信。', 'chat.addPeople': '添加人员', 'chat.loadingConversations': '加载中...', 'chat.noConversations': '暂无会话', diff --git a/frontend/src/localized-error.js b/frontend/src/localized-error.js index 90ea497b..30f7f919 100644 --- a/frontend/src/localized-error.js +++ b/frontend/src/localized-error.js @@ -54,7 +54,9 @@ const fixedErrorTranslations = new Map([ ['消息不存在', 'Message not found'], ['无权删除该消息', 'You do not have permission to delete this message'], ['消息不存在或已被删除', 'Message not found or already deleted'], - ['消息操作失败', 'Message operation failed'], + ['消息操作失败', 'Message operation failed'], + ['发送被拒,你已经被拉黑', 'Message rejected. This user has blocked you'], + ['请先解除拉黑再发送', 'Unblock this user before sending a message'], ['头像不存在', 'Avatar not found'], ['Telegram Bridge 未配置', 'Telegram Bridge is not configured'], ['Telegram 头像暂时不可用', 'Telegram avatar is temporarily unavailable'], diff --git a/frontend/src/pages/ChatPage.vue b/frontend/src/pages/ChatPage.vue index 20c12f16..484f631b 100644 --- a/frontend/src/pages/ChatPage.vue +++ b/frontend/src/pages/ChatPage.vue @@ -1,5 +1,5 @@