接入群消息系统通知和本机开关
This commit is contained in:
1 parent
fef421bd4b
commit
5c882ac855
7 files changed
+179
-6
No files matched your search
+31
-1
@@ -1,4 +1,4 @@
|
||||
import { app, BrowserWindow, ipcMain, protocol, safeStorage, session } from 'electron'
|
||||
import { app, BrowserWindow, ipcMain, Notification, protocol, safeStorage, session } from 'electron'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { signChallenge, signMls } from './identity'
|
||||
@@ -6,6 +6,7 @@ import { openBrowser, registerBrowserHandlers, website } from './browser'
|
||||
|
||||
const appURL = 'xhchat://app/'
|
||||
app.enableSandbox()
|
||||
if (process.platform === 'win32' && !app.isPackaged) app.setAppUserModelId(process.execPath)
|
||||
protocol.registerSchemesAsPrivileged([{
|
||||
scheme: 'xhchat', privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true },
|
||||
}])
|
||||
@@ -76,6 +77,35 @@ async function start() {
|
||||
return !win.isDestroyed() && event.sender === win.webContents && frame && frame === win.webContents.mainFrame &&
|
||||
frame.url.split('#')[0] === appURL
|
||||
}
|
||||
let groupNotification: Notification | undefined
|
||||
let lastGroupNotification = 0
|
||||
ipcMain.handle('notification:group-supported', (event) => trustedSender(event) && Notification.isSupported())
|
||||
ipcMain.handle('notification:group-show', (event) => {
|
||||
if (!trustedSender(event) || !Notification.isSupported() || (win.isFocused() && !win.isMinimized())) return
|
||||
const now = Date.now()
|
||||
if (now - lastGroupNotification < 2500) return
|
||||
lastGroupNotification = now
|
||||
groupNotification?.close()
|
||||
const notification = new Notification({ title: 'XHChat', body: '有新的群消息', icon: join(renderer, 'brand/xhchat.png') })
|
||||
groupNotification = notification
|
||||
const release = () => { if (groupNotification === notification) groupNotification = undefined }
|
||||
notification.once('close', release)
|
||||
notification.once('failed', release)
|
||||
notification.once('click', () => {
|
||||
release()
|
||||
if (win.isDestroyed()) return
|
||||
if (win.isMinimized()) win.restore()
|
||||
win.show()
|
||||
win.focus()
|
||||
})
|
||||
notification.show()
|
||||
})
|
||||
ipcMain.handle('notification:group-close', (event) => {
|
||||
if (!trustedSender(event)) return
|
||||
groupNotification?.close()
|
||||
groupNotification = undefined
|
||||
})
|
||||
win.on('closed', () => groupNotification?.close())
|
||||
let microphoneUntil = 0
|
||||
let microphonePage = ''
|
||||
function recordingPage(url: string) {
|
||||
|
||||
@@ -6,6 +6,9 @@ contextBridge.exposeInMainWorld('xhchat', {
|
||||
apiBase: apiArgument?.slice('--xhchat-api='.length),
|
||||
signChallenge: (username: string, challenge: string) => ipcRenderer.invoke('device:sign', username, challenge),
|
||||
openBrowser: (url?: string) => ipcRenderer.invoke('browser:open', url),
|
||||
groupNotificationsSupported: () => ipcRenderer.invoke('notification:group-supported'),
|
||||
showGroupNotification: () => ipcRenderer.invoke('notification:group-show'),
|
||||
closeGroupNotification: () => ipcRenderer.invoke('notification:group-close'),
|
||||
allowVoiceRecording: () => ipcRenderer.invoke('voice:allow'),
|
||||
endVoiceRecording: () => ipcRenderer.invoke('voice:end'),
|
||||
signMls: (username: string, kind: string, user: string, device: string, value: Uint8Array) =>
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
| 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 |
|
||||
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
|
||||
| 加密群聊 | 创建群组、通过联系人或一次性链接及二维码邀请、管理成员和转让群主。群主可发布加密公告。群列表显示本机未读,并按账号同步置顶和免打扰。 |
|
||||
| 群消息通知 | 可在本机启用通用系统通知,免打扰群仍可同步和显示未读。 |
|
||||
| 加密附件 | 两端可在私聊和群聊发送、下载最多 8 MiB 的文件,并在本机预览图片和视频。群聊支持多选、拖拽发送,以及文件、图片和视频分类。 |
|
||||
| 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 |
|
||||
| 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索、收藏和本机删除。可打开消息里的网页链接,并将消息转发到加密群或已核验的联系人设备。私聊支持可选加密已读回执。 |
|
||||
|
||||
+7
-1
@@ -165,7 +165,7 @@ Windows Electron 和 Edge 验证了群组页在兜底轮询前显示邀请、成
|
||||
|
||||
## 群置顶和免打扰
|
||||
|
||||
两端可按账号设置群置顶和免打扰,置顶群排在群列表前面。离开群页面时,未静音的新群投递可显示通用的应用内提醒,点击返回群组。免打扰保留 WebSocket 补拉提示,省略应用内提醒标记。原生系统通知和 Web Push 仍待实现。
|
||||
两端可按账号设置群置顶和免打扰,置顶群排在群列表前面。离开群页面时,未静音的新群投递可显示通用的应用内提醒,点击返回群组。免打扰保留 WebSocket 补拉提示,省略通知标记。
|
||||
|
||||
测试覆盖迁移 010、邀请者和外部账号不可修改群设置、不同账号的设置隔离、双端静音收取和提醒入口,以及同一账号的两台设备实时同步偏好。
|
||||
|
||||
@@ -198,3 +198,9 @@ Windows Electron 与 Edge 验证多选发送、拖拽和移除待发文件。模
|
||||
Windows 和 Web 可从本机缓存删除群消息。删除同时移除其本机收藏和分类入口,保留同步游标,重新进入群聊不会重复取回该记录。其他设备照常保留各自记录。已经另存的文件由用户在系统中管理。
|
||||
|
||||
集成测试验证 Windows 从群文件视图删除收藏文件后,重新进入群聊仍保持删除,Web 保留原消息。群链接在 Edge 新标签页与 Windows 隔离 Chromium 中实际打开。群聊、私聊和服务端投递回归共 8 项通过。
|
||||
|
||||
## 群消息系统通知
|
||||
|
||||
Windows 和 Web 的账号侧栏提供本机通知开关,默认关闭。窗口或标签页在后台且有有效实时连接时,未静音的群投递可以显示通用系统通知。通知只显示 XHChat 和「有新的群消息」。Web 点击通知打开相应群组,Windows 点击通知恢复应用窗口。Web 需要站点通知授权,关闭网页后的 Web Push 待实现。Windows 通知中心的展示还取决于系统通知设置及应用注册,打包安装验收待完成。 [Electron 通知文档](https://www.electronjs.org/docs/latest/tutorial/notifications) · [浏览器通知文档](https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API)
|
||||
|
||||
集成验收验证设备开关、静音不触发通知、Web 通知 API 和 Windows 窗口最小化后的原生通知 API 调用。通知中只含通用标题和提示文案。私聊和服务端投递回归通过。
|
||||
@@ -133,6 +133,18 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
|
||||
route.connectToServer()
|
||||
})
|
||||
await owner.context().grantPermissions(['microphone'], { origin: base })
|
||||
await removed.context().grantPermissions(['notifications'], { origin: base })
|
||||
await removed.addInitScript(() => {
|
||||
const BrowserNotification = window.Notification
|
||||
window.groupNotificationLog = []
|
||||
window.Notification = class extends BrowserNotification {
|
||||
constructor(title, options) {
|
||||
super(title, options)
|
||||
window.groupNotificationLog.push({ title, body: options.body, tag: options.tag })
|
||||
}
|
||||
}
|
||||
document.hasFocus = () => false
|
||||
})
|
||||
await Promise.all([owner.goto(base), removed.goto(base)])
|
||||
desktop = await _electron.launch({
|
||||
executablePath: electron,
|
||||
@@ -140,6 +152,14 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
|
||||
env: { ...process.env, XHCHAT_SERVER_URL: base },
|
||||
})
|
||||
const windows = await desktop.firstWindow()
|
||||
await desktop.evaluate(({ Notification }) => {
|
||||
const show = Notification.prototype.show
|
||||
globalThis.groupNotificationLog = []
|
||||
Notification.prototype.show = function () {
|
||||
globalThis.groupNotificationLog.push({ title: this.title, body: this.body })
|
||||
return show.call(this)
|
||||
}
|
||||
})
|
||||
pages.push(owner, windows, removed)
|
||||
assert.equal(await windows.evaluate(async () => {
|
||||
try { await window.xhchat.allowVoiceRecording(); return true } catch { return false }
|
||||
@@ -156,6 +176,10 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
|
||||
await owner.getByRole('heading', { name: group }).waitFor()
|
||||
await invite(owner, windows, names[1], group)
|
||||
await invite(owner, removed, names[2], group)
|
||||
const webToggle = removed.getByRole('button', { name: '群消息系统通知', exact: true })
|
||||
assert.equal(await webToggle.getAttribute('aria-pressed'), 'false')
|
||||
await webToggle.click()
|
||||
await removed.getByText('已在本设备启用群消息系统通知', { exact: true }).waitFor()
|
||||
const settings = (page, name) => page.getByRole('button', { name, exact: true })
|
||||
await settings(removed, '群聊免打扰').click()
|
||||
await removed.getByRole('button', { name: '群聊免打扰', pressed: true }).waitFor()
|
||||
@@ -201,6 +225,7 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
|
||||
await owner.getByText('实时连接已建立', { exact: true }).waitFor()
|
||||
await Promise.all([owner, windows].map((page) => chat(page).getByText(first, { exact: true }).waitFor({ timeout: 3500 })))
|
||||
assert.equal(await removed.getByRole('link', { name: '有新的群消息' }).count(), 0)
|
||||
assert.equal(await removed.evaluate(() => window.groupNotificationLog.length), 0)
|
||||
await work(removed).getByRole('link', { name: '群组' }).click()
|
||||
const unreadGroup = removed.getByRole('link', { name: new RegExp(group + '.*1 条未读') })
|
||||
await unreadGroup.click()
|
||||
@@ -242,6 +267,9 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
|
||||
assert.equal(await send(windows, edited, '保存编辑'), epoch)
|
||||
const notice = removed.getByRole('link', { name: '有新的群消息' })
|
||||
await notice.waitFor({ timeout: 4500 })
|
||||
await removed.waitForFunction(() => window.groupNotificationLog.length === 1)
|
||||
assert.deepEqual(await removed.evaluate(() => window.groupNotificationLog[0]),
|
||||
{ title: 'XHChat', body: '有新的群消息', tag: 'xhchat-group' })
|
||||
const incomingEdit = chat(owner).getByRole('listitem').filter({ has: owner.getByText(edited, { exact: true }) })
|
||||
await incomingEdit.getByText('已编辑', { exact: true }).waitFor()
|
||||
await notice.click()
|
||||
@@ -659,6 +687,30 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
|
||||
await successorAnnouncement.getByLabel('公告内容').fill('新群主公告')
|
||||
await successorAnnouncement.getByRole('button', { name: '发布公告' }).click()
|
||||
await successorAnnouncement.getByText('新群主公告', { exact: true }).waitFor()
|
||||
|
||||
await owner.getByRole('link', { name: new RegExp(group) }).click()
|
||||
await chat(owner).getByRole('button', { name: '启用本机群聊' }).click()
|
||||
await chat(owner).getByText('群加密已建立', { exact: true }).waitFor()
|
||||
const windowsToggle = windows.getByRole('button', { name: '群消息系统通知', exact: true })
|
||||
assert.equal(await windowsToggle.getAttribute('aria-pressed'), 'false')
|
||||
await windowsToggle.click()
|
||||
await windows.getByText('已在本设备启用群消息系统通知', { exact: true }).waitFor()
|
||||
await desktop.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].minimize())
|
||||
await send(owner, 'Windows 后台群消息 ' + id())
|
||||
const restoreWindow = async () => desktop.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].restore())
|
||||
try {
|
||||
const toast = await desktop.evaluate(async () => {
|
||||
for (let attempt = 0; attempt < 24 && !globalThis.groupNotificationLog.length; attempt++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 150))
|
||||
}
|
||||
return globalThis.groupNotificationLog[0]
|
||||
})
|
||||
assert.deepEqual(toast, { title: 'XHChat', body: '有新的群消息' })
|
||||
} finally {
|
||||
await restoreWindow()
|
||||
}
|
||||
await windows.getByRole('button', { name: '群消息系统通知', pressed: true }).click()
|
||||
await windows.getByText('已在本设备关闭群消息系统通知', { exact: true }).waitFor()
|
||||
} 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 })
|
||||
|
||||
@@ -7,6 +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>
|
||||
allowVoiceRecording: () => Promise<void>
|
||||
endVoiceRecording: () => Promise<void>
|
||||
signMls: (username: string, kind: 'credential' | 'KeyPackage', user: string, device: string, value: Uint8Array<ArrayBuffer>) => Promise<Uint8Array<ArrayBuffer>>
|
||||
|
||||
@@ -1,15 +1,81 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useSession } from '../session'
|
||||
|
||||
const session = useSession()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const error = ref('')
|
||||
const busy = ref(false)
|
||||
const browser = window.xhchat?.openBrowser
|
||||
const notice = ref<string>()
|
||||
let noticeTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const systemNotices = ref(false)
|
||||
const noticeSettingStatus = ref('')
|
||||
let webNotice: Notification | undefined
|
||||
let lastSystemNotice = 0
|
||||
|
||||
function noticeSettingKey() {
|
||||
return 'xhchat-group-notifications:' + (window.xhchat?.apiBase ?? location.origin) + '/' + session.identity?.device.id
|
||||
}
|
||||
|
||||
function closeSystemNotice() {
|
||||
webNotice?.close()
|
||||
webNotice = undefined
|
||||
void window.xhchat?.closeGroupNotification().catch(() => {})
|
||||
}
|
||||
|
||||
function readNoticeSetting() {
|
||||
try { systemNotices.value = localStorage.getItem(noticeSettingKey()) === 'enabled' }
|
||||
catch { systemNotices.value = false }
|
||||
if (!systemNotices.value) closeSystemNotice()
|
||||
}
|
||||
|
||||
function storageChanged(event: StorageEvent) {
|
||||
if (event.key === noticeSettingKey()) readNoticeSetting()
|
||||
}
|
||||
|
||||
async function toggleSystemNotices() {
|
||||
noticeSettingStatus.value = ''
|
||||
const enabled = !systemNotices.value
|
||||
if (enabled) {
|
||||
if (window.xhchat) {
|
||||
if (!await window.xhchat.groupNotificationsSupported()) throw new Error('当前系统不支持桌面通知')
|
||||
} else {
|
||||
if (!('Notification' in window)) throw new Error('当前浏览器不支持系统通知')
|
||||
if (await Notification.requestPermission() !== 'granted') throw new Error('请在浏览器站点设置中允许通知')
|
||||
}
|
||||
}
|
||||
if (!session.identity) return
|
||||
localStorage.setItem(noticeSettingKey(), enabled ? 'enabled' : 'disabled')
|
||||
systemNotices.value = enabled
|
||||
if (!enabled) closeSystemNotice()
|
||||
noticeSettingStatus.value = enabled ? '已在本设备启用群消息系统通知' : '已在本设备关闭群消息系统通知'
|
||||
}
|
||||
|
||||
function showSystemNotice(group: string) {
|
||||
if (!systemNotices.value) return
|
||||
if (window.xhchat) {
|
||||
void window.xhchat.showGroupNotification().catch(() => {})
|
||||
return
|
||||
}
|
||||
if (!('Notification' in window) || Notification.permission !== 'granted' ||
|
||||
(document.visibilityState === 'visible' && document.hasFocus()) || Date.now() - lastSystemNotice < 2500) return
|
||||
lastSystemNotice = Date.now()
|
||||
try {
|
||||
webNotice?.close()
|
||||
webNotice = new Notification('XHChat', { body: '有新的群消息', icon: '/brand/xhchat.png', tag: 'xhchat-group' })
|
||||
webNotice.onclick = () => {
|
||||
if (!session.identity) return
|
||||
window.focus()
|
||||
void router.push('/groups/' + group)
|
||||
closeSystemNotice()
|
||||
}
|
||||
} catch {
|
||||
// The application notification remains available in browsers without desktop delivery.
|
||||
}
|
||||
}
|
||||
|
||||
function dismissNotice() {
|
||||
clearTimeout(noticeTimer)
|
||||
@@ -17,13 +83,23 @@ function dismissNotice() {
|
||||
}
|
||||
|
||||
watch(() => session.groupChange, (event) => {
|
||||
if (!event?.notify || route.params.id === event.groupId) return
|
||||
if (!event?.notify) return
|
||||
showSystemNotice(event.groupId)
|
||||
if (route.params.id === event.groupId) return
|
||||
dismissNotice()
|
||||
notice.value = event.groupId
|
||||
noticeTimer = setTimeout(dismissNotice, 8000)
|
||||
})
|
||||
watch(() => route.params.id, (id) => { if (id === notice.value) dismissNotice() })
|
||||
onBeforeUnmount(dismissNotice)
|
||||
onMounted(() => {
|
||||
readNoticeSetting()
|
||||
window.addEventListener('storage', storageChanged)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
dismissNotice()
|
||||
closeSystemNotice()
|
||||
window.removeEventListener('storage', storageChanged)
|
||||
})
|
||||
|
||||
async function act(action: () => Promise<void>) {
|
||||
busy.value = true
|
||||
@@ -62,6 +138,8 @@ 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>
|
||||
<small v-if="noticeSettingStatus" role="status">{{ noticeSettingStatus }}</small>
|
||||
<button class="plain" :disabled="busy" @click="act(session.logout)">退出登录</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
Reference in new issue
Block a user