支持私聊附件多选拖拽和批量重试

This commit is contained in:
xhgit committed 2026-11-15 22:41:23 +08:00
1 parent ec2679b991
commit 2931383906
8 files changed
+166 -35

No files matched your search

+1 -1
View File
@@ -22,7 +22,7 @@
| 私聊会话 | 会话置顶随账号同步。当前设备的未读数可在重新登录后恢复,免打扰会话仍显示未读。 |
| 加密群聊 | 创建群组、通过联系人或一次性链接及二维码邀请、管理成员和转让群主。群主可发布加密公告。群列表显示本机未读,并按账号同步置顶和免打扰。 |
| 消息通知 | 可在本机启用私聊和群聊的系统通知。联系人和群组可单独免打扰,密文仍会同步。 |
| 加密附件 | 两端可在私聊和群聊发送、下载最多 8 MiB 的文件,并在本机预览图片和视频。群聊支持多选、拖拽发送,以及文件、图片和视频分类。 |
| 加密附件 | 两端可在私聊和群聊多选或拖入文件,每批最多 8 个,每个最大 8 MiB。图片、视频在本机预览,群聊支持按附件类型查看。 |
| 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 |
| 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索、收藏和本机删除。可打开消息里的网页链接,并将消息转发到加密群或已核验的联系人设备。私聊支持可选加密已读回执。 |
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 |
+6
View File
@@ -216,3 +216,9 @@ Windows Electron 与 Edge 实测通知 API 调用、提醒跳转及免打扰后
置顶会话排在普通会话之前,设置随账号同步。会话列表取当前设备的未读投递,包含免打扰联系人。设备在前台打开已验证的会话后,客户端提交本次已处理的游标。按接收设备和发送设备分别存储游标,已读回执仍由用户独立控制。升级前的投递保留原有历史,从升级后的新增消息开始计数。
接口测试验证同账号设备的计数隔离、游标权限、撤销后拒绝提交以及旧游标重试。Windows 与 Edge 验证置顶隔离、静音未读提示和会话查看后清除。
## 私聊附件批量发送
Windows 和 Web 可以多选或拖入待发送附件,移除单项或清空列表。每批最多 8 个,单个文件最大 8 MiB。客户端逐个加密、上传并提交。上传中断时,未进入加密发件箱的文件保留在当前待发列表,由用户继续发送。已进入发件箱的封包沿用原消息 ID 进行投递重试。待发列表在切换联系人或对方设备时重置。
Windows 与 Edge 验证多选、拖拽、移除、清空和数量上限。第二个上传请求中断后仅重试剩余文件,接收端只收到一份先前已送达的文件。
+49 -2
View File
@@ -161,8 +161,37 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
const contents = Buffer.from('端到端文件 ' + randomBytes(32).toString('hex'))
const fileName = '跨端验收.txt'
const remainingFile = '私聊批量重试.txt'
const discardedFile = '待移除附件.txt'
const payload = (name, buffer = Buffer.from(name)) => ({ name, mimeType: 'text/plain', buffer })
const dropZone = (page) => page.getByRole('region', { name: '私聊附件发送区' })
const sendBatch = (page) => dropZone(page).getByRole('button', { name: '发送私聊附件', exact: true }).click()
const queue = dropZone(windows).getByRole('list', { name: '待发私聊附件' })
const transfer = await windows.evaluateHandle((name) => {
const data = new DataTransfer()
data.items.add(new File([name], name, { type: 'text/plain' }))
return data
}, remainingFile)
await dropZone(windows).locator('input:enabled').setInputFiles([payload(fileName, contents), payload(discardedFile)])
assert.equal(await queue.getByRole('listitem').count(), 2)
await queue.getByRole('button', { name: '移除 ' + discardedFile, exact: true }).click()
await dropZone(windows).dispatchEvent('dragover', { dataTransfer: transfer })
await dropZone(windows).dispatchEvent('drop', { dataTransfer: transfer })
await transfer.dispose()
assert.deepEqual(await queue.getByRole('listitem').locator('span').allTextContents(), [fileName, remainingFile])
assert.equal(await web.getByRole('button', { name: '下载 ' + fileName, exact: true }).count(), 0)
const uploadMatcher = (url) => url.pathname.startsWith('/api/v1/attachments/') && url.searchParams.has('recipient')
let attempts = 0
const failSecond = async (route) => {
if (route.request().method() === 'POST' && ++attempts === 2) {
await route.fulfill({ status: 503, headers: { 'access-control-allow-origin': 'xhchat://app' },
json: { error: { message: '私聊附件上传暂不可用' } } })
} else await route.continue()
}
await windows.route(uploadMatcher, failSecond)
const upload = windows.waitForRequest((req) => req.method() === 'POST' && req.url().includes('/api/v1/attachments/'))
await windows.locator('input[type=file]').setInputFiles({ name: fileName, mimeType: 'text/plain', buffer: contents })
await sendBatch(windows)
const fileRequest = await upload
const uploaded = fileRequest.postDataBuffer()
assert.ok(uploaded)
@@ -171,6 +200,14 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
assert.ok(!fileRequest.url().includes(encodeURIComponent(fileName)))
const fileButton = web.getByRole('button', { name: '下载 ' + fileName, exact: true })
await fileButton.waitFor()
await windows.getByRole('alert').getByText('私聊附件上传暂不可用', { exact: true }).waitFor()
assert.deepEqual(await queue.getByRole('listitem').locator('span').allTextContents(), [remainingFile])
await windows.unroute(uploadMatcher, failSecond)
await sendBatch(windows)
await web.getByRole('button', { name: '下载 ' + remainingFile, exact: true }).waitFor()
await queue.waitFor({ state: 'detached' })
assert.equal(await fileButton.count(), 1)
assert.equal(await web.getByRole('button', { name: '下载 ' + discardedFile, exact: true }).count(), 0)
const fileURL = new URL(fileRequest.url())
await web.route(fileURL.origin + fileURL.pathname, async (route) => {
const response = await route.fetch()
@@ -205,7 +242,17 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
})
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jf2sAAAAASUVORK5CYII=', 'base64')
await web.locator('input[type=file]').setInputFiles({ name: '加密预览.png', mimeType: 'image/png', buffer: pixel })
const webInput = dropZone(web).locator('input:enabled')
const webQueue = dropZone(web).getByRole('list', { name: '待发私聊附件' })
await webInput.setInputFiles(Array.from({ length: 9 }, (_, index) => payload('容量测试' + index + '.txt')))
await web.getByText('每批最多发送 8 个私聊附件', { exact: true }).waitFor()
assert.equal(await webQueue.count(), 0)
await webInput.setInputFiles(payload('清空测试.txt'))
await webQueue.getByText('清空测试.txt', { exact: true }).waitFor()
await dropZone(web).getByRole('button', { name: '清空待发附件', exact: true }).click()
await webQueue.waitFor({ state: 'detached' })
await webInput.setInputFiles({ name: '加密预览.png', mimeType: 'image/png', buffer: pixel })
await sendBatch(web)
await windows.getByRole('button', { name: '预览 加密预览.png' }).click()
const image = windows.getByRole('img', { name: '加密预览.png' })
await image.waitFor()
+4 -5
View File
@@ -628,12 +628,11 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
await windows.getByRole('link', { name: names[0] }).click()
await windows.getByRole('button', { name: '启用本机加密聊天' }).click()
const privateFile = '私聊文件-' + id() + '.txt'
const privateAttachments = windows.getByRole('region', { name: '私聊附件发送区' })
await privateAttachments.locator('input:enabled').setInputFiles({ name: privateFile, mimeType: 'text/plain', buffer: contents })
const originalUpload = windows.waitForResponse((item) => /\/api\/v1\/attachments\//.test(item.url()) && item.request().method() === 'POST')
const attachmentInput = windows.locator('input[type=file]:enabled')
const [originalFile] = await Promise.all([
originalUpload,
attachmentInput.setInputFiles({ name: privateFile, mimeType: 'text/plain', buffer: contents }),
])
await privateAttachments.getByRole('button', { name: '发送私聊附件', exact: true }).click()
const originalFile = await originalUpload
assert.equal(originalFile.status(), 204)
const originalBytes = originalFile.request().postDataBuffer()
assert.ok(originalBytes && originalBytes.length === contents.length + 16)
+2 -7
View File
@@ -481,11 +481,11 @@ onBeforeUnmount(() => {
<div v-if="ready && !editing" class="group-chat-composer">
<VoiceRecorder v-if="currentEpoch" :key="currentEpoch" :epoch="currentEpoch" :disabled="busy || view?.hasPending || !!pendingVoice"
@send="sendVoice" @error="error = $event" />
<section class="group-drop-zone" aria-label="群附件发送区" :class="{ dragging: draggingFiles }"
<section class="attachment-drop-zone" aria-label="群附件发送区" :class="{ dragging: draggingFiles }"
@dragover="dragFiles" @dragleave="leaveDropArea" @drop="dropFiles">
<label>选择群附件 <input type="file" multiple :disabled="busy || view?.hasPending" @change="chooseFiles"></label>
<p class="muted">也可拖入文件。每批最多 8 个,单个文件最大 8 MiB。</p>
<ul v-if="files.length" class="group-file-queue" aria-label="待发附件">
<ul v-if="files.length" class="attachment-queue" aria-label="待发附件">
<li v-for="(item, index) in files" :key="item.name + '/' + index">
<span>{{ item.name }}</span>
<button type="button" class="plain" :aria-label="'移除 ' + item.name" :disabled="busy" @click="files.splice(index, 1)">移除</button>
@@ -520,11 +520,6 @@ onBeforeUnmount(() => {
.group-media li { min-width: 0; padding: .7rem; border: 1px solid var(--line); border-radius: .45rem; }
.group-chat-composer { display: grid; gap: .55rem; }
.group-chat-composer textarea { display: block; width: 100%; resize: vertical; font: inherit; }
.group-drop-zone { display: grid; gap: .5rem; padding: .65rem .8rem; border: 1px dashed var(--line); border-radius: .45rem; }
.group-drop-zone.dragging { border-color: var(--green); background: var(--green-soft); }
.group-file-queue { display: grid; gap: .35rem; margin: 0; padding: 0; list-style: none; }
.group-file-queue li { display: flex; align-items: baseline; justify-content: space-between; gap: .5rem; }
.group-file-queue span { overflow-wrap: anywhere; }
.group-chat button { justify-self: start; }
.media-preview :deep(img), .media-preview :deep(video) { display: block; max-width: 100%; max-height: 18rem; }
</style>
+3 -1
View File
@@ -217,7 +217,8 @@ export function mutateMessage(identity: ChatIdentity, user: string, peer: Peer,
})
}
export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call, reply?: ChatLine) {
export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call,
{ reply, onQueued }: { reply?: ChatLine; onQueued?: () => void } = {}) {
return update(identity, async (state, save, factory) => {
const current = (await directory(call, user)).find((item) => item.id === peer.id)
if (!current || state.pinned[current.id] !== current.publicKey) throw new Error('发送前请核验对方设备安全码')
@@ -257,6 +258,7 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, content:
state.lines.push({ id, peer: current.id, contact: user, text, attachment, quote: attachment ? undefined : quote, time: new Date().toISOString(), own: true })
state.engine = base64(engine.snapshot())
await save(state)
onQueued?.()
await flush(state, save, call)
} finally {
engine.free()
+6
View File
@@ -97,6 +97,12 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so
.media-preview img, .media-preview video { display: block; max-width: min(300px, 100%); max-height: 220px; border-radius: 5px; }
.chat-compose { display: grid; gap: 8px; }
.chat-compose button { justify-self: end; }
.attachment-drop-zone { display: grid; gap: .5rem; padding: .65rem .8rem; border: 1px dashed var(--line); border-radius: .45rem; }
.attachment-drop-zone.dragging { border-color: var(--green); background: var(--green-soft); }
.attachment-drop-zone p { margin: 0; }
.attachment-queue { display: grid; gap: .35rem; margin: 0; padding: 0; list-style: none; }
.attachment-queue li { display: flex; align-items: baseline; justify-content: space-between; gap: .5rem; }
.attachment-queue span { overflow-wrap: anywhere; }
.chat-filters, .chat-quote, .message-actions { display: flex; gap: 6px; flex-wrap: wrap; align-items: end; }
.chat-filters label:first-child { flex: 1 1 180px; }
.chat-checkbox { display: flex; align-items: center; gap: 6px; padding: 10px 4px; }
+95 -19
View File
@@ -9,7 +9,7 @@ import { forwardContent } from '../chat/group-chat'
import type { ForwardDestination } from '../chat/group-chat'
import ForwardDialog from '../chat/ForwardDialog.vue'
import type { Contact } from '../contacts'
import { downloadAttachment } from '../chat/attachments'
import { downloadAttachment, maxAttachmentSize } from '../chat/attachments'
import type { Attachment } from '../chat/attachments'
import VoiceRecorder from '../chat/VoiceRecorder.vue'
import VoiceMessage from '../chat/VoiceMessage.vue'
@@ -38,7 +38,11 @@ const unread = ref<Record<string, number>>({})
const conversationQuery = ref('')
const history = ref<HTMLOListElement>()
const shareRead = ref(false)
const pendingFile = ref<File>()
const pendingVoice = ref<File>()
const files = ref<File[]>([])
const draggingFiles = ref(false)
const batchProgress = ref('')
const maxBatchFiles = 8
const view = ref<Awaited<ReturnType<typeof synchronize>>>()
const target = computed(() => typeof route.params.user === 'string' ? route.params.user : '')
const activeContact = computed(() => contacts.value.find((item) => item.id === target.value && item.state === 'friend'))
@@ -220,7 +224,7 @@ function submit() {
if (editing.value) {
await mutateMessage(session.identity, target.value, peer.value, { action: 'edit', id: editing.value.id, text: draft.value }, session.authorized)
} else {
await send(session.identity, target.value, peer.value, draft.value, session.authorized, reply.value)
await send(session.identity, target.value, peer.value, draft.value, session.authorized, { reply: reply.value })
}
draft.value = ''
reply.value = undefined
@@ -244,29 +248,84 @@ function recall() {
})
}
function attach(event: Event) {
function chooseFiles(event: Event) {
const input = event.target as HTMLInputElement
const file = input.files?.[0]
if (input.files) addFiles(input.files)
input.value = ''
if (file) pendingFile.value = file
}
function sendFile(file: File) {
function addFiles(selection: FileList) {
if (!trusted.value || batchProgress.value || editing.value || !selection.length) return
error.value = ''
if (files.value.length + selection.length > maxBatchFiles) {
error.value = '每批最多发送 8 个私聊附件'
return
}
const incoming = Array.from(selection)
const oversized = incoming.find((item) => item.size > maxAttachmentSize)
if (oversized) {
error.value = oversized.name + ' 超过单文件 8 MiB 上限'
return
}
files.value.push(...incoming)
}
function dragFiles(event: DragEvent) {
if (!event.dataTransfer?.types.includes('Files')) return
event.preventDefault()
draggingFiles.value = Boolean(trusted.value && !busy.value && !editing.value)
event.dataTransfer.dropEffect = draggingFiles.value ? 'copy' : 'none'
}
function leaveDropArea(event: DragEvent) {
const area = event.currentTarget as HTMLElement
if (!(event.relatedTarget instanceof Node) || !area.contains(event.relatedTarget)) draggingFiles.value = false
}
function dropFiles(event: DragEvent) {
draggingFiles.value = false
if (!event.dataTransfer?.types.includes('Files')) return
event.preventDefault()
addFiles(event.dataTransfer.files)
}
function sendFiles() {
const identity = session.identity
const device = peer.value
const contact = target.value
const queue = files.value
if (!identity || !device || !trusted.value || !queue.length) return
void execute(async () => {
const total = queue.length
try {
for (let index = 0; index < total && active; index++) {
const file = queue[0]
if (!file || files.value !== queue || selected.value !== device.id || target.value !== contact) break
batchProgress.value = `正在发送 ${index + 1} / ${total}`
await send(identity, contact, device, file, session.authorized, { onQueued: () => queue.shift() })
}
} catch (cause) {
if (active && target.value === contact && selected.value === device.id) await refresh().catch(() => {})
throw cause
} finally {
batchProgress.value = ''
}
if (active && target.value === contact && selected.value === device.id) await refresh()
})
}
function sendVoice(file: File) {
pendingVoice.value = file
}
watch([pendingVoice, busy], ([file, inProgress]) => {
if (!file || inProgress) return
pendingVoice.value = undefined
void execute(async () => {
if (!session.identity || !peer.value) return
await send(session.identity, target.value, peer.value, file, session.authorized)
await refresh()
})
}
function sendVoice(file: File) {
pendingFile.value = file
}
watch([pendingFile, busy], ([file, inProgress]) => {
if (!file || inProgress) return
pendingFile.value = undefined
sendFile(file)
})
function saveAttachment(attachment: Attachment) {
@@ -321,7 +380,9 @@ watch(selected, () => {
recalling.value = undefined
forwarding.value = undefined
forwardStatus.value = ''
pendingFile.value = undefined
pendingVoice.value = undefined
files.value = []
draggingFiles.value = false
draft.value = ''
scheduleReceipt()
queueSeen()
@@ -460,7 +521,22 @@ onBeforeUnmount(() => {
<span>引用 {{ (reply.text || reply.attachment?.name || '').slice(0, 80) }}</span>
<button type="button" class="plain" @click="reply = undefined">取消引用</button>
</div>
<label v-if="!editing">发送附件<input type="file" :disabled="busy" @change="attach"></label>
<section v-if="!editing" class="attachment-drop-zone" aria-label="私聊附件发送区" :class="{ dragging: draggingFiles }"
@dragover="dragFiles" @dragleave="leaveDropArea" @drop="dropFiles">
<label>选择私聊附件 <input type="file" multiple :disabled="busy" @change="chooseFiles"></label>
<p class="muted">也可拖入文件。每批最多 8 个,单个文件最大 8 MiB。</p>
<ul v-if="files.length" class="attachment-queue" aria-label="待发私聊附件">
<li v-for="(item, index) in files" :key="item.name + '/' + index">
<span>{{ item.name }}</span>
<button type="button" class="plain" :aria-label="'移除 ' + item.name" :disabled="busy" @click="files.splice(index, 1)">移除</button>
</li>
</ul>
<p v-if="batchProgress" role="status">{{ batchProgress }}</p>
<div v-if="files.length" class="message-actions">
<button type="button" class="plain" :disabled="busy" @click="sendFiles">发送私聊附件</button>
<button type="button" class="plain" :disabled="busy" @click="files = []">清空待发附件</button>
</div>
</section>
<VoiceRecorder v-if="!editing" :key="selected" :disabled="busy" @send="sendVoice" @error="error = $event" />
<label>消息<textarea v-model="draft" required rows="3" maxlength="4000"></textarea></label>
<button class="primary" :disabled="busy || !draft.trim()">{{ editing ? '保存编辑' : '发送' }}</button>