From f923b0ca7b33f012cc89761a5112fc4e673b0380 Mon Sep 17 00:00:00 2001 From: xhgit Date: Sun, 15 Nov 2026 22:55:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=94=B6=E8=97=8F=E6=A0=87?= =?UTF-8?q?=E7=AD=BE=E5=92=8C=E6=89=B9=E9=87=8F=E5=8F=96=E6=B6=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/progress.md | 2 + tests/encrypted-chat.test.mjs | 30 +++++++- web/src/chat/chat.ts | 12 ++- web/src/chat/favorites.ts | 77 ++++++++++++++++---- web/src/chat/group-chat.ts | 9 ++- web/src/views/FavoritesView.vue | 125 ++++++++++++++++++++++++++++---- 7 files changed, 218 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index e903e7e..30eec9c 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ | 加密附件 | 两端可在私聊和群聊多选或拖入文件,每批最多 8 个,每个最大 8 MiB。图片、视频在本机预览,群聊支持按附件类型查看。 | | 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 | | 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索、收藏和本机删除。可打开消息里的网页链接,并将消息转发到加密群或已核验的联系人设备。私聊支持可选加密已读回执。 | -| 本机收藏 | 在同一个入口查看私聊与群聊收藏,按来源和内容类型筛选。支持本机搜索、预览媒体、播放语音、下载加密附件和取消收藏。 | +| 本机收藏 | 汇总私聊与群聊收藏,支持本机搜索、按来源、内容类型和标签筛选。可预览媒体、播放语音、下载加密附件或批量取消收藏。 | | Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 | 当前为开发预览。大文件分片、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md) diff --git a/docs/progress.md b/docs/progress.md index c7035f8..1ada074 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -226,3 +226,5 @@ Windows 与 Edge 验证多选、拖拽、移除、清空和数量上限。第二 ## 本机收藏中心 Windows 和 Web 可从工作区进入收藏,查看当前设备本机密文库中的私聊和群聊收藏,按消息时间倒序分页。可按来源和文字、网页、图片、视频、语音、文件筛选。本机搜索匹配消息文字、引用、文件名及会话名称。复用聊天内的安全链接处理、媒体解密预览、语音播放和附件下载,附件仍受服务端访问权限和保留期限约束。取消收藏保留原消息,收藏状态按本机设备隔离。 + +收藏标签与消息一起保存在本机加密库,可筛选和搜索。批量管理支持选择当前列表和逐条选择,确认后在一次本机写入中清除收藏与关联标签。已撤回消息也会移出收藏。 diff --git a/tests/encrypted-chat.test.mjs b/tests/encrypted-chat.test.mjs index 8b06233..ed68d5d 100644 --- a/tests/encrypted-chat.test.mjs +++ b/tests/encrypted-chat.test.mjs @@ -420,8 +420,21 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢 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() + await web.getByLabel('内容类型').selectOption('link') + await webFavorites.getByRole('button', { name: '编辑标签', exact: true }).click() + await web.getByLabel('收藏标签').fill('验收资料,DOC,Doc') + await webFavorites.getByRole('button', { name: '保存标签', exact: true }).click() + await webFavorites.getByRole('button', { name: '验收资料', exact: true }).waitFor() + assert.equal(await webFavorites.locator('.favorite-tags button').count(), 2) + await web.getByLabel('标签筛选', { exact: true }).selectOption('doc') + await search.fill('dOc') + await webFavorites.getByRole('link', { name: link, exact: true }).waitFor() + await work(web).getByRole('link', { name: '联系人', exact: true }).click() + await work(web).getByRole('link', { name: '收藏', exact: true }).click() + await webFavorites.getByRole('button', { name: '验收资料', exact: true }).waitFor() web.off('request', trackFavorites) - assert.ok(tracked.every(([url, method, body]) => method === 'GET' && !body && !url.includes(encodeURIComponent(marker)))) + assert.ok(tracked.every(([url, method, body]) => method === 'GET' && !body && + !url.includes(encodeURIComponent(marker)) && !url.includes(encodeURIComponent('验收资料')))) await windows.getByLabel('内容类型').selectOption('image') await windowsFavorites.getByRole('button', { name: '预览 加密预览.png', exact: true }).click() @@ -430,6 +443,21 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢 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) + await windows.getByLabel('内容类型').selectOption('all') + await windows.getByRole('button', { name: '批量管理', exact: true }).click() + await windows.getByRole('button', { name: '选择当前列表', exact: true }).click() + const bulk = windows.getByRole('button', { name: '取消所选收藏(2)', exact: true }) + await bulk.click() + const confirmation = windows.getByRole('region', { name: '确认取消收藏' }) + await confirmation.getByRole('button', { name: '返回', exact: true }).click() + assert.equal(await windowsFavorites.getByRole('listitem').count(), 2) + await bulk.click() + await confirmation.getByRole('button', { name: '确认取消收藏', exact: true }).click() + await windows.getByText('本机还没有收藏。', { exact: true }).waitFor() + await windows.evaluate((url) => { location.hash = new URL(url).hash }, windowsChat) + await enable(windows) + await windows.getByRole('button', { name: '预览 加密预览.png', exact: true }).waitFor() + await windows.getByRole('button', { name: '播放语音', exact: true }).waitFor() } finally { await desktop?.close() await browser.close() diff --git a/web/src/chat/chat.ts b/web/src/chat/chat.ts index 4eb8e15..e41de3d 100644 --- a/web/src/chat/chat.ts +++ b/web/src/chat/chat.ts @@ -6,6 +6,8 @@ import { withVault } from './vault' import { decodeMessage, encodeAttachment, encodeMutation, encodeRead, encodeReply, readForwardedFile, sealAttachment, uploadAttachment } from './attachments' import type { Attachment, Mutation } from './attachments' import type { GroupChatState } from './group-chat' +import { clearFavorite } from './favorites' +import type { FavoriteFields } from './favorites' export interface Peer { id: string @@ -23,13 +25,12 @@ export interface Package { package: string; signature: string } interface Outgoing { messageId: string; recipientDevice: string; ciphertext: string; mutationTarget?: string; silent?: boolean } interface Incoming { messageId: string; senderDevice: string; ciphertext: string; sequence: string; createdAt: string } -export interface ChatLine { +export interface ChatLine extends FavoriteFields { id: string peer: string text: string attachment?: Attachment quote?: string - favorite?: boolean recalled?: boolean edited?: boolean read?: boolean @@ -174,13 +175,14 @@ async function flush(state: ChatState, save: (state: ChatState) => Promise return unavailable } -export function applyMutation(line: Pick, mutation: Mutation) { +export function applyMutation(line: Pick & FavoriteFields, mutation: Mutation) { if (line.recalled) return if (mutation.action === 'recall') { line.recalled = true line.text = '' delete line.attachment delete line.quote + clearFavorite(line) } else if (!line.attachment && mutation.text) { line.text = mutation.text line.edited = true @@ -276,7 +278,9 @@ export function localMessageAction(identity: ChatIdentity, line: ChatLine, actio } state.lines.splice(index, 1) } else { - state.lines[index]!.favorite = !state.lines[index]!.favorite + const target = state.lines[index]! + if (target.favorite) clearFavorite(target) + else if (!target.recalled) target.favorite = true } await save(state) }) diff --git a/web/src/chat/favorites.ts b/web/src/chat/favorites.ts index 9a4d52f..2242fde 100644 --- a/web/src/chat/favorites.ts +++ b/web/src/chat/favorites.ts @@ -12,7 +12,9 @@ type CommonFavorite = { quote?: string time: string attachment?: Attachment + tags: string[] } +export type FavoriteFields = { favorite?: boolean; favoriteTags?: string[] } export type Favorite = CommonFavorite & ( { kind: 'private'; contact?: string; peer: string; own: boolean; id: string } | { kind: 'group'; group: string; sender: string; epoch?: string; id: string } @@ -21,6 +23,28 @@ export type Favorite = CommonFavorite & ( 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('/') +export function clearFavorite(line: FavoriteFields) { + delete line.favorite + delete line.favoriteTags +} + +export function favoriteTagKey(tag: string) { + return tag.normalize('NFKC').toLowerCase() +} + +function normalizedTags(tags: string[]) { + const values = new Map() + for (const tag of tags) { + const label = tag.trim() + if (!label) continue + if ([...label].length > 24 || /\p{C}/u.test(label)) throw new Error('每个标签最多 24 个字符,请移除不可见字符') + const key = favoriteTagKey(label) + if (!values.has(key)) values.set(key, label) + } + if (values.size > 8) throw new Error('每条收藏最多使用 8 个标签') + return [...values.values()] +} + function favoriteType(line: Pick): FavoriteType { if (line.attachment?.voice) return 'voice' if (line.attachment?.media?.startsWith('image/')) return 'image' @@ -34,13 +58,15 @@ function entries(state?: ChatState): 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 }) + favorites.push({ kind: 'private', key: privateKey(line), type: favoriteType(line), id, peer, own, contact, text, quote, time, + attachment, tags: line.favoriteTags ?? [] }) } 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 }) + favorites.push({ kind: 'group', key: groupKey(group, line), type: favoriteType(line), id, group, epoch, sender, text, quote, + time, attachment, tags: line.favoriteTags ?? [] }) } } return favorites.sort((a, b) => b.time.localeCompare(a.time) || a.key.localeCompare(b.key)) @@ -50,19 +76,44 @@ export function listFavorites(device: string) { return withVault(device, async (state) => entries(state), true) } -export function removeFavorite(device: string, key: string) { +function changeFavorites(device: string, change: (state: ChatState) => boolean) { return withVault(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) - } + if (change(state)) await save(state) return entries(state) }, true) } + +export function removeFavorites(device: string, keys: ReadonlySet) { + return changeFavorites(device, (state) => { + let changed = false + for (const line of state.lines) { + if (line.favorite && keys.has(privateKey(line))) { + clearFavorite(line) + changed = true + } + } + for (const [group, chat] of Object.entries(state.groupChats ?? {})) { + for (const line of chat.lines) { + if (line.favorite && keys.has(groupKey(group, line))) { + clearFavorite(line) + changed = true + } + } + } + return changed + }) +} + +export function setFavoriteTags(device: string, key: string, tags: string[]) { + return changeFavorites(device, (state) => { + const group = key.split('/')[1] ?? '' + const line = key.startsWith('private/') ? state.lines.find((item) => privateKey(item) === key) : + state.groupChats?.[group]?.lines.find((item) => groupKey(group, item) === key) + if (!line?.favorite || line.recalled) throw new Error('此消息已不在本机收藏') + const labels = normalizedTags(tags) + if (labels.length) line.favoriteTags = labels + else delete line.favoriteTags + return true + }) +} diff --git a/web/src/chat/group-chat.ts b/web/src/chat/group-chat.ts index 8fb3b26..46154bc 100644 --- a/web/src/chat/group-chat.ts +++ b/web/src/chat/group-chat.ts @@ -4,6 +4,8 @@ import { applyMutation, replenishPackages, send, update, verifiedPeer, verify } import type { Call, ChatIdentity, Package, Peer } from './chat' import { decodeMessage, encodeAttachment, encodeMutation, encodeReply, readForwardedFile, sealAttachment } from './attachments' import type { Attachment, Mutation } from './attachments' +import { clearFavorite } from './favorites' +import type { FavoriteFields } from './favorites' export type GroupMember = { id: string; username: string; state: 'active' | 'invited'; role: 'owner' | 'admin' | 'member' } export type GroupDetail = { id: string; membershipVersion: string; members: GroupMember[]; role: GroupMember['role'] } @@ -15,9 +17,9 @@ type Epoch = { id: string; creatorDevice: string; membershipVersion: string; wel type Publishing = { id: string; membershipVersion: string; devices: { device: string; wire?: string }[] } type Outgoing = { id: string; epoch: string; wire: string } type Packet = Outgoing & { sequence: string; senderDevice: string; createdAt: string; attachmentId?: string } -export type GroupLine = { +export type GroupLine = FavoriteFields & { id: string; user: string; sender: string; name: string; text: string; time: string; epoch?: string - attachment?: Attachment; quote?: string; edited?: boolean; recalled?: boolean; favorite?: boolean + attachment?: Attachment; quote?: string; edited?: boolean; recalled?: boolean } type LineRef = Pick export type ForwardDestination = { group: string } | { user: string; device: Peer } @@ -62,7 +64,6 @@ function applyGroupMutation(chat: GroupChatState, epoch: string, sender: string, const target = chat.lines.find((line) => line.id === mutation.id && line.epoch === epoch && line.sender === sender) if (!target) return applyMutation(target, mutation) - if (target.recalled) delete target.favorite } function trimHistory(chat: GroupChatState) { @@ -76,7 +77,7 @@ export function setGroupFavorite(identity: ChatIdentity, group: GroupDetail, mes const line = chat?.lines.find((item) => item.id === message.id && item.epoch === message.epoch && item.sender === message.sender) if (!chat || !line || line.recalled) throw new Error('此群消息无法收藏') if (favorite) line.favorite = true - else delete line.favorite + else clearFavorite(line) trimHistory(chat) await save(state) return chat.lines diff --git a/web/src/views/FavoritesView.vue b/web/src/views/FavoritesView.vue index cf820a5..3d2f2b7 100644 --- a/web/src/views/FavoritesView.vue +++ b/web/src/views/FavoritesView.vue @@ -2,7 +2,7 @@ import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { useSession } from '../session' import { downloadAttachment } from '../chat/attachments' -import { listFavorites, removeFavorite } from '../chat/favorites' +import { favoriteTagKey, listFavorites, removeFavorites, setFavoriteTags } from '../chat/favorites' import type { Favorite } from '../chat/favorites' import { groupAttachmentPath } from '../chat/group-chat' import type { ListedGroup } from '../chat/group-chat' @@ -17,6 +17,12 @@ const groups = ref>({}) const query = ref('') const type = ref('all') const source = ref('all') +const tag = ref('') +const editor = ref('') +const tagDraft = ref('') +const selecting = ref(false) +const selected = ref(new Set()) +const confirmingBulk = ref(false) const limit = ref(30) const loading = ref(true) const busy = ref(false) @@ -29,14 +35,27 @@ 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)))) +const tags = computed(() => { + const options = new Map() + for (const item of favorites.value) { + for (const label of item.tags) { + const key = favoriteTagKey(label) + if (!options.has(key)) options.set(key, label) + } + } + return [...options.entries()].sort(([, a], [, b]) => a.localeCompare(b, 'zh-CN')) }) +const results = computed(() => { + const term = favoriteTagKey(query.value.trim()) + return favorites.value.filter((item) => (type.value === 'all' || item.type === type.value) && + (source.value === 'all' || item.kind === source.value) && (!tag.value || item.tags.some((label) => favoriteTagKey(label) === tag.value)) && + (!term || [item.text, item.quote, item.attachment?.name, title(item), ...item.tags] + .some((value) => value && favoriteTagKey(value).includes(term)))) +}) +const visible = computed(() => results.value.slice(0, limit.value)) +const allVisibleSelected = computed(() => visible.value.length > 0 && visible.value.every((item) => selected.value.has(item.key))) + function path(item: Favorite) { return item.kind === 'group' && item.attachment ? groupAttachmentPath({ id: item.group }, item.attachment.id) : undefined } @@ -62,22 +81,58 @@ async function loadNames() { if (conversations.status === 'fulfilled') groups.value = Object.fromEntries(conversations.value.map((item) => [item.id, item.name])) } -async function cancelFavorite(item: Favorite) { +async function change(action: (device: string) => Promise) { const device = session.identity?.device.id - if (!device || busy.value) return + if (!device || busy.value) return false busy.value = true error.value = '' revision++ try { - const items = await removeFavorite(device, item.key) + const items = await action(device) if (active) favorites.value = items + return active } catch (cause) { - if (active) error.value = cause instanceof Error ? cause.message : '无法取消收藏' + if (active) error.value = cause instanceof Error ? cause.message : '无法更新本机收藏' + return false } finally { busy.value = false } } +function editTags(item: Favorite) { + error.value = '' + editor.value = item.key + tagDraft.value = item.tags.join(',') +} + +async function saveTags() { + const key = editor.value + if (await change((device) => setFavoriteTags(device, key, tagDraft.value.split(/[,,]/u)))) editor.value = '' +} + +function toggleBatch() { + selecting.value = !selecting.value + editor.value = '' + confirmingBulk.value = false + selected.value.clear() +} + +function selectItem(key: string, enabled: boolean) { + if (enabled) selected.value.add(key) + else selected.value.delete(key) + confirmingBulk.value = false +} + +function selectVisible() { + const enabled = !allVisibleSelected.value + for (const item of visible.value) selectItem(item.key, enabled) +} + +async function cancelSelected() { + const keys = new Set(selected.value) + if (keys.size && await change((device) => removeFavorites(device, keys))) toggleBatch() +} + async function download(item: Favorite) { if (!item.attachment || busy.value) return busy.value = true @@ -91,7 +146,13 @@ async function download(item: Favorite) { } } -watch([query, source, type], () => { limit.value = 30 }) +watch([query, source, type, tag], () => { + limit.value = 30 + selected.value.clear() + confirmingBulk.value = false + editor.value = '' +}) +watch(tags, (options) => { if (tag.value && !options.some(([key]) => key === tag.value)) tag.value = '' }) watch(() => [session.contactChanges, session.groupListChanges], () => void loadNames()) onMounted(() => { void refresh() @@ -106,22 +167,38 @@ onBeforeUnmount(() => {