汇总私聊与群聊本机收藏

This commit is contained in:
xhgit committed 2026-11-15 22:50:07 +08:00
1 parent a7d85f183c
commit e08c990cc7
12 files changed
+314 -24

No files matched your search

+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>