476 lines
20 KiB
Vue
476 lines
20 KiB
Vue
<script setup lang="ts">
|
||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||
import { useRoute } from 'vue-router'
|
||
import { useSession } from '../session'
|
||
import { APIError } from '../api'
|
||
import { enableChat, localMessageAction, markRead, mutateMessage, readPrivateForward, recentConversations, send, setReadReceipts, synchronize, trust } from '../chat/chat'
|
||
import type { ChatLine } from '../chat/chat'
|
||
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 type { Attachment } from '../chat/attachments'
|
||
import VoiceRecorder from '../chat/VoiceRecorder.vue'
|
||
import VoiceMessage from '../chat/VoiceMessage.vue'
|
||
import MediaPreview from '../chat/MediaPreview.vue'
|
||
import MessageText from '../chat/MessageText.vue'
|
||
|
||
const session = useSession()
|
||
const route = useRoute()
|
||
const ownCode = ref('')
|
||
const code = ref('')
|
||
const selected = ref('')
|
||
const draft = ref('')
|
||
const search = ref('')
|
||
const favoritesOnly = ref(false)
|
||
const reply = ref<ChatLine>()
|
||
const deleting = ref<ChatLine>()
|
||
const editing = ref<ChatLine>()
|
||
const recalling = ref<ChatLine>()
|
||
const forwarding = ref<ChatLine>()
|
||
const forwardStatus = ref('')
|
||
const error = ref('')
|
||
const busy = ref(false)
|
||
const contacts = ref<Contact[]>([])
|
||
const recent = ref<Record<string, string>>({})
|
||
const unread = ref<Record<string, number>>({})
|
||
const conversationQuery = ref('')
|
||
const history = ref<HTMLOListElement>()
|
||
const shareRead = ref(false)
|
||
const pendingFile = ref<File>()
|
||
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'))
|
||
const peer = computed(() => view.value?.peers.find((item) => item.id === selected.value))
|
||
const trusted = computed(() => peer.value && view.value?.pinned[peer.value.id] === peer.value.publicKey)
|
||
const changed = computed(() => peer.value && view.value?.pinned[peer.value.id] && !trusted.value)
|
||
const conversations = computed(() => {
|
||
const query = conversationQuery.value.trim().toLowerCase()
|
||
return contacts.value.filter((item) => item.state === 'friend' &&
|
||
[item.alias, item.username].some((value) => value.toLowerCase().includes(query)))
|
||
.sort((a, b) => Number(b.pinned) - Number(a.pinned) || (recent.value[b.id] ?? '').localeCompare(recent.value[a.id] ?? '') ||
|
||
(a.alias || a.username).localeCompare(b.alias || b.username))
|
||
})
|
||
const lines = computed(() => {
|
||
const query = search.value.trim().toLowerCase()
|
||
return (view.value?.lines ?? []).filter((line) => line.peer === selected.value &&
|
||
(!favoritesOnly.value || line.favorite) &&
|
||
(!query || [line.text, line.attachment?.name, line.quote].some((part) => part?.toLowerCase().includes(query))))
|
||
})
|
||
let timer: ReturnType<typeof setInterval>
|
||
let receiptTimer: ReturnType<typeof setTimeout> | undefined
|
||
let seenTimer: ReturnType<typeof setTimeout> | undefined
|
||
let unreadTimer: ReturnType<typeof setTimeout> | undefined
|
||
let unreadVersion = 0
|
||
let conversationVersion = 0
|
||
let markingSeen = false
|
||
let active = true
|
||
const seen = new Map<string, string>()
|
||
|
||
async function loadConversations() {
|
||
const identity = session.identity
|
||
if (!identity) return
|
||
const version = ++conversationVersion
|
||
try {
|
||
const [people, dates] = await Promise.all([session.contacts(), recentConversations(identity)])
|
||
if (version !== conversationVersion || session.identity?.device.id !== identity.device.id) return
|
||
contacts.value = people
|
||
recent.value = dates
|
||
} catch (cause) {
|
||
error.value = cause instanceof Error ? cause.message : '无法加载会话'
|
||
}
|
||
}
|
||
|
||
function queueUnread() {
|
||
if (!active) return
|
||
clearTimeout(unreadTimer)
|
||
const version = ++unreadVersion
|
||
unreadTimer = setTimeout(async () => {
|
||
try {
|
||
const counts = await session.authorized<Record<string, number>>('/inbox/unread')
|
||
if (version === unreadVersion) unread.value = counts
|
||
} catch {
|
||
// Retain the latest badges while the service is unavailable.
|
||
}
|
||
}, 200)
|
||
}
|
||
|
||
function queueSeen() {
|
||
if (!active) return
|
||
clearTimeout(seenTimer)
|
||
seenTimer = setTimeout(async () => {
|
||
const device = peer.value?.id
|
||
const sequence = device && view.value?.received[device]
|
||
if (!device || !sequence || !trusted.value || markingSeen || seen.get(device) === sequence ||
|
||
document.visibilityState !== 'visible' || !document.hasFocus()) return
|
||
markingSeen = true
|
||
try {
|
||
await session.authorized('/inbox/seen', 'POST', { senderDevice: device, sequence })
|
||
seen.set(device, sequence)
|
||
queueUnread()
|
||
queueSeen()
|
||
} catch (error) {
|
||
// The server may expire a delivery before the device reports it as seen.
|
||
if (error instanceof APIError && error.status === 404) seen.set(device, sequence)
|
||
} finally {
|
||
markingSeen = false
|
||
}
|
||
}, 200)
|
||
}
|
||
|
||
async function execute(action: () => Promise<void>) {
|
||
if (busy.value || !session.identity) return
|
||
busy.value = true
|
||
error.value = ''
|
||
try {
|
||
await action()
|
||
} catch (cause) {
|
||
error.value = cause instanceof Error ? cause.message : '加密聊天暂不可用'
|
||
} finally {
|
||
busy.value = false
|
||
scheduleReceipt()
|
||
}
|
||
}
|
||
|
||
async function refresh() {
|
||
const identity = session.identity
|
||
if (!identity || !target.value || !ownCode.value) return
|
||
const contact = target.value
|
||
const current = await synchronize(identity, contact, session.authorized)
|
||
if (target.value !== contact) return
|
||
view.value = current
|
||
shareRead.value = current.shareRead
|
||
for (const line of current.lines) {
|
||
if (line.contact && (!recent.value[line.contact] || recent.value[line.contact] < line.time)) {
|
||
recent.value[line.contact] = line.time
|
||
}
|
||
}
|
||
if (!current.peers.some((device) => device.id === selected.value)) selected.value = current.peers[0]?.id ?? ''
|
||
queueSeen()
|
||
}
|
||
|
||
function togglePreference(preference: 'mute' | 'pin') {
|
||
const contact = activeContact.value
|
||
if (!contact) return
|
||
const enabled = preference === 'mute' ? contact.muted : contact.pinned
|
||
void execute(async () => {
|
||
await session.changeContact(contact.id, enabled ? `un${preference}` : preference)
|
||
await loadConversations()
|
||
})
|
||
}
|
||
|
||
function scheduleReceipt() {
|
||
clearTimeout(receiptTimer)
|
||
if (!view.value?.shareRead || busy.value || !trusted.value) return
|
||
receiptTimer = setTimeout(async () => {
|
||
await nextTick()
|
||
const identity = session.identity
|
||
const selectedPeer = peer.value
|
||
const list = history.value
|
||
if (busy.value || !identity || !selectedPeer || !list || document.visibilityState !== 'visible' || !document.hasFocus()) return
|
||
const bounds = list.getBoundingClientRect()
|
||
const ids = Array.from(list.querySelectorAll<HTMLElement>('[data-unread]')).filter((row) => {
|
||
const rect = row.getBoundingClientRect()
|
||
return Math.min(rect.bottom, bounds.bottom, innerHeight) - Math.max(rect.top, bounds.top, 0) >= Math.min(rect.height, 24)
|
||
}).map((row) => row.dataset.unread!).slice(0, 64)
|
||
if (!ids.length) return
|
||
await execute(async () => {
|
||
await markRead(identity, target.value, selectedPeer, ids, session.authorized)
|
||
await refresh()
|
||
})
|
||
}, 300)
|
||
}
|
||
|
||
function toggleReceipts(event: Event) {
|
||
const checked = (event.target as HTMLInputElement).checked
|
||
shareRead.value = checked
|
||
void execute(async () => {
|
||
if (!session.identity) return
|
||
try {
|
||
await setReadReceipts(session.identity, checked)
|
||
} catch (cause) {
|
||
shareRead.value = !checked
|
||
throw cause
|
||
}
|
||
await refresh()
|
||
})
|
||
}
|
||
|
||
function enable() {
|
||
void execute(async () => {
|
||
if (!session.identity) return
|
||
ownCode.value = await enableChat(session.identity, session.authorized)
|
||
await refresh()
|
||
})
|
||
}
|
||
|
||
function confirm() {
|
||
void execute(async () => {
|
||
if (!session.identity || !peer.value) return
|
||
await trust(session.identity, target.value, peer.value, code.value)
|
||
code.value = ''
|
||
await refresh()
|
||
})
|
||
}
|
||
|
||
function submit() {
|
||
void execute(async () => {
|
||
if (!session.identity || !peer.value) return
|
||
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)
|
||
}
|
||
draft.value = ''
|
||
reply.value = undefined
|
||
editing.value = undefined
|
||
await refresh()
|
||
})
|
||
}
|
||
|
||
function edit(line: ChatLine) {
|
||
editing.value = line
|
||
reply.value = undefined
|
||
draft.value = line.text
|
||
}
|
||
|
||
function recall() {
|
||
void execute(async () => {
|
||
if (!session.identity || !peer.value || !recalling.value) return
|
||
await mutateMessage(session.identity, target.value, peer.value, { action: 'recall', id: recalling.value.id }, session.authorized)
|
||
recalling.value = undefined
|
||
await refresh()
|
||
})
|
||
}
|
||
|
||
function attach(event: Event) {
|
||
const input = event.target as HTMLInputElement
|
||
const file = input.files?.[0]
|
||
input.value = ''
|
||
if (file) pendingFile.value = file
|
||
}
|
||
|
||
function sendFile(file: File) {
|
||
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) {
|
||
void execute(() => downloadAttachment(attachment, session.authorized))
|
||
}
|
||
|
||
function localAction(line: ChatLine, action: 'favorite' | 'remove') {
|
||
void execute(async () => {
|
||
if (!session.identity) return
|
||
await localMessageAction(session.identity, line, action)
|
||
deleting.value = undefined
|
||
if (action === 'remove' && reply.value?.id === line.id) reply.value = undefined
|
||
await refresh()
|
||
})
|
||
}
|
||
|
||
function beginForward(line: ChatLine) {
|
||
forwardStatus.value = ''
|
||
forwarding.value = line
|
||
}
|
||
|
||
function submitForward(destination: ForwardDestination) {
|
||
const identity = session.identity
|
||
const message = forwarding.value
|
||
if (identity && message) void execute(async () => {
|
||
const status = await forwardContent(identity, destination, session.authorized,
|
||
() => readPrivateForward(identity, message, session.authorized))
|
||
if (forwarding.value !== message) return
|
||
forwardStatus.value = status
|
||
forwarding.value = undefined
|
||
await refresh()
|
||
})
|
||
}
|
||
|
||
function sync() {
|
||
if (ownCode.value) void execute(refresh)
|
||
}
|
||
|
||
watch(target, () => {
|
||
view.value = undefined
|
||
selected.value = ''
|
||
code.value = ''
|
||
draft.value = ''
|
||
sync()
|
||
})
|
||
watch(selected, () => {
|
||
search.value = ''
|
||
favoritesOnly.value = false
|
||
reply.value = undefined
|
||
deleting.value = undefined
|
||
editing.value = undefined
|
||
recalling.value = undefined
|
||
forwarding.value = undefined
|
||
forwardStatus.value = ''
|
||
pendingFile.value = undefined
|
||
draft.value = ''
|
||
scheduleReceipt()
|
||
queueSeen()
|
||
})
|
||
watch(() => [session.inboxChanges, session.contactChanges, session.connection], sync)
|
||
watch(() => [session.inboxChanges, session.contactChanges, session.connection], queueUnread)
|
||
watch(() => [session.contactChanges, session.connection], () => void loadConversations())
|
||
watch([search, favoritesOnly], scheduleReceipt)
|
||
onMounted(() => {
|
||
void loadConversations()
|
||
queueUnread()
|
||
timer = setInterval(() => { sync(); queueUnread() }, 10_000)
|
||
window.addEventListener('focus', scheduleReceipt)
|
||
window.addEventListener('focus', queueSeen)
|
||
document.addEventListener('visibilitychange', scheduleReceipt)
|
||
document.addEventListener('visibilitychange', queueSeen)
|
||
})
|
||
onBeforeUnmount(() => {
|
||
active = false
|
||
clearInterval(timer)
|
||
clearTimeout(receiptTimer)
|
||
clearTimeout(seenTimer)
|
||
clearTimeout(unreadTimer)
|
||
unreadVersion++
|
||
window.removeEventListener('focus', scheduleReceipt)
|
||
window.removeEventListener('focus', queueSeen)
|
||
document.removeEventListener('visibilitychange', scheduleReceipt)
|
||
document.removeEventListener('visibilitychange', queueSeen)
|
||
})
|
||
</script>
|
||
|
||
<template>
|
||
<section class="device-page">
|
||
<header class="page-header">
|
||
<h1>加密聊天</h1>
|
||
<button v-if="activeContact" type="button" class="plain" :aria-pressed="activeContact.muted" :disabled="busy"
|
||
@click="togglePreference('mute')">消息免打扰</button>
|
||
<button v-if="activeContact" type="button" class="plain" :aria-pressed="activeContact.pinned" :disabled="busy"
|
||
@click="togglePreference('pin')">会话置顶</button>
|
||
<button v-if="ownCode" class="plain" :disabled="busy" @click="sync">刷新</button>
|
||
</header>
|
||
<div class="conversation-layout">
|
||
<aside class="conversation-list" aria-label="会话列表">
|
||
<label>查找会话<input v-model="conversationQuery" type="search" maxlength="120"></label>
|
||
<RouterLink v-for="contact in conversations" :key="contact.id" class="contact-item" :to="'/chat/' + contact.id">
|
||
<span class="avatar" aria-hidden="true">{{ contact.username[0]?.toUpperCase() }}</span>
|
||
<span><strong>{{ contact.alias || contact.username }}</strong>
|
||
<small v-if="contact.pinned">已置顶</small>
|
||
<small v-if="recent[contact.id]">{{ new Date(recent[contact.id]).toLocaleDateString('zh-CN') }}</small>
|
||
</span>
|
||
<span v-if="unread[contact.id]" class="unread-badge" :class="{ muted: contact.muted }">
|
||
<span aria-hidden="true">{{ unread[contact.id]! >= 100 ? '99+' : unread[contact.id] }}</span>
|
||
<span class="unread-label">{{ unread[contact.id]! >= 100 ? '99 条以上未读' : unread[contact.id] + ' 条未读' }}</span>
|
||
</span>
|
||
</RouterLink>
|
||
<p v-if="!conversations.length" class="muted">{{ conversationQuery ? '没有匹配的会话。' : '添加好友后可开始聊天。' }}</p>
|
||
</aside>
|
||
<div class="device-content chat-page">
|
||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||
<p v-if="forwardStatus" role="status">{{ forwardStatus }}</p>
|
||
<button v-if="!ownCode" type="button" class="primary" :disabled="busy" @click="enable">启用本机加密聊天</button>
|
||
<template v-else>
|
||
<details open>
|
||
<summary>本机安全码</summary>
|
||
<p>请通过另一可信渠道将此安全码告知对方。双方都需验证。</p>
|
||
<code class="security-code">{{ ownCode }}</code>
|
||
</details>
|
||
<template v-if="target">
|
||
<label v-if="view?.peers.length">对方设备
|
||
<select v-model="selected" :disabled="busy">
|
||
<option v-for="device in view.peers" :key="device.id" :value="device.id">{{ device.name }}</option>
|
||
</select>
|
||
</label>
|
||
<p v-else>对方设备出现后可开始验证。</p>
|
||
<p v-if="changed" class="error" role="alert">设备身份已变更,请重新核验。</p>
|
||
<p v-if="peer && !peer.mls">等待对方启用本机加密聊天。</p>
|
||
<form v-if="peer?.mls && !trusted" class="contact-preferences" @submit.prevent="confirm">
|
||
<label>对方安全码<input v-model="code" required maxlength="100" autocomplete="off"></label>
|
||
<button class="plain" :disabled="busy">核验设备</button>
|
||
</form>
|
||
<template v-if="trusted">
|
||
<p class="verified-label">设备已验证</p>
|
||
<p v-if="view?.deliveryError" class="error">{{ view.deliveryError }}</p>
|
||
<p v-if="view?.rejected" class="muted">已拒绝 {{ view.rejected }} 个无法验证的封包。</p>
|
||
<div class="chat-filters">
|
||
<label>搜索本机消息<input v-model="search" type="search" maxlength="120"></label>
|
||
<label class="chat-checkbox"><input v-model="favoritesOnly" type="checkbox">只看收藏</label>
|
||
<label class="chat-checkbox"><input type="checkbox" :checked="shareRead" :disabled="busy" @change="toggleReceipts">发送已读回执</label>
|
||
</div>
|
||
<ol ref="history" class="chat-lines" aria-label="消息记录" aria-live="polite" @scroll.passive="scheduleReceipt">
|
||
<li v-for="line in lines" :key="line.peer + ':' + line.own + ':' + line.id" :class="{ own: line.own }"
|
||
:data-unread="!line.own && !line.read && !line.recalled ? line.id : undefined">
|
||
<blockquote v-if="line.quote">{{ line.quote }}</blockquote>
|
||
<span v-if="line.recalled" class="muted">消息已撤回</span>
|
||
<VoiceMessage v-else-if="line.attachment?.voice" :attachment="line.attachment" />
|
||
<template v-else-if="line.attachment">
|
||
<MediaPreview v-if="line.attachment.media" :attachment="line.attachment" />
|
||
<button type="button" class="plain" :disabled="busy"
|
||
@click="saveAttachment(line.attachment)">下载 {{ line.attachment.name }}</button>
|
||
</template>
|
||
<MessageText v-else :text="line.text" @error="error = $event" />
|
||
<small v-if="view?.unsent.includes(line.id)">待发送</small>
|
||
<small v-else-if="line.own && line.read && !line.recalled">已读</small>
|
||
<small v-if="line.edited && !line.recalled">已编辑</small>
|
||
<div class="message-actions">
|
||
<button v-if="!line.recalled" type="button" class="plain" :disabled="busy || Boolean(editing)" @click="reply = line">引用</button>
|
||
<button v-if="!line.recalled" type="button" class="plain" :disabled="busy" @click="localAction(line, 'favorite')">
|
||
{{ line.favorite ? '取消收藏' : '收藏' }}
|
||
</button>
|
||
<button v-if="!line.recalled" type="button" class="plain" :disabled="busy" @click="beginForward(line)">转发</button>
|
||
<button v-if="line.own && !line.recalled && !line.attachment" type="button" class="plain" :disabled="busy" @click="edit(line)">编辑</button>
|
||
<button v-if="line.own && !line.recalled" type="button" class="plain" :disabled="busy" @click="recalling = line">撤回</button>
|
||
<button type="button" class="plain" :disabled="busy || view?.unsent.includes(line.id)" @click="deleting = line">本机删除</button>
|
||
</div>
|
||
</li>
|
||
</ol>
|
||
<p v-if="(search || favoritesOnly) && !lines.length" class="muted">没有匹配的消息。</p>
|
||
<div v-if="deleting" class="confirmation">
|
||
<p>从本机删除这条消息?</p>
|
||
<button type="button" class="plain" :disabled="busy" @click="localAction(deleting, 'remove')">确认删除</button>
|
||
<button type="button" class="plain" @click="deleting = undefined">取消</button>
|
||
</div>
|
||
<div v-if="recalling" class="confirmation">
|
||
<p>撤回这条消息?</p>
|
||
<button type="button" class="plain" :disabled="busy" @click="recall">确认撤回</button>
|
||
<button type="button" class="plain" @click="recalling = undefined">取消</button>
|
||
</div>
|
||
<ForwardDialog v-if="forwarding && view" :key="[forwarding.peer, forwarding.id, forwarding.own].join('/')"
|
||
:pinned="view.pinned" :busy="busy" @confirm="submitForward" @cancel="forwarding = undefined" />
|
||
<form class="chat-compose" @submit.prevent="submit">
|
||
<div v-if="editing" class="chat-quote">
|
||
<span>正在编辑消息</span>
|
||
<button type="button" class="plain" @click="editing = undefined; draft = ''">取消编辑</button>
|
||
</div>
|
||
<div v-if="reply" class="chat-quote">
|
||
<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>
|
||
<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>
|
||
</form>
|
||
</template>
|
||
</template>
|
||
<p v-else>选择一个联系人开始聊天。</p>
|
||
</template>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
</template>
|