支持加密图片与视频的本机预览

This commit is contained in:
xhgit committed 2026-11-13 23:41:56 +08:00
1 parent 87676ae983
commit 6b728a0996
10 files changed
+94 -7

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { readAttachment } from './attachments'
import type { Attachment } from './attachments'
import { useSession } from '../session'
const props = defineProps<{ attachment: Attachment }>()
const session = useSession()
const url = ref('')
const busy = ref(false)
const error = ref('')
let active = true
function close() {
if (url.value) URL.revokeObjectURL(url.value)
url.value = ''
}
async function open() {
if (!props.attachment.media) return
busy.value = true
error.value = ''
try {
const bytes = await readAttachment(props.attachment, session.authorized)
if (active) url.value = URL.createObjectURL(new Blob([bytes], { type: props.attachment.media }))
} catch (cause) {
if (active) error.value = cause instanceof Error ? cause.message : '无法加载媒体预览'
} finally {
busy.value = false
}
}
function decodeError() {
close()
error.value = '客户端无法解码此媒体文件'
}
onBeforeUnmount(() => {
active = false
close()
})
</script>
<template>
<div class="media-preview">
<template v-if="url">
<img v-if="attachment.media?.startsWith('image/')" :src="url" :alt="attachment.name" @error="decodeError">
<video v-else :src="url" controls preload="metadata" :aria-label="attachment.name" @error="decodeError"></video>
<button type="button" class="plain" @click="close">关闭预览</button>
</template>
<button v-else type="button" class="plain" :disabled="busy" @click="open">
{{ busy ? '正在解密…' : '预览 ' + attachment.name }}
</button>
<small v-if="error" class="error" role="alert">{{ error }}</small>
</div>
</template>
+11 -1
View File
@@ -4,6 +4,12 @@ import type { Call } from './chat'
const maxSize = 8 * 1024 * 1024
const encoder = new TextEncoder()
const decoder = new TextDecoder('utf-8', { fatal: true })
const mediaTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'video/mp4', 'video/webm'] as const
type MediaType = typeof mediaTypes[number]
function mediaType(value: unknown): value is MediaType {
return mediaTypes.some((type) => type === value)
}
export interface Attachment {
id: string
@@ -12,6 +18,7 @@ export interface Attachment {
key: string
iv: string
voice?: true
media?: MediaType
}
const voiceRecordings = new WeakSet<File>()
@@ -25,9 +32,10 @@ function attachmentPath(id: string) {
return '/attachments/' + encodeURIComponent(id)
}
function authenticatedData(file: Pick<Attachment, 'id' | 'name' | 'size' | 'voice'>) {
function authenticatedData(file: Pick<Attachment, 'id' | 'name' | 'size' | 'voice' | 'media'>) {
const fields = ['XHChat attachment v1', file.id, file.name, file.size]
if (file.voice) fields.push('voice')
if (file.media) fields.push(file.media)
return encoder.encode(JSON.stringify(fields))
}
@@ -41,6 +49,7 @@ export async function sealAttachment(file: File) {
const iv = crypto.getRandomValues(new Uint8Array(12))
const attachment: Attachment = { id: crypto.randomUUID(), name: safeName(file.name), size: file.size, key: base64(key), iv: base64(iv) }
if (voiceRecordings.has(file)) attachment.voice = true
else if (mediaType(file.type)) attachment.media = file.type
try {
const imported = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['encrypt'])
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: authenticatedData(attachment) }, imported, await file.arrayBuffer())
@@ -99,6 +108,7 @@ export function decodeMessage(message: Uint8Array): ChatContent {
typeof value.name !== 'string' || value.name !== safeName(value.name) ||
!Number.isInteger(value.size) || value.size < 0 || value.size > maxSize ||
(value.voice !== undefined && value.voice !== true) ||
(value.media !== undefined && (!mediaType(value.media) || value.voice === true)) ||
typeof value.key !== 'string' || decode(value.key).length !== 32 ||
typeof value.iv !== 'string' || decode(value.iv).length !== 12) {
throw new Error('附件描述格式无效')
+2 -1
View File
@@ -266,7 +266,8 @@ export async function forwardMessage(identity: ChatIdentity, line: ChatLine, rec
if (line.recalled) throw new Error('撤回的消息无法转发')
const attachment = line.attachment
const bytes = attachment ? await readAttachment(attachment, call) : undefined
const content = attachment && bytes ? attachment.voice ? voiceFile([bytes]) : new File([bytes], attachment.name) : line.text
const content = attachment && bytes ? attachment.voice ? voiceFile([bytes]) :
new File([bytes], attachment.name, { type: attachment.media }) : line.text
await send(identity, recipient, device, content, call)
}
+2
View File
@@ -84,6 +84,8 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so
.chat-lines li.own { align-self: end; background: var(--green-soft); }
.chat-lines small { display: block; text-align: end; }
.chat-lines audio { display: block; width: min(260px, 100%); }
.media-preview { display: grid; gap: 5px; justify-items: start; margin-bottom: 5px; }
.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; }
.chat-filters, .chat-quote, .message-actions { display: flex; gap: 6px; flex-wrap: wrap; align-items: end; }
+6 -2
View File
@@ -9,6 +9,7 @@ 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'
const session = useSession()
const route = useRoute()
@@ -370,8 +371,11 @@ onBeforeUnmount(() => {
<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" />
<button v-else-if="line.attachment" type="button" class="plain" :disabled="busy"
@click="saveAttachment(line.attachment)">下载 {{ line.attachment.name }}</button>
<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>
<span v-else><template v-for="(part, index) in messageParts(line.text)" :key="index"><button v-if="part.url && internalBrowser"
type="button" class="chat-link" @click="openLink(part.url)">{{ part.text }}</button><a v-else-if="part.url"
class="chat-link" :href="part.url" target="_blank" rel="noopener noreferrer">{{ part.text }}</a><template v-else>{{ part.text }}</template></template></span>