双端本机收藏中心 #44

Merged
xhgit merged 1 commits from xhgit/local-favorites into main 2026-11-15 23:02:54 +08:00
12 changed files with 314 additions and 24 deletions

No files matched your search

+1
View File
@@ -25,6 +25,7 @@
| 加密附件 | 两端可在私聊和群聊多选或拖入文件,每批最多 8 个,每个最大 8 MiB。图片、视频在本机预览,群聊支持按附件类型查看。 |
| 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 |
| 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索、收藏和本机删除。可打开消息里的网页链接,并将消息转发到加密群或已核验的联系人设备。私聊支持可选加密已读回执。 |
| 本机收藏 | 在同一个入口查看私聊与群聊收藏,按来源和内容类型筛选。支持本机搜索、预览媒体、播放语音、下载加密附件和取消收藏。 |
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 |
当前为开发预览。大文件分片、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md)
+4
View File
@@ -222,3 +222,7 @@ Windows Electron 与 Edge 实测通知 API 调用、提醒跳转及免打扰后
Windows 和 Web 可以多选或拖入待发送附件,移除单项或清空列表。每批最多 8 个,单个文件最大 8 MiB。客户端逐个加密、上传并提交。上传中断时,未进入加密发件箱的文件保留在当前待发列表,由用户继续发送。已进入发件箱的封包沿用原消息 ID 进行投递重试。待发列表在切换联系人或对方设备时重置。
Windows 与 Edge 验证多选、拖拽、移除、清空和数量上限。第二个上传请求中断后仅重试剩余文件,接收端只收到一份先前已送达的文件。
## 本机收藏中心
Windows 和 Web 可从工作区进入收藏,查看当前设备本机密文库中的私聊和群聊收藏,按消息时间倒序分页。可按来源和文字、网页、图片、视频、语音、文件筛选。本机搜索匹配消息文字、引用、文件名及会话名称。复用聊天内的安全链接处理、媒体解密预览、语音播放和附件下载,附件仍受服务端访问权限和保留期限约束。取消收藏保留原消息,收藏状态按本机设备隔离。
+42
View File
@@ -388,6 +388,48 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
const address = toolbar.getByRole('textbox', { name: '网址或搜索关键词' })
await toolbar.waitForFunction((expected) => document.querySelector('#address')?.value === expected, link)
assert.equal(await address.inputValue(), link)
await toolbar.close()
async function addFavorite(page, locator) {
const line = page.getByRole('list', { name: '消息记录' }).getByRole('listitem').filter({ has: locator })
await line.getByRole('button', { name: '收藏', exact: true }).click()
await line.getByRole('button', { name: '取消收藏', exact: true }).waitFor()
}
await addFavorite(web, webLink)
await addFavorite(web, web.getByRole('button', { name: '下载 ' + remainingFile, exact: true }))
await addFavorite(windows, windows.getByRole('button', { name: '预览 加密预览.png', exact: true }))
await addFavorite(windows, windows.getByRole('button', { name: '播放语音', exact: true }))
await Promise.all([web, windows].map((page) => work(page).getByRole('link', { name: '收藏', exact: true }).click()))
const webFavorites = web.getByRole('list', { name: '本机收藏' })
const windowsFavorites = windows.getByRole('list', { name: '本机收藏' })
await webFavorites.getByRole('link', { name: link, exact: true }).waitFor()
assert.equal(await webFavorites.getByRole('listitem').count(), 2)
const tracked = []
const trackFavorites = (request) => tracked.push([request.url(), request.method(), request.postData()])
web.on('request', trackFavorites)
await web.getByLabel('内容类型').selectOption('link')
assert.equal(await webFavorites.getByRole('listitem').count(), 1)
const search = web.getByRole('searchbox', { name: '搜索本机收藏' })
const marker = '本机收藏验收 ' + randomBytes(8).toString('hex')
await search.fill(marker)
await web.getByText('没有匹配的收藏。', { exact: true }).waitFor()
await search.clear()
await web.getByLabel('内容类型').selectOption('file')
const favoriteDownload = web.waitForEvent('download')
await webFavorites.getByRole('button', { name: '下载 ' + remainingFile, exact: true }).click()
assert.deepEqual(await readFile(await (await favoriteDownload).path()), Buffer.from(remainingFile))
await webFavorites.getByRole('button', { name: '取消收藏', exact: true }).click()
await web.getByText('没有匹配的收藏。', { exact: true }).waitFor()
web.off('request', trackFavorites)
assert.ok(tracked.every(([url, method, body]) => method === 'GET' && !body && !url.includes(encodeURIComponent(marker))))
await windows.getByLabel('内容类型').selectOption('image')
await windowsFavorites.getByRole('button', { name: '预览 加密预览.png', exact: true }).click()
await windowsFavorites.getByRole('img', { name: '加密预览.png' }).waitFor()
await windows.getByLabel('内容类型').selectOption('voice')
await windowsFavorites.getByRole('button', { name: '播放语音', exact: true }).click()
await windows.waitForFunction(() => document.querySelector('.favorite-card audio')?.currentTime > 0)
assert.equal(await windowsFavorites.getByRole('link', { name: link, exact: true }).count(), 0)
} finally {
await desktop?.close()
await browser.close()
+20
View File
@@ -638,6 +638,9 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
assert.ok(originalBytes && originalBytes.length === contents.length + 16)
await windows.getByRole('listitem').filter({ hasText: privateFile }).getByRole('button', { name: '转发', exact: true }).click()
const privateLine = windows.getByRole('list', { name: '消息记录' }).getByRole('listitem').filter({ hasText: privateFile })
await privateLine.getByRole('button', { name: '收藏', exact: true }).click()
await privateLine.getByRole('button', { name: '取消收藏', exact: true }).waitFor()
const desktopForward = windows.getByRole('form', { name: '转发私聊消息' })
const writes = []
const recordWrite = (req) => { if (req.method() === 'POST' && req.url().includes('/groups/')) writes.push(req.url()) }
@@ -710,6 +713,23 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
}
await windows.getByRole('button', { name: '消息系统通知', pressed: true }).click()
await windows.getByText('已在本设备关闭消息系统通知', { exact: true }).waitFor()
await work(windows).getByRole('link', { name: '群组', exact: true }).click()
await windows.getByRole('link', { name: new RegExp(targetGroup) }).click()
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
const groupFile = chat(windows).getByRole('listitem').filter({ has: windows.getByRole('button', { name: '下载 ' + privateFile, exact: true }) })
await groupFile.getByRole('button', { name: '收藏', exact: true }).click()
await groupFile.getByRole('button', { name: '取消收藏', exact: true }).waitFor()
await work(windows).getByRole('link', { name: '收藏', exact: true }).click()
const collection = windows.getByRole('list', { name: '本机收藏' })
await windows.getByRole('searchbox', { name: '搜索本机收藏' }).fill(privateFile)
const downloads = collection.getByRole('button', { name: '下载 ' + privateFile, exact: true })
await downloads.nth(1).waitFor()
await windows.getByLabel('来源', { exact: true }).selectOption('group')
assert.equal(await downloads.count(), 1)
await collection.getByText(new RegExp(targetGroup)).waitFor()
await windows.getByLabel('来源', { exact: true }).selectOption('private')
assert.equal(await downloads.count(), 1)
} catch (error) {
const status = await Promise.all(pages.map((page) => page.locator('[role=alert], .group-chat [role=status]').allTextContents()))
throw new Error(JSON.stringify(status), { cause: error })
+2 -21
View File
@@ -1,31 +1,12 @@
<script setup lang="ts">
import { computed } from 'vue'
import { splitChatText } from './links'
const props = defineProps<{ text: string }>()
const emit = defineEmits<{ error: [message: string] }>()
const internalBrowser = window.xhchat?.openBrowser
const parts = computed(() => {
const text = props.text
const segments: { text: string; url?: string }[] = []
let offset = 0
for (const match of text.matchAll(/https?:\/\/[^\s<>"']+/giu)) {
const label = match[0].replace(/[.,!?;:,。!?;:、))\]】]+$/u, '')
if (label.length > 4096) continue
try {
const url = new URL(label)
if (url.username || url.password ||
(url.protocol !== 'https:' && !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))) continue
if (match.index > offset) segments.push({ text: text.slice(offset, match.index) })
segments.push({ text: label, url: url.href })
offset = match.index + label.length
} catch {
continue
}
}
if (offset < text.length) segments.push({ text: text.slice(offset) })
return segments
})
const parts = computed(() => splitChatText(props.text))
async function open(url: string) {
try {
+1 -1
View File
@@ -38,7 +38,7 @@ export interface ChatLine {
own: boolean
}
interface ChatState {
export interface ChatState {
engine: string
cursor: string
pending: Incoming[]
+68
View File
@@ -0,0 +1,68 @@
import type { Attachment } from './attachments'
import type { ChatLine, ChatState } from './chat'
import type { GroupLine } from './group-chat'
import { splitChatText } from './links'
import { withVault } from './vault'
type FavoriteType = 'text' | 'link' | 'image' | 'video' | 'voice' | 'file'
type CommonFavorite = {
key: string
type: FavoriteType
text: string
quote?: string
time: string
attachment?: Attachment
}
export type Favorite = CommonFavorite & (
{ kind: 'private'; contact?: string; peer: string; own: boolean; id: string } |
{ kind: 'group'; group: string; sender: string; epoch?: string; id: string }
)
const privateKey = (line: ChatLine) => ['private', line.peer, line.own ? 'own' : 'remote', line.id].join('/')
const groupKey = (group: string, line: GroupLine) => ['group', group, line.epoch, line.sender, line.id].join('/')
function favoriteType(line: Pick<ChatLine, 'attachment' | 'text'>): FavoriteType {
if (line.attachment?.voice) return 'voice'
if (line.attachment?.media?.startsWith('image/')) return 'image'
if (line.attachment?.media?.startsWith('video/')) return 'video'
if (line.attachment) return 'file'
return splitChatText(line.text).some((segment) => segment.url) ? 'link' : 'text'
}
function entries(state?: ChatState): Favorite[] {
const favorites: Favorite[] = []
for (const line of state?.lines ?? []) {
if (!line.favorite || line.recalled) continue
const { id, peer, own, contact, text, quote, time, attachment } = line
favorites.push({ kind: 'private', key: privateKey(line), type: favoriteType(line), id, peer, own, contact, text, quote, time, attachment })
}
for (const [group, chat] of Object.entries(state?.groupChats ?? {})) {
for (const line of chat.lines) {
if (!line.favorite || line.recalled) continue
const { id, epoch, sender, text, quote, time, attachment } = line
favorites.push({ kind: 'group', key: groupKey(group, line), type: favoriteType(line), id, group, epoch, sender, text, quote, time, attachment })
}
}
return favorites.sort((a, b) => b.time.localeCompare(a.time) || a.key.localeCompare(b.key))
}
export function listFavorites(device: string) {
return withVault<ChatState, Favorite[]>(device, async (state) => entries(state), true)
}
export function removeFavorite(device: string, key: string) {
return withVault<ChatState, Favorite[]>(device, async (state, save) => {
if (!state) return []
let line: ChatLine | GroupLine | undefined
if (key.startsWith('private/')) line = state.lines.find((item) => privateKey(item) === key)
else {
const groupID = key.split('/')[1] ?? ''
line = state.groupChats?.[groupID]?.lines.find((item) => groupKey(groupID, item) === key)
}
if (line?.favorite) {
delete line.favorite
await save(state)
}
return entries(state)
}, true)
}
+2 -2
View File
@@ -37,8 +37,8 @@ const encoder = new TextEncoder()
const decoder = new TextDecoder('utf-8', { fatal: true })
const announcementPrefix = [255, 5]
const maxAnnouncementBytes = 2000
const path = (group: GroupDetail) => '/groups/' + encodeURIComponent(group.id)
export const groupAttachmentPath = (group: GroupDetail, id: string) => path(group) + '/attachments/' + encodeURIComponent(id)
const path = (group: Pick<GroupDetail, 'id'>) => '/groups/' + encodeURIComponent(group.id)
export const groupAttachmentPath = (group: Pick<GroupDetail, 'id'>, id: string) => path(group) + '/attachments/' + encodeURIComponent(id)
const aad = (group: string, epoch: string, id: string, sender: string) =>
encoder.encode(['XHChat group message v1', group, epoch, id, sender].join('\n'))
+20
View File
@@ -0,0 +1,20 @@
export function splitChatText(text: string) {
const segments: { text: string; url?: string }[] = []
let offset = 0
for (const match of text.matchAll(/https?:\/\/[^\s<>"']+/giu)) {
const label = match[0].replace(/[.,!?;:,。!?;:、))\]】]+$/u, '')
if (label.length > 4096) continue
try {
const url = new URL(label)
if (url.username || url.password ||
(url.protocol !== 'https:' && !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))) continue
if (match.index > offset) segments.push({ text: text.slice(offset, match.index) })
segments.push({ text: label, url: url.href })
offset = match.index + label.length
} catch {
continue
}
}
if (offset < text.length) segments.push({ text: text.slice(offset) })
return segments
}
+2
View File
@@ -7,6 +7,7 @@ import DeviceView from './views/DeviceView.vue'
import ContactsView from './views/ContactsView.vue'
import ChatView from './views/ChatView.vue'
import GroupView from './views/GroupView.vue'
import FavoritesView from './views/FavoritesView.vue'
import Workspace from './views/Workspace.vue'
import { useSession } from './session'
import { incomingGroupInvite, parseGroupInvite } from './chat/group-invites'
@@ -23,6 +24,7 @@ const router = createRouter({
{ path: 'contacts', component: ContactsView },
{ path: 'chat/:user?', component: ChatView },
{ path: 'groups/:id?', component: GroupView },
{ path: 'favorites', component: FavoritesView },
] },
{ path: '/:pathMatch(.*)*', redirect: '/' },
],
+150
View File
@@ -0,0 +1,150 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useSession } from '../session'
import { downloadAttachment } from '../chat/attachments'
import { listFavorites, removeFavorite } from '../chat/favorites'
import type { Favorite } from '../chat/favorites'
import { groupAttachmentPath } from '../chat/group-chat'
import type { ListedGroup } from '../chat/group-chat'
import MediaPreview from '../chat/MediaPreview.vue'
import MessageText from '../chat/MessageText.vue'
import VoiceMessage from '../chat/VoiceMessage.vue'
const session = useSession()
const favorites = ref<Favorite[]>([])
const contacts = ref<Record<string, string>>({})
const groups = ref<Record<string, string>>({})
const query = ref('')
const type = ref('all')
const source = ref('all')
const limit = ref(30)
const loading = ref(true)
const busy = ref(false)
const error = ref('')
const types = { text: '文字', link: '网页', image: '图片', video: '视频', voice: '语音', file: '文件' }
let active = true
let revision = 0
function title(item: Favorite) {
return item.kind === 'group' ? groups.value[item.group] ?? '群聊' : contacts.value[item.contact ?? ''] ?? '私聊'
}
const normalize = (value: string) => value.normalize('NFKC').toLowerCase()
const results = computed(() => {
const term = normalize(query.value.trim())
return favorites.value.filter((item) => (type.value === 'all' || item.type === type.value) &&
(source.value === 'all' || item.kind === source.value) && (!term ||
[item.text, item.quote, item.attachment?.name, title(item)].some((value) => value && normalize(value).includes(term))))
})
function path(item: Favorite) {
return item.kind === 'group' && item.attachment ? groupAttachmentPath({ id: item.group }, item.attachment.id) : undefined
}
async function refresh() {
const device = session.identity?.device.id
if (!device || busy.value) return
const version = ++revision
try {
const items = await listFavorites(device)
if (active && version === revision) favorites.value = items
} catch (cause) {
if (active && version === revision) error.value = cause instanceof Error ? cause.message : '无法读取本机收藏'
} finally {
if (active && version === revision) loading.value = false
}
}
async function loadNames() {
const [people, conversations] = await Promise.allSettled([session.contacts(), session.authorized<ListedGroup[]>('/groups')])
if (!active) return
if (people.status === 'fulfilled') contacts.value = Object.fromEntries(people.value.map((item) => [item.id, item.alias || item.username]))
if (conversations.status === 'fulfilled') groups.value = Object.fromEntries(conversations.value.map((item) => [item.id, item.name]))
}
async function cancelFavorite(item: Favorite) {
const device = session.identity?.device.id
if (!device || busy.value) return
busy.value = true
error.value = ''
revision++
try {
const items = await removeFavorite(device, item.key)
if (active) favorites.value = items
} catch (cause) {
if (active) error.value = cause instanceof Error ? cause.message : '无法取消收藏'
} finally {
busy.value = false
}
}
async function download(item: Favorite) {
if (!item.attachment || busy.value) return
busy.value = true
error.value = ''
try {
await downloadAttachment(item.attachment, session.authorized, path(item))
} catch (cause) {
if (active) error.value = cause instanceof Error ? cause.message : '无法下载附件'
} finally {
busy.value = false
}
}
watch([query, source, type], () => { limit.value = 30 })
watch(() => [session.contactChanges, session.groupListChanges], () => void loadNames())
onMounted(() => {
void refresh()
void loadNames()
window.addEventListener('focus', refresh)
})
onBeforeUnmount(() => {
active = false
window.removeEventListener('focus', refresh)
})
</script>
<template>
<section class="device-page">
<header class="page-header"><h1>收藏</h1></header>
<div class="device-content favorites">
<div class="favorite-filters">
<label>搜索本机收藏<input v-model="query" type="search" maxlength="120" placeholder="文字、链接、文件名或会话"></label>
<label><span id="favorite-type-label">内容类型</span><select v-model="type" aria-labelledby="favorite-type-label"><option value="all">全部类型</option>
<option v-for="(label, value) in types" :key="value" :value="value">{{ label }}</option>
</select></label>
<label><span id="favorite-source-label">来源</span><select v-model="source" aria-labelledby="favorite-source-label"><option value="all">全部会话</option>
<option value="private">私聊</option><option value="group">群聊</option>
</select></label>
</div>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<p v-if="loading" role="status">正在读取本机收藏…</p>
<p v-else-if="!results.length" class="muted" role="status">{{ favorites.length ? '没有匹配的收藏。' : '本机还没有收藏。' }}</p>
<ul v-else class="favorite-list" aria-label="本机收藏">
<li v-for="item in results.slice(0, limit)" :key="item.key" class="favorite-card">
<small>{{ title(item) }} · {{ types[item.type] }} · {{ new Date(item.time).toLocaleString('zh-CN') }}</small>
<blockquote v-if="item.quote">{{ item.quote }}</blockquote>
<template v-if="item.attachment">
<VoiceMessage v-if="item.type === 'voice'" :attachment="item.attachment" :path="path(item)" />
<MediaPreview v-if="item.attachment.media" :attachment="item.attachment" :path="path(item)" />
<button type="button" class="plain" :disabled="busy" @click="download(item)">下载 {{ item.attachment.name }}</button>
</template>
<p v-else class="favorite-text"><MessageText :text="item.text" @error="error = $event" /></p>
<div class="message-actions"><button type="button" class="plain" :disabled="busy" @click="cancelFavorite(item)">取消收藏</button></div>
</li>
</ul>
<button v-if="results.length > limit" type="button" class="plain" @click="limit += 30">加载更多收藏</button>
</div>
</section>
</template>
<style scoped>
.favorites, .favorite-list, .favorite-card { display: grid; gap: .7rem; justify-items: start; }
.favorite-filters { width: 100%; display: flex; flex-wrap: wrap; gap: .65rem; align-items: end; }
.favorite-filters label:first-child { flex: 1 1 15rem; }
.favorite-filters select { font: inherit; color: var(--text); background: var(--base); border: 1px solid var(--line); border-radius: .5rem; padding: .69rem .55rem; }
.favorite-list { width: 100%; list-style: none; margin: 0; padding: 0; }
.favorite-card { width: 100%; padding: .85rem; border: 1px solid var(--line); border-radius: .5rem; overflow-wrap: anywhere; }
.favorite-card blockquote { margin: 0; border-inline-start: 2px solid var(--line); padding-inline-start: .55rem; color: var(--muted); }
.favorite-text { white-space: pre-wrap; }
</style>
+2
View File
@@ -130,6 +130,7 @@ async function act(action: () => Promise<void>) {
<RouterLink class="mark" to="/devices" aria-label="XHChat"><img src="/brand/xhchat.png" alt=""></RouterLink>
<RouterLink class="rail-link" to="/chat" title="消息" aria-label="消息">◇</RouterLink>
<RouterLink class="rail-link" to="/contacts" title="联系人" aria-label="联系人">人</RouterLink>
<RouterLink class="rail-link" to="/favorites" title="收藏" aria-label="收藏">☆</RouterLink>
<RouterLink class="rail-link" to="/devices" title="设备管理" aria-label="设备管理">▣</RouterLink>
<button v-if="browser" type="button" class="rail-link browser-button" title="浏览器" aria-label="浏览器" @click="act(browser)">◎</button>
</nav>
@@ -142,6 +143,7 @@ async function act(action: () => Promise<void>) {
<RouterLink to="/chat">消息</RouterLink>
<RouterLink to="/contacts">联系人</RouterLink>
<RouterLink to="/groups">群组</RouterLink>
<RouterLink to="/favorites">收藏</RouterLink>
<RouterLink to="/devices">设备管理</RouterLink>
<button v-if="browser" class="plain mobile-browser" @click="act(browser)">浏览器</button>
</nav>