接入私聊消息通知和联系人免打扰

This commit is contained in:
xhgit committed 2026-11-15 22:27:58 +08:00
1 parent 5c882ac855
commit 7e165ba9b4
23 files changed
+286 -97

No files matched your search

+6 -3
View File
@@ -20,7 +20,7 @@ export interface ChatIdentity {
}
export interface Package { package: string; signature: string }
interface Outgoing { messageId: string; recipientDevice: string; ciphertext: string; mutationTarget?: 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 {
@@ -159,7 +159,10 @@ async function flush(state: ChatState, save: (state: ChatState) => Promise<void>
for (const item of [...state.outbox]) {
if (unavailable.has(item.recipientDevice)) continue
try {
await call('/inbox', 'POST', { messageId: item.messageId, recipientDevice: item.recipientDevice, ciphertext: item.ciphertext })
await call('/inbox', 'POST', {
messageId: item.messageId, recipientDevice: item.recipientDevice, ciphertext: item.ciphertext,
...(item.silent || item.mutationTarget ? { silent: true } : {}),
})
state.outbox = state.outbox.filter((pending) => pending.messageId !== item.messageId)
await save(state)
} catch (error) {
@@ -308,7 +311,7 @@ export function markRead(identity: ChatIdentity, user: string, peer: Peer, visib
try {
const id = crypto.randomUUID()
const bytes = engine.encrypt(decode(group), aad(id, identity.device.id, peer.id), encodeRead(lines.map((line) => line.id)))
state.outbox.push({ messageId: id, recipientDevice: peer.id, ciphertext: base64(bytes) })
state.outbox.push({ messageId: id, recipientDevice: peer.id, ciphertext: base64(bytes), silent: true })
for (const line of lines) line.read = true
state.engine = base64(engine.snapshot())
await save(state)
+2 -1
View File
@@ -4,6 +4,7 @@ export interface Contact {
state: 'none' | 'incoming' | 'outgoing' | 'friend' | 'blocked'
alias: string
category: string
muted: boolean
}
export type ContactAction = 'request' | 'accept' | 'reject' | 'cancel' | 'delete' | 'block' | 'unblock' | 'preferences'
export type ContactAction = 'request' | 'accept' | 'reject' | 'cancel' | 'delete' | 'block' | 'unblock' | 'preferences' | 'mute' | 'unmute'
+3 -3
View File
@@ -7,9 +7,9 @@ interface DesktopBridge {
apiBase: string
signChallenge: (username: string, challenge: string) => Promise<DeviceProof>
openBrowser?: (url?: string) => Promise<void>
groupNotificationsSupported: () => Promise<boolean>
showGroupNotification: () => Promise<void>
closeGroupNotification: () => Promise<void>
messageNotificationsSupported: () => Promise<boolean>
showMessageNotification: (kind: 'group' | 'private') => Promise<void>
closeMessageNotification: () => Promise<void>
allowVoiceRecording: () => Promise<void>
endVoiceRecording: () => Promise<void>
signMls: (username: string, kind: 'credential' | 'KeyPackage', user: string, device: string, value: Uint8Array<ArrayBuffer>) => Promise<Uint8Array<ArrayBuffer>>
+9 -4
View File
@@ -26,6 +26,7 @@ export const useSession = defineStore('session', () => {
const connection = ref('离线')
const contactChanges = ref(0)
const inboxChanges = ref(0)
const privateNotice = shallowRef<{ contactId: string }>()
const groupChange = shallowRef<{ groupId: string; notify: boolean }>()
const groupListChanges = ref(0)
let token = ''
@@ -37,6 +38,7 @@ export const useSession = defineStore('session', () => {
token = ''
identity.value = undefined
groupChange.value = undefined
privateNotice.value = undefined
connection.value = '离线'
clearTimeout(retry)
const previous = socket
@@ -54,13 +56,16 @@ export const useSession = defineStore('session', () => {
socket = active
active.onmessage = (event) => {
if (socket !== active) return
const { type, groupId, notify } = JSON.parse(event.data)
const { type, contactId, groupId, notify } = JSON.parse(event.data)
if (type === 'ready') {
connection.value = '实时连接已建立'
attempts = 0
}
if (type === 'contacts_changed') contactChanges.value++
if (type === 'inbox_changed') inboxChanges.value++
if (type === 'inbox_changed') {
inboxChanges.value++
if (notify === true && typeof contactId === 'string') privateNotice.value = { contactId }
}
if (type === 'group_changed' && typeof groupId === 'string') groupChange.value = { groupId, notify: notify === true }
if (type === 'group_list_changed') groupListChanges.value++
}
@@ -114,12 +119,12 @@ export const useSession = defineStore('session', () => {
}
return {
identity, connection, contactChanges, inboxChanges, groupChange, groupListChanges, authenticate, logout, authorized,
identity, connection, contactChanges, inboxChanges, privateNotice, groupChange, groupListChanges, authenticate, logout, authorized,
devices: () => authorized<Device[]>('/devices'),
revoke: (id: string) => authorized<void>('/devices/' + encodeURIComponent(id), 'DELETE'),
contacts: () => authorized<Contact[]>('/contacts'),
searchContact: (username: string) => authorized<Contact>('/contacts/search?' + new URLSearchParams({ username })),
changeContact: (id: string, action: ContactAction, alias: string, category: string) =>
changeContact: (id: string, action: ContactAction, alias?: string, category?: string) =>
authorized<void>('/contacts/' + encodeURIComponent(id), 'POST', { action, alias, category }),
}
})
+12
View File
@@ -39,6 +39,7 @@ 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)
@@ -101,6 +102,15 @@ async function refresh() {
if (!current.peers.some((device) => device.id === selected.value)) selected.value = current.peers[0]?.id ?? ''
}
function toggleMute() {
const contact = activeContact.value
if (!contact) return
void execute(async () => {
await session.changeContact(contact.id, contact.muted ? 'unmute' : 'mute')
await loadConversations()
})
}
function scheduleReceipt() {
clearTimeout(receiptTimer)
if (!view.value?.shareRead || busy.value || !trusted.value) return
@@ -287,6 +297,8 @@ onBeforeUnmount(() => {
<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="toggleMute">消息免打扰</button>
<button v-if="ownCode" class="plain" :disabled="busy" @click="sync">刷新</button>
</header>
<div class="conversation-layout">
+4 -1
View File
@@ -70,7 +70,8 @@ async function change(action: ContactAction) {
const contact = detail.value
if (!contact) return
await operation(async () => {
await session.changeContact(contact.id, action, alias.value, category.value)
if (action === 'preferences') await session.changeContact(contact.id, action, alias.value, category.value)
else await session.changeContact(contact.id, action)
pendingAction.value = undefined
if (['cancel', 'reject', 'delete', 'unblock'].includes(action)) {
result.value = undefined
@@ -116,6 +117,8 @@ async function change(action: ContactAction) {
<button v-if="detail.state === 'blocked'" class="plain" :disabled="busy" @click="change('unblock')">解除拉黑</button>
<form v-if="detail.state === 'friend'" class="contact-preferences" @submit.prevent="change('preferences')">
<RouterLink class="plain" :to="'/chat/' + detail.id">打开加密聊天</RouterLink>
<button type="button" class="plain" :aria-pressed="detail.muted" :disabled="busy"
@click="change(detail.muted ? 'unmute' : 'mute')">消息免打扰</button>
<label>备注<input v-model="alias" maxlength="64"></label>
<label>分组<input v-model="category" maxlength="32"></label>
<button class="plain" :disabled="busy">保存</button>
+29 -19
View File
@@ -9,7 +9,8 @@ const router = useRouter()
const error = ref('')
const busy = ref(false)
const browser = window.xhchat?.openBrowser
const notice = ref<string>()
type NoticeKind = 'group' | 'private'
const notice = ref<{ href: string; label: string }>()
let noticeTimer: ReturnType<typeof setTimeout> | undefined
const systemNotices = ref(false)
const noticeSettingStatus = ref('')
@@ -23,7 +24,7 @@ function noticeSettingKey() {
function closeSystemNotice() {
webNotice?.close()
webNotice = undefined
void window.xhchat?.closeGroupNotification().catch(() => {})
void window.xhchat?.closeMessageNotification().catch(() => {})
}
function readNoticeSetting() {
@@ -41,7 +42,7 @@ async function toggleSystemNotices() {
const enabled = !systemNotices.value
if (enabled) {
if (window.xhchat) {
if (!await window.xhchat.groupNotificationsSupported()) throw new Error('当前系统不支持桌面通知')
if (!await window.xhchat.messageNotificationsSupported()) throw new Error('当前系统不支持桌面通知')
} else {
if (!('Notification' in window)) throw new Error('当前浏览器不支持系统通知')
if (await Notification.requestPermission() !== 'granted') throw new Error('请在浏览器站点设置中允许通知')
@@ -51,13 +52,13 @@ async function toggleSystemNotices() {
localStorage.setItem(noticeSettingKey(), enabled ? 'enabled' : 'disabled')
systemNotices.value = enabled
if (!enabled) closeSystemNotice()
noticeSettingStatus.value = enabled ? '已在本设备启用群消息系统通知' : '已在本设备关闭群消息系统通知'
noticeSettingStatus.value = enabled ? '已在本设备启用消息系统通知' : '已在本设备关闭消息系统通知'
}
function showSystemNotice(group: string) {
function showSystemNotice(kind: NoticeKind, href: string, label: string) {
if (!systemNotices.value) return
if (window.xhchat) {
void window.xhchat.showGroupNotification().catch(() => {})
void window.xhchat.showMessageNotification(kind).catch(() => {})
return
}
if (!('Notification' in window) || Notification.permission !== 'granted' ||
@@ -65,11 +66,11 @@ function showSystemNotice(group: string) {
lastSystemNotice = Date.now()
try {
webNotice?.close()
webNotice = new Notification('XHChat', { body: '有新的群消息', icon: '/brand/xhchat.png', tag: 'xhchat-group' })
webNotice = new Notification('XHChat', { body: label, icon: '/brand/xhchat.png', tag: 'xhchat-' + kind })
webNotice.onclick = () => {
if (!session.identity) return
window.focus()
void router.push('/groups/' + group)
void router.push(href)
closeSystemNotice()
}
} catch {
@@ -82,15 +83,24 @@ function dismissNotice() {
notice.value = undefined
}
watch(() => session.groupChange, (event) => {
if (!event?.notify) return
showSystemNotice(event.groupId)
if (route.params.id === event.groupId) return
function showNotice(kind: NoticeKind, id: string) {
if (!/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(id)) return
const href = (kind === 'group' ? '/groups/' : '/chat/') + id
const label = kind === 'group' ? '有新的群消息' : '有新的私聊消息'
showSystemNotice(kind, href, label)
if (route.path === href) return
dismissNotice()
notice.value = event.groupId
notice.value = { href, label }
noticeTimer = setTimeout(dismissNotice, 8000)
}
watch(() => session.groupChange, (event) => {
if (event?.notify) showNotice('group', event.groupId)
})
watch(() => route.params.id, (id) => { if (id === notice.value) dismissNotice() })
watch(() => session.privateNotice, (event) => {
if (event) showNotice('private', event.contactId)
})
watch(() => route.path, (path) => { if (path === notice.value?.href) dismissNotice() })
onMounted(() => {
readNoticeSetting()
window.addEventListener('storage', storageChanged)
@@ -138,21 +148,21 @@ async function act(action: () => Promise<void>) {
<div class="account-footer">
<p aria-live="polite"><span class="dot" :class="{ online: session.connection === '实时连接已建立' }"></span>{{ session.connection }}</p>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<button class="plain" type="button" :aria-pressed="systemNotices" :disabled="busy" @click="act(toggleSystemNotices)">群消息系统通知</button>
<button class="plain" type="button" :aria-pressed="systemNotices" :disabled="busy" @click="act(toggleSystemNotices)">消息系统通知</button>
<small v-if="noticeSettingStatus" role="status">{{ noticeSettingStatus }}</small>
<button class="plain" :disabled="busy" @click="act(session.logout)">退出登录</button>
</div>
</aside>
<RouterView />
<div v-if="notice" class="group-notice" role="status">
<RouterLink :to="'/groups/' + notice" @click="dismissNotice">有新的群消息</RouterLink>
<button type="button" class="plain" aria-label="关闭群消息提醒" @click="dismissNotice">关闭</button>
<div v-if="notice" class="message-notice" role="status">
<RouterLink :to="notice.href" @click="dismissNotice">{{ notice.label }}</RouterLink>
<button type="button" class="plain" aria-label="关闭消息提醒" @click="dismissNotice">关闭</button>
</div>
</main>
</template>
<style scoped>
.group-notice {
.message-notice {
position: fixed; inset-inline-end: 1rem; inset-block-end: 1rem; z-index: 6;
display: flex; align-items: center; gap: .7rem; padding: .6rem .85rem;
background: var(--surface); border: 1px solid var(--line); border-radius: .5rem;