Merge pull request '私聊消息通知和联系人免打扰' (#41) from xhgit/private-notifications into main
Reviewed-on: #41
This commit was merged in pull request #41.
This commit is contained in:
commit
76cc023f96
23 files changed
+286
-97
No files matched your search
+17
-15
@@ -77,18 +77,20 @@ 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
|
||||
let messageNotification: Notification | undefined
|
||||
let lastMessageNotification = 0
|
||||
ipcMain.handle('notification:message-supported', (event) => trustedSender(event) && Notification.isSupported())
|
||||
ipcMain.handle('notification:message-show', (event, kind: unknown) => {
|
||||
if (!trustedSender(event) || (kind !== 'group' && kind !== 'private') || !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 }
|
||||
if (now - lastMessageNotification < 2500) return
|
||||
lastMessageNotification = now
|
||||
messageNotification?.close()
|
||||
const body = kind === 'group' ? '有新的群消息' : '有新的私聊消息'
|
||||
const notification = new Notification({ title: 'XHChat', body, icon: join(renderer, 'brand/xhchat.png') })
|
||||
messageNotification = notification
|
||||
const release = () => { if (messageNotification === notification) messageNotification = undefined }
|
||||
notification.once('close', release)
|
||||
notification.once('failed', release)
|
||||
notification.once('click', () => {
|
||||
@@ -100,12 +102,12 @@ async function start() {
|
||||
})
|
||||
notification.show()
|
||||
})
|
||||
ipcMain.handle('notification:group-close', (event) => {
|
||||
ipcMain.handle('notification:message-close', (event) => {
|
||||
if (!trustedSender(event)) return
|
||||
groupNotification?.close()
|
||||
groupNotification = undefined
|
||||
messageNotification?.close()
|
||||
messageNotification = undefined
|
||||
})
|
||||
win.on('closed', () => groupNotification?.close())
|
||||
win.on('closed', () => messageNotification?.close())
|
||||
let microphoneUntil = 0
|
||||
let microphonePage = ''
|
||||
function recordingPage(url: string) {
|
||||
|
||||
@@ -6,9 +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'),
|
||||
messageNotificationsSupported: () => ipcRenderer.invoke('notification:message-supported'),
|
||||
showMessageNotification: (kind: 'group' | 'private') => ipcRenderer.invoke('notification:message-show', kind),
|
||||
closeMessageNotification: () => ipcRenderer.invoke('notification:message-close'),
|
||||
allowVoiceRecording: () => ipcRenderer.invoke('voice:allow'),
|
||||
endVoiceRecording: () => ipcRenderer.invoke('voice:end'),
|
||||
signMls: (username: string, kind: string, user: string, device: string, value: Uint8Array) =>
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
| 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 |
|
||||
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
|
||||
| 加密群聊 | 创建群组、通过联系人或一次性链接及二维码邀请、管理成员和转让群主。群主可发布加密公告。群列表显示本机未读,并按账号同步置顶和免打扰。 |
|
||||
| 群消息通知 | 可在本机启用通用系统通知,免打扰群仍可同步和显示未读。 |
|
||||
| 消息通知 | 可在本机启用私聊和群聊的系统通知。联系人和群组可单独免打扰,密文仍会同步。 |
|
||||
| 加密附件 | 两端可在私聊和群聊发送、下载最多 8 MiB 的文件,并在本机预览图片和视频。群聊支持多选、拖拽发送,以及文件、图片和视频分类。 |
|
||||
| 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 |
|
||||
| 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索、收藏和本机删除。可打开消息里的网页链接,并将消息转发到加密群或已核验的联系人设备。私聊支持可选加密已读回执。 |
|
||||
|
||||
+3
-3
@@ -17,7 +17,7 @@
|
||||
| GET | /api/v1/contacts | 返回好友、来往申请和当前账号的黑名单 |
|
||||
| GET | /api/v1/contacts/search?username= | 按完整用户名查找,返回可见的联系人状态 |
|
||||
| POST | /api/v1/contacts/{id} | 请求体包含 action,可选 alias 和 category,成功返回 204 |
|
||||
| POST | /api/v1/inbox | 接收 messageId、recipientDevice 和 Base64 编码的 MLS 封包,返回字符串 sequence |
|
||||
| POST | /api/v1/inbox | 接收 messageId、recipientDevice、Base64 编码的 MLS 封包及可选的布尔值 silent,返回字符串 sequence |
|
||||
| GET | /api/v1/inbox?after= | 按当前设备和递增游标取最多 64 条封包 |
|
||||
| GET | /api/v1/contacts/{id}/devices | 返回已接受联系人的有效设备与公开身份密钥 |
|
||||
| POST | /api/v1/key-packages | 当前设备发布带设备签名的 MLS KeyPackage,成功返回 204 |
|
||||
@@ -42,9 +42,9 @@
|
||||
|
||||
用户名为 3–32 位 ASCII 字母、数字或下划线,忽略大小写。密码最少 12 个 Unicode 字符,最多 256 字节。platform 为 web 或 windows。公钥、签名和 challenge 使用无填充 Base64URL。设备使用 Ed25519 签名 UTF-8 字符串 `XHChat device authentication v1\n` 后紧接 challenge。该签名仅用于证明基础设备密钥持有权。
|
||||
|
||||
联系人操作包含 request、accept、reject、cancel、delete、block、unblock 和 preferences。变更后 WebSocket 发送 contacts_changed,客户端重新获取授权后的列表。
|
||||
联系人操作包含 request、accept、reject、cancel、delete、block、unblock、preferences、mute 和 unmute。联系人列表和搜索返回当前账号的 `muted`。备注、分组和免打扰的变更只给设置者的设备发送 `contacts_changed`,客户端重新获取列表。
|
||||
|
||||
设备投递当前要求双方是已接受的联系人,且两个设备均未撤销。接口校验 MLS 1.0 PrivateMessage 和 Welcome 的外层类型与长度,客户端负责完整协议验证。相同发送设备、接收设备、消息 ID 和封包的重试返回原游标,内容不同返回 409。WebSocket 的 inbox_changed 仅提示当前设备补拉。投递保留期由 XHCHAT_ENVELOPE_RETENTION 配置,默认 720 小时。
|
||||
设备投递当前要求双方是已接受的联系人,且两个设备均未撤销。接口校验 MLS 1.0 PrivateMessage 和 Welcome 的外层类型与长度,客户端负责完整协议验证。相同发送设备、接收设备、消息 ID 和封包的重试返回原游标,内容不同返回 409。`inbox_changed` 提示授权设备补拉。新的 PrivateMessage 投递在 `silent` 未开启且接收账号未静音此联系人时附带 `contactId` 和 `notify: true`。客户端对编辑、撤回和已读回执发送 `silent: true`。Welcome、重试及静音投递只发送补拉提示。投递保留期由 XHCHAT_ENVELOPE_RETENTION 配置,默认 720 小时。
|
||||
|
||||
密钥包与签名均使用标准 Base64。设备以已有的 Ed25519 密钥签名 UTF-8 前缀 `XHChat MLS KeyPackage v1\n{userId}\n{deviceId}\n` 和原始 MLS 封包的拼接。服务端验证签名和外层格式,密钥包可在发布后的 24 小时内领取一次。客户端仍需独立验证设备公钥信任和完整 MLS 对象。重试发布同一封包不会再次开放领取。
|
||||
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
| users | UUID 主键,规范化用户名唯一,密码保存 Argon2id PHC,记录创建时间 |
|
||||
| devices | UUID 主键,用户外键,用户内公钥唯一,记录平台、首次和最近活动时间、撤销时间 |
|
||||
| sessions | 高熵令牌的 SHA-256 摘要为主键,关联设备,包含到期时间 |
|
||||
| contact_relationships、contact_blocks、contact_preferences | 关系按账号对去重,拉黑有方向,私有备注按拥有者授权 |
|
||||
| contact_relationships、contact_blocks、contact_preferences | 关系按账号对去重,拉黑有方向,备注、分组与免打扰按拥有者授权 |
|
||||
| conversations、memberships | 会话与成员关系,记录角色和生效世代 |
|
||||
| devices、device_key_packages | 公开设备凭据及签名的一次性密钥包,事务领取,撤销后停止发放 |
|
||||
| device_envelopes | 二进制协议封包、投递游标和目标设备,按发送设备、接收设备和客户端消息 ID 幂等 |
|
||||
|
||||
@@ -204,3 +204,9 @@ Windows 和 Web 可从本机缓存删除群消息。删除同时移除其本机
|
||||
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 调用。通知中只含通用标题和提示文案。私聊和服务端投递回归通过。
|
||||
|
||||
## 私聊通知和联系人免打扰
|
||||
|
||||
私聊新增应用内提醒,点击进入相应会话。Windows 和 Web 复用原设备系统通知开关,启用后后台通知只显示 XHChat 和通用消息提示。私聊和联系人页均可切换免打扰,账号内同步设置。静音、重试和 MLS 会话初始化仍可触发密文补拉,当前客户端对已读回执、编辑和撤回请求静默投递。
|
||||
|
||||
Windows Electron 与 Edge 实测通知 API 调用、提醒跳转及免打扰后的同步。接口测试覆盖对方不可见设置、备注与分组保留、欢迎封包和重复提交只提示补拉,以及解除免打扰后恢复提醒。
|
||||
@@ -16,6 +16,7 @@ type Contact struct {
|
||||
State string `json:"state"`
|
||||
Alias string `json:"alias"`
|
||||
Category string `json:"category"`
|
||||
Muted bool `json:"muted"`
|
||||
}
|
||||
|
||||
type Store struct{ db *pgxpool.Pool }
|
||||
@@ -29,7 +30,7 @@ const selectContact = `
|
||||
WHEN r.requested_by = $1 THEN 'outgoing'
|
||||
WHEN r.status = 'pending' THEN 'incoming'
|
||||
ELSE 'none' END,
|
||||
COALESCE(p.alias,''), COALESCE(p.category,'')
|
||||
COALESCE(p.alias,''), COALESCE(p.category,''), COALESCE(p.muted,false)
|
||||
FROM users u
|
||||
LEFT JOIN contact_relationships r ON r.first_user = LEAST($1::uuid, u.id)
|
||||
AND r.second_user = GREATEST($1::uuid, u.id)
|
||||
@@ -42,7 +43,7 @@ const selectContact = `
|
||||
func (s *Store) Search(ctx context.Context, owner, username string) (Contact, error) {
|
||||
var c Contact
|
||||
err := s.db.QueryRow(ctx, selectContact+" AND u.username=$2", owner, username).
|
||||
Scan(&c.ID, &c.Username, &c.State, &c.Alias, &c.Category)
|
||||
Scan(&c.ID, &c.Username, &c.State, &c.Alias, &c.Category, &c.Muted)
|
||||
return c, err
|
||||
}
|
||||
|
||||
@@ -57,7 +58,7 @@ func (s *Store) List(ctx context.Context, owner string) ([]Contact, error) {
|
||||
result := make([]Contact, 0)
|
||||
for rows.Next() {
|
||||
var c Contact
|
||||
if err := rows.Scan(&c.ID, &c.Username, &c.State, &c.Alias, &c.Category); err != nil {
|
||||
if err := rows.Scan(&c.ID, &c.Username, &c.State, &c.Alias, &c.Category, &c.Muted); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, c)
|
||||
@@ -147,6 +148,16 @@ func (s *Store) Change(ctx context.Context, owner, target, action, alias, catego
|
||||
if err == nil && tag.RowsAffected() == 0 {
|
||||
return ErrUnavailable
|
||||
}
|
||||
case "mute", "unmute":
|
||||
tag, writeErr := tx.Exec(ctx, `
|
||||
INSERT INTO contact_preferences(owner_id,contact_id,alias,category,muted)
|
||||
SELECT $1::uuid,$2::uuid,'','',$3::boolean FROM contact_relationships WHERE `+pair+` AND status='accepted'
|
||||
ON CONFLICT (owner_id,contact_id) DO UPDATE SET muted=EXCLUDED.muted
|
||||
`, owner, target, action == "mute")
|
||||
err = writeErr
|
||||
if err == nil && tag.RowsAffected() == 0 {
|
||||
return ErrUnavailable
|
||||
}
|
||||
default:
|
||||
return ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE contact_preferences ADD COLUMN muted boolean NOT NULL DEFAULT false;
|
||||
@@ -43,6 +43,9 @@ var groupSeenMigration string
|
||||
//go:embed 012_group_invite_link.sql
|
||||
var groupInviteLinkMigration string
|
||||
|
||||
//go:embed 013_contact_mute.sql
|
||||
var contactMuteMigration string
|
||||
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
@@ -58,7 +61,7 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
for index, migration := range []string{
|
||||
identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration,
|
||||
attachmentsMigration, groupsMigration, groupTransportMigration, groupAttachmentsMigration, groupPreferencesMigration,
|
||||
groupSeenMigration, groupInviteLinkMigration,
|
||||
groupSeenMigration, groupInviteLinkMigration, contactMuteMigration,
|
||||
} {
|
||||
version := index + 1
|
||||
var applied bool
|
||||
|
||||
@@ -27,15 +27,15 @@ type Store struct{ db *pgxpool.Pool }
|
||||
|
||||
func New(db *pgxpool.Pool) *Store { return &Store{db: db} }
|
||||
|
||||
func (s *Store) Send(ctx context.Context, sender, recipient, message string, ciphertext []byte) (string, error) {
|
||||
func (s *Store) Send(ctx context.Context, sender, recipient, message string, ciphertext []byte, requestNotice bool) (string, bool, error) {
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", false, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
if err = authorizeDelivery(ctx, tx, sender, recipient); err != nil {
|
||||
return "", err
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
var seq string
|
||||
@@ -46,19 +46,34 @@ func (s *Store) Send(ctx context.Context, sender, recipient, message string, cip
|
||||
RETURNING sequence::text
|
||||
`, message, sender, recipient, ciphertext).Scan(&seq)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
requestNotice = false
|
||||
var previous []byte
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT sequence::text,ciphertext FROM device_envelopes
|
||||
WHERE message_id=$1 AND sender_device=$2 AND recipient_device=$3
|
||||
`, message, sender, recipient).Scan(&seq, &previous)
|
||||
if err == nil && !bytes.Equal(previous, ciphertext) {
|
||||
return "", ErrConflict
|
||||
return "", false, ErrConflict
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", false, err
|
||||
}
|
||||
return seq, tx.Commit(ctx)
|
||||
var notify bool
|
||||
if requestNotice {
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT NOT EXISTS (
|
||||
SELECT 1 FROM contact_preferences p
|
||||
JOIN devices sender ON sender.user_id=p.contact_id
|
||||
JOIN devices recipient ON recipient.user_id=p.owner_id
|
||||
WHERE sender.id=$1 AND recipient.id=$2 AND p.muted
|
||||
)
|
||||
`, sender, recipient).Scan(¬ify)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
}
|
||||
return seq, notify, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) Inbox(ctx context.Context, recipient string, after int64) ([]Envelope, error) {
|
||||
|
||||
@@ -78,7 +78,7 @@ func (a *API) changeContact(w http.ResponseWriter, r *http.Request, _ string, id
|
||||
}
|
||||
pipe := a.redis.Pipeline()
|
||||
pipe.Publish(r.Context(), "xhchat:contacts:"+identity.User.ID, "changed")
|
||||
if input.Action != "preferences" {
|
||||
if input.Action != "preferences" && input.Action != "mute" && input.Action != "unmute" {
|
||||
pipe.Publish(r.Context(), "xhchat:contacts:"+strings.ToLower(target), "changed")
|
||||
}
|
||||
_, _ = pipe.Exec(r.Context())
|
||||
|
||||
@@ -15,6 +15,7 @@ func (a *API) sendEnvelope(w http.ResponseWriter, r *http.Request, _ string, ide
|
||||
MessageID string `json:"messageId"`
|
||||
RecipientDevice string `json:"recipientDevice"`
|
||||
Ciphertext []byte `json:"ciphertext"`
|
||||
Silent bool `json:"silent"`
|
||||
}
|
||||
if !parseLimit(w, r, &input, 96<<10) {
|
||||
return
|
||||
@@ -27,7 +28,8 @@ func (a *API) sendEnvelope(w http.ResponseWriter, r *http.Request, _ string, ide
|
||||
return
|
||||
}
|
||||
recipient := strings.ToLower(input.RecipientDevice)
|
||||
seq, err := a.delivery.Send(r.Context(), identity.Device.ID, recipient, input.MessageID, input.Ciphertext)
|
||||
seq, notify, err := a.delivery.Send(r.Context(), identity.Device.ID, recipient, input.MessageID, input.Ciphertext,
|
||||
input.Ciphertext[3] == 2 && !input.Silent)
|
||||
switch {
|
||||
case errors.Is(err, delivery.ErrUnavailable):
|
||||
problem(w, 404, "delivery_unavailable", "无法向指定设备投递")
|
||||
@@ -36,7 +38,11 @@ func (a *API) sendEnvelope(w http.ResponseWriter, r *http.Request, _ string, ide
|
||||
case err != nil:
|
||||
unavailable(w, err)
|
||||
default:
|
||||
_ = a.redis.Publish(r.Context(), "xhchat:inbox:"+recipient, "changed").Err()
|
||||
hint := "changed"
|
||||
if notify {
|
||||
hint = "private-notify:" + identity.User.ID
|
||||
}
|
||||
_ = a.redis.Publish(r.Context(), "xhchat:inbox:"+recipient, hint).Err()
|
||||
respond(w, 200, map[string]string{"sequence": seq})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,12 +109,18 @@ func (a *API) realtime(w http.ResponseWriter, r *http.Request) {
|
||||
event["type"] = "group_list_changed"
|
||||
case inboxChannel:
|
||||
event["type"] = "inbox_changed"
|
||||
kind, group, _ := strings.Cut(change.Payload, ":")
|
||||
if (kind == "group" || kind == "group-notify") && uuidPattern.MatchString(group) {
|
||||
event["type"] = "group_changed"
|
||||
event["groupId"] = group
|
||||
if kind == "group-notify" {
|
||||
kind, id, _ := strings.Cut(change.Payload, ":")
|
||||
if uuidPattern.MatchString(id) {
|
||||
switch kind {
|
||||
case "private-notify":
|
||||
event["contactId"] = id
|
||||
event["notify"] = true
|
||||
case "group", "group-notify":
|
||||
event["type"] = "group_changed"
|
||||
event["groupId"] = id
|
||||
if kind == "group-notify" {
|
||||
event["notify"] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+47
-19
@@ -52,8 +52,8 @@ async function watchRealtime(actor, t) {
|
||||
}
|
||||
|
||||
// Opaque fixture with the MLS header. Crypto interoperability is tested separately in crypto/.
|
||||
function frame() {
|
||||
return Buffer.concat([Buffer.from([0, 1, 0, 2]), randomBytes(96)]).toString('base64')
|
||||
function frame(kind = 2) {
|
||||
return Buffer.concat([Buffer.from([0, 1, 0, kind]), randomBytes(96)]).toString('base64')
|
||||
}
|
||||
|
||||
test('群组邀请、授权、成员移除、版本变更与实时提示', { timeout: 25_000 }, async (t) => {
|
||||
@@ -333,12 +333,14 @@ test('群密文和实时提示只投递到名单设备,移除或撤销阻断
|
||||
assert.deepEqual(outsiderEvents, [])
|
||||
})
|
||||
|
||||
test('设备密文投递、幂等、离线补拉、实时提示和撤销', { timeout: 25000 }, async () => {
|
||||
test('设备密文投递、幂等、离线补拉、免打扰与撤销', { timeout: 25000 }, async (t) => {
|
||||
const sender = await register()
|
||||
const recipient = await register()
|
||||
const other = await register()
|
||||
const payload = { messageId: randomUUID(), recipientDevice: recipient.device.id, ciphertext: frame() }
|
||||
const preferences = '/contacts/' + sender.user.id
|
||||
await json('/inbox', 'POST', sender.token, payload, 404)
|
||||
await json(preferences, 'POST', recipient.token, { action: 'mute' }, 409)
|
||||
await contact(sender, recipient, 'request')
|
||||
await contact(recipient, sender, 'accept')
|
||||
await json('/inbox', 'POST', sender.token, { ...payload, ciphertext: Buffer.from('plaintext').toString('base64') }, 400)
|
||||
@@ -355,23 +357,49 @@ test('设备密文投递、幂等、离线补拉、实时提示和撤销', { tim
|
||||
assert.deepEqual(await json('/inbox', 'GET', sender.token), [])
|
||||
assert.deepEqual(await json('/inbox', 'GET', other.token), [])
|
||||
|
||||
const { ticket } = await json('/realtime/ticket', 'POST', recipient.token)
|
||||
const ws = new WebSocket(base.replace(/^http/, 'ws') + '/api/v1/realtime', ['xhchat.v1', 'ticket.' + ticket], { origin: base })
|
||||
try {
|
||||
assert.equal(JSON.parse((await once(ws, 'message'))[0]).type, 'ready')
|
||||
const changed = once(ws, 'message')
|
||||
const second = { ...payload, messageId: randomUUID(), ciphertext: frame() }
|
||||
await json('/inbox', 'POST', sender.token, second)
|
||||
assert.equal(JSON.parse((await changed)[0]).type, 'inbox_changed')
|
||||
const pending = await json('/inbox?after=' + first.sequence, 'GET', recipient.token)
|
||||
assert.equal(pending.length, 1)
|
||||
assert.equal(pending[0].ciphertext, second.ciphertext)
|
||||
assert.equal((await call('/devices/' + recipient.device.id, 'DELETE', recipient.token)).status, 204)
|
||||
await json('/inbox', 'GET', recipient.token, undefined, 401)
|
||||
await json('/inbox', 'POST', sender.token, { ...payload, messageId: randomUUID() }, 404)
|
||||
} finally {
|
||||
ws.terminate()
|
||||
const [socket, senderSocket] = await Promise.all([recipient, sender].map((actor) => watchRealtime(actor, t)))
|
||||
const senderEvents = []
|
||||
senderSocket.on('message', (data) => senderEvents.push(JSON.parse(data)))
|
||||
async function expectEvent(type, act) {
|
||||
const arrival = once(socket, 'message', { signal: AbortSignal.timeout(4000) })
|
||||
const [[data], result] = await Promise.all([arrival, act()])
|
||||
assert.deepEqual(JSON.parse(data), type)
|
||||
return result
|
||||
}
|
||||
const syncOnly = { type: 'inbox_changed' }
|
||||
const alert = { ...syncOnly, contactId: sender.user.id, notify: true }
|
||||
const contactsChanged = { type: 'contacts_changed' }
|
||||
const newPayload = (ciphertext = frame()) => ({ ...payload, messageId: randomUUID(), ciphertext })
|
||||
const deliver = (expected, packet) => expectEvent(expected, () => json('/inbox', 'POST', sender.token, packet))
|
||||
const second = newPayload()
|
||||
const result = await deliver(alert, second)
|
||||
assert.deepEqual(await deliver(syncOnly, second), result)
|
||||
await deliver(syncOnly, newPayload(frame(3)))
|
||||
await deliver(syncOnly, { ...newPayload(), silent: true })
|
||||
|
||||
await expectEvent(contactsChanged, () => contact(recipient, sender, 'mute'))
|
||||
await expectEvent(contactsChanged, async () => {
|
||||
const reply = await call(preferences, 'POST', recipient.token, { action: 'preferences', alias: '朋友', category: '测试' })
|
||||
assert.equal(reply.status, 204, await reply.text())
|
||||
})
|
||||
assert.deepEqual((await json('/contacts', 'GET', recipient.token))[0], {
|
||||
id: sender.user.id, username: sender.user.username, state: 'friend', alias: '朋友', category: '测试', muted: true,
|
||||
})
|
||||
assert.equal((await json('/contacts', 'GET', sender.token))[0].muted, false)
|
||||
const muted = newPayload()
|
||||
await deliver(syncOnly, muted)
|
||||
const pending = await json('/inbox?after=' + first.sequence, 'GET', recipient.token)
|
||||
assert.equal(pending.length, 4)
|
||||
assert.equal(pending[0].ciphertext, second.ciphertext)
|
||||
assert.equal(pending.at(-1).ciphertext, muted.ciphertext)
|
||||
await expectEvent(contactsChanged, () => contact(recipient, sender, 'unmute'))
|
||||
const unmuted = (await json('/contacts', 'GET', recipient.token))[0]
|
||||
assert.deepEqual([unmuted.muted, unmuted.alias, unmuted.category], [false, '朋友', '测试'])
|
||||
await deliver(alert, newPayload())
|
||||
assert.deepEqual(senderEvents, [])
|
||||
assert.equal((await call('/devices/' + recipient.device.id, 'DELETE', recipient.token)).status, 204)
|
||||
await json('/inbox', 'GET', recipient.token, undefined, 401)
|
||||
await json('/inbox', 'POST', sender.token, newPayload(), 404)
|
||||
})
|
||||
|
||||
test('设备密钥包验证签名并只领取一次', { timeout: 25000 }, async () => {
|
||||
|
||||
@@ -123,6 +123,7 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
|
||||
await windows.getByLabel('发送已读回执').check()
|
||||
await sentLine.getByText('已读', { exact: true }).waitFor({ timeout: 15_000 })
|
||||
assert.ok(receiptPackets.length > 0)
|
||||
assert.ok(receiptPackets.every((item) => item.silent === true))
|
||||
assert.ok(receiptPackets.every((item) => !JSON.stringify(item).includes(packet.messageId)))
|
||||
const reply = 'Windows 到 Web ' + randomBytes(8).toString('hex')
|
||||
await windows.getByRole('listitem').filter({ hasText: text }).getByRole('button', { name: '引用', exact: true }).click()
|
||||
@@ -235,6 +236,82 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
|
||||
} finally { db.close() }
|
||||
})
|
||||
assert.deepEqual(stored, [{ wrapped: true, encrypted: true, fields: ['iv', 'key', 'sealed'] }])
|
||||
|
||||
const systemToggle = (page) => page.getByRole('button', { name: '消息系统通知', exact: true })
|
||||
const privateNotice = (page) => page.getByRole('link', { name: '有新的私聊消息', exact: true })
|
||||
const muteToggle = (page) => page.getByRole('button', { name: '消息免打扰', exact: true })
|
||||
await desktop.evaluate(({ Notification }) => {
|
||||
const nativeShow = Notification.prototype.show
|
||||
globalThis.privateNotificationLog = []
|
||||
Notification.prototype.show = function () {
|
||||
globalThis.privateNotificationLog.push({ title: this.title, body: this.body })
|
||||
return nativeShow.call(this)
|
||||
}
|
||||
})
|
||||
await systemToggle(windows).click()
|
||||
await windows.getByText('已在本设备启用消息系统通知', { exact: true }).waitFor()
|
||||
await work(windows).getByRole('link', { name: '设备管理' }).click()
|
||||
const desktopNoticeText = 'Windows 后台私聊 ' + randomBytes(8).toString('hex')
|
||||
await desktop.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].minimize())
|
||||
try {
|
||||
await send(web, desktopNoticeText)
|
||||
const toast = await desktop.evaluate(async () => {
|
||||
for (let attempt = 0; attempt < 30 && !globalThis.privateNotificationLog.length; attempt++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 150))
|
||||
}
|
||||
return globalThis.privateNotificationLog[0]
|
||||
})
|
||||
assert.deepEqual(toast, { title: 'XHChat', body: '有新的私聊消息' })
|
||||
} finally {
|
||||
await desktop.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].restore())
|
||||
}
|
||||
await privateNotice(windows).click()
|
||||
await windows.waitForURL(windowsChat)
|
||||
await enable(windows)
|
||||
await windows.getByText(desktopNoticeText, { exact: true }).waitFor()
|
||||
|
||||
assert.equal(await systemToggle(web).getAttribute('aria-pressed'), 'false')
|
||||
await web.context().grantPermissions(['notifications'], { origin: base })
|
||||
await web.evaluate(() => {
|
||||
const BrowserNotification = window.Notification
|
||||
window.privateNotificationLog = []
|
||||
window.Notification = class extends BrowserNotification {
|
||||
constructor(title, options) {
|
||||
super(title, options)
|
||||
window.privateNotificationLog.push({ title, body: options.body, tag: options.tag })
|
||||
}
|
||||
}
|
||||
document.hasFocus = () => false
|
||||
})
|
||||
await systemToggle(web).click()
|
||||
await web.getByText('已在本设备启用消息系统通知', { exact: true }).waitFor()
|
||||
const webChat = web.url()
|
||||
await work(web).getByRole('link', { name: '设备管理' }).click()
|
||||
const webNoticeText = 'Edge 后台私聊 ' + randomBytes(8).toString('hex')
|
||||
await send(windows, webNoticeText)
|
||||
await privateNotice(web).waitFor()
|
||||
await web.waitForFunction(() => window.privateNotificationLog.length === 1)
|
||||
assert.deepEqual(await web.evaluate(() => window.privateNotificationLog[0]),
|
||||
{ title: 'XHChat', body: '有新的私聊消息', tag: 'xhchat-private' })
|
||||
await privateNotice(web).click()
|
||||
await web.waitForURL(webChat)
|
||||
await enable(web)
|
||||
await web.getByText(webNoticeText, { exact: true }).waitFor()
|
||||
|
||||
await muteToggle(web).click()
|
||||
await web.getByRole('button', { name: '消息免打扰', pressed: true }).waitFor()
|
||||
assert.equal(await muteToggle(windows).getAttribute('aria-pressed'), 'false')
|
||||
await work(web).getByRole('link', { name: '联系人' }).click()
|
||||
await web.getByRole('button', { name: new RegExp(b) }).click()
|
||||
await web.getByRole('button', { name: '消息免打扰', pressed: true }).waitFor()
|
||||
const mutedText = '免打扰仍能同步 ' + randomBytes(8).toString('hex')
|
||||
await send(windows, mutedText)
|
||||
await web.getByRole('link', { name: '打开加密聊天' }).click()
|
||||
await enable(web)
|
||||
await web.getByText(mutedText, { exact: true }).waitFor()
|
||||
assert.equal(await privateNotice(web).count(), 0)
|
||||
assert.equal(await web.evaluate(() => window.privateNotificationLog.length), 1)
|
||||
|
||||
const link = base + '/healthz'
|
||||
await send(web, link)
|
||||
const webLink = web.getByRole('link', { name: link, exact: true })
|
||||
|
||||
@@ -176,10 +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 })
|
||||
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()
|
||||
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()
|
||||
@@ -691,10 +691,10 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
|
||||
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 })
|
||||
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 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())
|
||||
@@ -709,8 +709,8 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
|
||||
} finally {
|
||||
await restoreWindow()
|
||||
}
|
||||
await windows.getByRole('button', { name: '群消息系统通知', pressed: true }).click()
|
||||
await windows.getByText('已在本设备关闭群消息系统通知', { exact: true }).waitFor()
|
||||
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 })
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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 }),
|
||||
}
|
||||
})
|
||||
@@ -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">
|
||||
|
||||
@@ -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
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user