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

310 lines
15 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 { downloadAttachment } from './attachments'
import type { Attachment } from './attachments'
import MediaPreview from './MediaPreview.vue'
import VoiceMessage from './VoiceMessage.vue'
import VoiceRecorder from './VoiceRecorder.vue'
import { enableChat, trust } from './chat'
import { discardPendingGroupMessage, groupAttachmentPath, groupQuote, publishGroup, sendGroupMessage, setGroupFavorite, synchronizeGroup } from './group-chat'
import type { GroupDetail, GroupDevice, GroupLine } from './group-chat'
const props = defineProps<{ group: GroupDetail }>()
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 search = ref('')
const favoritesOnly = ref(false)
const replying = ref<GroupLine>()
const editing = ref<GroupLine>()
const recalling = ref<GroupLine>()
const file = ref<File>()
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()
return (view.value?.lines ?? []).filter((line) =>
(!favoritesOnly.value || line.favorite) &&
(!query || [line.text, line.quote, line.attachment?.name].some((part) => part?.toLowerCase().includes(query))))
})
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>
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)
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 ?? ''
}
}
}
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
}
}
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 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 chooseFile(event: Event) {
const input = event.target as HTMLInputElement
file.value = input.files?.[0]
input.value = ''
}
function sendFile() {
const identity = session.identity
const selectedFile = file.value
if (identity && selectedFile) void run(async () => {
await sendGroupMessage(identity, props.group, selectedFile, session.authorized)
file.value = undefined
await refresh()
})
}
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 discard() {
const identity = session.identity
if (identity) void run(async () => {
await discardPendingGroupMessage(identity, props.group)
await refresh()
})
}
watch(() => props.group.membershipVersion, () => void run(refresh))
watch(currentEpoch, (epoch, previous) => {
if (!previous || epoch === previous) return
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(() => { if (code.value) void run(refresh, false) }, 2500) })
onBeforeUnmount(() => clearInterval(timer))
</script>
<template>
<section class="group-chat" aria-label="群消息">
<h3>群消息</h3>
<p v-if="error" class="error" role="alert">{{ error }}</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>
<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?.lines.length || search || favoritesOnly" 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 && (search.trim() || favoritesOnly)" class="muted" role="status">没有匹配的群消息。</p>
<ul v-if="lines.length" class="group-chat-lines" aria-label="群消息记录">
<li v-for="line in lines" :key="[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>
<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>
<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" />
<label>选择群附件 <input type="file" :disabled="busy || view?.hasPending" @change="chooseFile"></label>
<div v-if="file" class="message-actions">
<span>{{ file.name }}</span>
<button type="button" class="plain" :disabled="busy || view?.hasPending" @click="sendFile">发送群附件</button>
<button type="button" class="plain" :disabled="busy" @click="file = undefined">取消</button>
</div>
</div>
</template>
</section>
</template>
<style scoped>
.group-chat { display: grid; gap: .7rem; padding-block: 1rem; }
.group-chat p, .group-chat h3 { margin: 0; }
.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-chat-composer { display: grid; gap: .55rem; }
.group-chat-composer textarea { display: block; width: 100%; resize: vertical; font: inherit; }
.group-chat button { justify-self: start; }
.media-preview :deep(img), .media-preview :deep(video) { display: block; max-width: 100%; max-height: 18rem; }
</style>