Files
XHChat/web/src/chat/GroupChat.vue
T

505 lines
24 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useSession } from '../session'
import { APIError } from '../api'
import { downloadAttachment, maxAttachmentSize } from './attachments'
import type { Attachment } from './attachments'
import MediaPreview from './MediaPreview.vue'
import ForwardDialog from './ForwardDialog.vue'
import VoiceMessage from './VoiceMessage.vue'
import VoiceRecorder from './VoiceRecorder.vue'
import { enableChat, trust } from './chat'
import { discardPendingGroupMessage, forwardGroupMessage, groupAttachmentPath, groupQuote, publishGroup, sendGroupMessage, setGroupFavorite, synchronizeGroup } from './group-chat'
import type { ForwardDestination, GroupDetail, GroupDevice, GroupLine } from './group-chat'
const props = defineProps<{ group: GroupDetail }>()
const emit = defineEmits<{ seen: [] }>()
const session = useSession()
const view = ref<Awaited<ReturnType<typeof synchronizeGroup>>>()
const code = ref('')
const codes = ref<Record<string, string>>({})
const selected = ref<Record<string, string>>({})
const draft = ref('')
const announcementDraft = ref<string>()
const search = ref('')
const favoritesOnly = ref(false)
const historyViews = [
{ id: 'messages', label: '消息', empty: '没有匹配的群消息。' },
{ id: 'files', label: '群文件', empty: '没有匹配的群文件。' },
{ id: 'images', label: '群图片', empty: '没有匹配的群图片。' },
{ id: 'videos', label: '群视频', empty: '没有匹配的群视频。' },
] as const
const historyView = ref<typeof historyViews[number]>(historyViews[0])
const mediaPageSize = 24
const mediaLimit = ref(mediaPageSize)
const replying = ref<GroupLine>()
const editing = ref<GroupLine>()
const recalling = ref<GroupLine>()
const forwarding = ref<GroupLine>()
const forwardStatus = ref('')
const files = ref<File[]>([])
const maxBatchFiles = 8
const draggingFiles = ref(false)
const batchProgress = ref('')
const pendingVoice = ref<{ file: File; epoch: string }>()
const busy = ref(false)
const error = ref('')
const ready = computed(() => view.value?.ready && view.value.current?.membershipVersion === props.group.membershipVersion)
const currentEpoch = computed(() => ready.value ? view.value?.current?.id : undefined)
const lines = computed(() => {
const query = search.value.trim().toLowerCase()
const mode = historyView.value.id
const matches = (view.value?.lines ?? []).filter((line) => {
if (favoritesOnly.value && !line.favorite) return false
if (mode === 'messages') {
return !query || [line.text, line.quote, line.attachment?.name].some((part) => part?.toLowerCase().includes(query))
}
const attachment = line.attachment
if (line.recalled || !attachment || attachment.voice || !attachment.name.toLowerCase().includes(query)) return false
return mode === 'files' || attachment.media?.startsWith(mode === 'images' ? 'image/' : 'video/')
})
return mode === 'messages' ? matches : matches.reverse()
})
const visibleLines = computed(() => historyView.value.id === 'messages' ? lines.value : lines.value.slice(0, mediaLimit.value))
const members = computed(() => props.group.members.filter((member) => member.state === 'active' && member.id !== session.identity?.user.id))
const canPublish = computed(() => Boolean(view.value && !view.value.current && members.value.every((member) =>
view.value?.devices.some((device) => device.user === member.id && device.id === selected.value[member.id] && pinned(device)))))
let timer: ReturnType<typeof setInterval>
let refreshTimer: ReturnType<typeof setTimeout> | undefined
let refreshPending = false
let lastSeen = '0'
let active = true
function pinned(device: GroupDevice) {
return view.value?.pinned[device.id] === device.publicKey
}
async function refresh() {
const identity = session.identity
if (!code.value || !identity) return
view.value = await synchronizeGroup(identity, props.group, session.authorized)
if (!active) return
for (const member of members.value) {
const devices = view.value.devices.filter((device) => device.user === member.id)
if (!devices.some((device) => device.id === selected.value[member.id] && pinned(device))) {
selected.value[member.id] = devices.find(pinned)?.id ?? ''
}
}
if (view.value.hasMore) queueRefresh()
const { cursor } = view.value
if (!ready.value || document.visibilityState !== 'visible' || cursor === lastSeen || cursor === '0') return
try {
await session.authorized('/groups/' + encodeURIComponent(props.group.id) + '/seen', 'POST', { sequence: cursor })
} catch (cause) {
// Retention or member changes can invalidate an already cached cursor.
if (!(cause instanceof APIError) || cause.status !== 404) throw cause
}
if (!active) return
lastSeen = cursor
emit('seen')
}
async function run(action: () => Promise<void>, manual = true) {
if (busy.value) return
busy.value = true
if (manual) error.value = ''
try {
await action()
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '群消息操作失败'
} finally {
busy.value = false
if (refreshPending) queueRefresh()
}
}
function queueRefresh() {
if (!active || !code.value) return
refreshPending = true
if (busy.value || refreshTimer) return
refreshTimer = setTimeout(() => {
refreshTimer = undefined
if (busy.value) return
refreshPending = false
void run(refresh, false)
}, 350)
}
function enable() {
const identity = session.identity
if (identity) void run(async () => {
code.value = await enableChat(identity, session.authorized)
await refresh()
})
}
function verifyDevice(device: GroupDevice) {
const identity = session.identity
if (identity) void run(async () => {
await trust(identity, device.user, device, codes.value[device.id] ?? '')
delete codes.value[device.id]
await refresh()
})
}
function establish() {
const identity = session.identity
if (identity) void run(async () => {
await publishGroup(identity, props.group, selected.value, session.authorized)
await refresh()
})
}
function saveAnnouncement() {
const identity = session.identity
const announcement = announcementDraft.value
if (!identity || announcement === undefined) return
void run(async () => {
await sendGroupMessage(identity, props.group, { announcement }, session.authorized)
announcementDraft.value = undefined
await refresh()
})
}
function send() {
const identity = session.identity
if (identity) void run(async () => {
const text = draft.value
if (editing.value?.epoch) {
await sendGroupMessage(identity, props.group, { action: 'edit', id: editing.value.id, epoch: editing.value.epoch, text }, session.authorized)
} else {
await sendGroupMessage(identity, props.group, replying.value ? { text, reply: replying.value } : text, session.authorized)
}
if (draft.value === text) draft.value = ''
editing.value = undefined
replying.value = undefined
await refresh()
})
}
function edit(line: GroupLine) {
editing.value = line
replying.value = undefined
draft.value = line.text
}
function recall() {
const identity = session.identity
const { id, epoch } = recalling.value ?? {}
if (!identity || !id || !epoch) return
void run(async () => {
await sendGroupMessage(identity, props.group, { action: 'recall', id, epoch }, session.authorized)
recalling.value = undefined
await refresh()
})
}
function chooseFiles(event: Event) {
const input = event.target as HTMLInputElement
if (input.files) addFiles(input.files)
input.value = ''
}
function addFiles(selection: FileList) {
if (!currentEpoch.value || busy.value || view.value?.hasPending || editing.value || !selection.length) return
error.value = ''
if (selection.length + files.value.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(currentEpoch.value && !busy.value && !view.value?.hasPending && !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')) {
event.preventDefault()
addFiles(event.dataTransfer.files)
}
}
function sendFiles() {
const identity = session.identity
const epoch = currentEpoch.value
if (!identity || !epoch || !files.value.length) return
void run(async () => {
const total = files.value.length
try {
for (let index = 0; index < total && active; index++) {
const file = files.value[0]
if (!file || epoch !== currentEpoch.value) break
batchProgress.value = `正在发送 ${index + 1} / ${total}`
await sendGroupMessage(identity, props.group, file, session.authorized, epoch)
// Once the encrypted envelope is queued, that outbox owns retrying it.
files.value.shift()
await refresh()
if (view.value?.hasPending) break
}
} finally {
batchProgress.value = ''
}
})
}
function sendVoice(recording: File, epoch?: string) {
if (epoch) pendingVoice.value = { file: recording, epoch }
}
function download(attachment: Attachment) {
void run(() => downloadAttachment(attachment, session.authorized, groupAttachmentPath(props.group, attachment.id)))
}
function favorite(line: GroupLine) {
const identity = session.identity
if (identity) void run(async () => {
const updated = await setGroupFavorite(identity, props.group, line, !line.favorite)
if (view.value) view.value.lines = updated
})
}
function beginForward(line: GroupLine) {
forwardStatus.value = ''
forwarding.value = line
}
function forward(destination: ForwardDestination) {
const identity = session.identity
const source = forwarding.value
if (identity && source) void run(async () => {
forwardStatus.value = await forwardGroupMessage(identity, props.group, source, destination, session.authorized)
forwarding.value = undefined
})
}
function discard() {
const identity = session.identity
if (identity) void run(async () => {
await discardPendingGroupMessage(identity, props.group)
await refresh()
})
}
watch(() => props.group.membershipVersion, queueRefresh)
watch([historyView, search, favoritesOnly], () => { mediaLimit.value = mediaPageSize })
watch(() => session.groupChange, (event) => { if (event?.groupId === props.group.id) queueRefresh() })
watch(() => session.connection, (connection) => { if (connection === '实时连接已建立') queueRefresh() })
watch(currentEpoch, (epoch, previous) => {
if (!previous || epoch === previous) return
announcementDraft.value = undefined
draggingFiles.value = false
if (editing.value || replying.value) draft.value = ''
editing.value = undefined
replying.value = undefined
recalling.value = undefined
})
watch([pendingVoice, busy, currentEpoch, () => view.value?.hasPending], ([voice, inProgress, epoch, hasPending]) => {
const identity = session.identity
if (!voice || !identity) return
if (voice.epoch !== epoch) {
pendingVoice.value = undefined
error.value = '群加密会话已变更,请重新录音'
return
}
if (inProgress || hasPending) return
pendingVoice.value = undefined
void run(async () => {
await sendGroupMessage(identity, props.group, voice.file, session.authorized, voice.epoch)
await refresh()
})
})
onMounted(() => {
timer = setInterval(queueRefresh, 15_000)
document.addEventListener('visibilitychange', queueRefresh)
})
onBeforeUnmount(() => {
active = false
refreshPending = false
clearTimeout(refreshTimer)
clearInterval(timer)
document.removeEventListener('visibilitychange', queueRefresh)
})
</script>
<template>
<section class="group-chat" aria-label="群消息" @dragover.prevent @drop.prevent>
<h3>群消息</h3>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<p v-if="forwardStatus" role="status">{{ forwardStatus }}</p>
<button v-if="!code" class="primary" :disabled="busy" @click="enable">启用本机群聊</button>
<template v-else>
<p v-if="view?.warning" class="muted" role="status">{{ view.warning }}</p>
<p v-if="ready" role="status">群加密已建立</p>
<p v-else-if="view?.current && !view.current.welcome">当前设备未获分配群密钥。</p>
<p v-else-if="!view?.current && group.role !== 'owner'">等待群主建立群加密会话。</p>
<section v-if="view && (view.announcement || (ready && group.role === 'owner'))" class="group-announcement" aria-label="群公告">
<h4>群公告</h4>
<p v-if="view.announcement" class="announcement-text">{{ view.announcement }}</p>
<p v-else class="muted">暂无群公告。</p>
<template v-if="ready && group.role === 'owner'">
<button v-if="announcementDraft === undefined" type="button" class="plain" :disabled="busy || view.hasPending"
@click="announcementDraft = view.announcement ?? ''">{{ view.announcement ? '编辑群公告' : '写群公告' }}</button>
<form v-else class="group-chat-composer" @submit.prevent="saveAnnouncement">
<label>公告内容<textarea v-model="announcementDraft" rows="3" maxlength="2000" /></label>
<div class="message-actions">
<button class="primary" :disabled="busy || view.hasPending || announcementDraft.trim() === (view.announcement ?? '')">
{{ announcementDraft.trim() ? '发布公告' : '清除公告' }}
</button>
<button type="button" class="plain" @click="announcementDraft = undefined">取消</button>
</div>
</form>
</template>
</section>
<details :open="!ready">
<summary>群设备和安全码</summary>
<p>本机安全码 <code class="group-security-code">{{ code }}</code></p>
<p class="muted">请通过线下或可信渠道与群成员核对各自设备的安全码。每位成员在一个群加密会话中使用一台设备。</p>
<div v-for="member in members" :key="member.id" class="group-device-member">
<strong>{{ member.username }}</strong>
<p v-if="!view?.devices.some((device) => device.user === member.id)" class="muted">该成员尚未启用加密。</p>
<div v-for="device in view?.devices.filter((item) => item.user === member.id)" :key="device.id">
<p>{{ device.name }} · {{ device.id.slice(0, 8) }}<span v-if="pinned(device)"> · 已核验</span></p>
<form v-if="!pinned(device)" class="contact-preferences" @submit.prevent="verifyDevice(device)">
<label>{{ member.username }} · {{ device.id.slice(0, 8) }} 安全码<input v-model="codes[device.id]" autocomplete="off" maxlength="96" required></label>
<button class="plain" :disabled="busy">核验设备</button>
</form>
</div>
<label v-if="group.role === 'owner' && !view?.current">{{ member.username }} 的群设备
<select v-model="selected[member.id]">
<option value="">选择已核验设备</option>
<option v-for="device in view?.devices.filter((item) => item.user === member.id && pinned(item))" :key="device.id" :value="device.id">
{{ device.name }} · {{ device.id.slice(0, 8) }}
</option>
</select>
</label>
</div>
<button v-if="group.role === 'owner' && !view?.current" class="primary" :disabled="busy || !canPublish" @click="establish">建立群加密会话</button>
</details>
<div v-if="view" class="group-history-views" role="group" aria-label="群历史视图">
<button v-for="mode in historyViews" :key="mode.id" type="button" class="plain"
:aria-pressed="historyView.id === mode.id" @click="historyView = mode">{{ mode.label }}</button>
</div>
<div v-if="view?.lines.length || search || favoritesOnly || historyView.id !== 'messages'" class="group-chat-search">
<label>搜索本机群消息<input v-model="search" type="search" maxlength="120"></label>
<label class="chat-checkbox"><input v-model="favoritesOnly" type="checkbox">只看收藏</label>
</div>
<p v-if="!lines.length && (historyView.id !== 'messages' || search.trim() || favoritesOnly)" class="muted" role="status">{{ historyView.empty }}</p>
<ul v-if="visibleLines.length" class="group-chat-lines" :class="{ 'group-media': historyView.id !== 'messages' }"
:aria-label="historyView.id === 'messages' ? '群消息记录' : historyView.label">
<li v-for="line in visibleLines" :key="[historyView.id, line.epoch, line.sender, line.id].join('/')">
<small>{{ line.name }} · {{ new Date(line.time).toLocaleString() }}</small>
<blockquote v-if="line.quote">{{ line.quote }}</blockquote>
<p v-if="line.recalled" class="muted">消息已撤回</p>
<VoiceMessage v-else-if="line.attachment?.voice" :attachment="line.attachment" :path="groupAttachmentPath(group, line.attachment.id)" />
<template v-else-if="line.attachment">
<p>{{ line.attachment.name }} · {{ new Intl.NumberFormat().format(line.attachment.size) }} 字节</p>
<MediaPreview v-if="line.attachment.media" :attachment="line.attachment" :path="groupAttachmentPath(group, line.attachment.id)" />
<button type="button" class="plain" :disabled="busy" @click="download(line.attachment)">下载 {{ line.attachment.name }}</button>
</template>
<p v-else>{{ line.text }}</p>
<small v-if="line.edited && !line.recalled" class="muted">已编辑</small>
<div v-if="!line.recalled" class="message-actions">
<button type="button" class="plain" :disabled="busy" @click="favorite(line)">{{ line.favorite ? '取消收藏' : '收藏' }}</button>
<button type="button" class="plain" :disabled="busy" @click="beginForward(line)">转发</button>
<template v-if="currentEpoch && line.epoch === currentEpoch">
<button type="button" class="plain" :disabled="busy || view?.hasPending || !!editing" @click="replying = line">引用</button>
<template v-if="line.sender === session.identity?.device.id">
<button v-if="!line.attachment" type="button" class="plain" :disabled="busy || view?.hasPending" @click="edit(line)">编辑</button>
<button type="button" class="plain" :disabled="busy || view?.hasPending" @click="recalling = line">撤回</button>
</template>
</template>
</div>
</li>
</ul>
<button v-if="visibleLines.length < lines.length" type="button" class="plain" @click="mediaLimit += mediaPageSize">加载更多本机附件</button>
<ForwardDialog v-if="forwarding && view" :key="[forwarding.epoch, forwarding.sender, forwarding.id].join('/')"
:source-group="group.id" :pinned="view.pinned" :busy="busy" @confirm="forward" @cancel="forwarding = undefined" />
<div v-if="ready && recalling" class="confirmation">
<p>撤回后,群成员的聊天界面会更新。成员可能已保存副本。</p>
<button type="button" class="plain" :disabled="busy || view?.hasPending" @click="recall">确认撤回</button>
<button type="button" class="plain" @click="recalling = undefined">取消</button>
</div>
<p v-if="view?.hasPending" role="status">
{{ view.stalePending ? '待发消息属于旧会话。' : '消息待投递,将自动重试。' }}
<button v-if="view.stalePending" class="plain" :disabled="busy" @click="discard">清除待发消息</button>
</p>
<form v-if="ready" class="group-chat-composer" @submit.prevent="send">
<div v-if="editing" class="chat-quote">
<span>编辑消息</span>
<button type="button" class="plain" @click="editing = undefined; draft = ''">取消编辑</button>
</div>
<div v-else-if="replying" class="chat-quote">
<span>引用 {{ groupQuote(replying) }}</span>
<button type="button" class="plain" @click="replying = undefined">取消引用</button>
</div>
<label>群消息<textarea v-model="draft" rows="3" maxlength="8000" required /></label>
<button class="primary" :disabled="busy || view?.hasPending || !draft.trim()">{{ editing ? '保存编辑' : '发送群消息' }}</button>
</form>
<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 }"
@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="待发附件">
<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 || view?.hasPending" @click="sendFiles">发送群附件</button>
<button type="button" class="plain" :disabled="busy" @click="files = []">清空待发附件</button>
</div>
</section>
</div>
</template>
</section>
</template>
<style scoped>
.group-chat { display: grid; gap: .7rem; padding-block: 1rem; }
.group-chat p, .group-chat h3 { margin: 0; }
.group-announcement { display: grid; gap: .45rem; padding: .65rem .8rem; border: 1px solid var(--line); border-radius: .45rem; }
.group-announcement h4 { margin: 0; }
.announcement-text { white-space: pre-wrap; overflow-wrap: anywhere; }
.group-security-code { overflow-wrap: anywhere; }
.group-device-member { margin-block: .75rem; }
.group-chat-lines { display: grid; gap: .75rem; max-height: 24rem; overflow-y: auto; margin: 0; padding: .7rem 0; list-style: none; }
.group-chat-lines p { white-space: pre-wrap; overflow-wrap: anywhere; }
.group-chat-lines blockquote { margin: .25rem 0; padding-inline-start: .5rem; border-inline-start: 2px solid currentColor; overflow-wrap: anywhere; }
.group-chat-search { display: flex; flex-wrap: wrap; align-items: end; gap: .75rem; }
.group-history-views { display: flex; flex-wrap: wrap; gap: .4rem; }
.group-history-views [aria-pressed='true'] { background: var(--green-soft); color: var(--green); }
.group-media { grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr)); align-items: start; }
.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>