增加私聊置顶和按设备统计未读

This commit is contained in:
xhgit committed 2026-11-15 22:35:45 +08:00
1 parent 7e165ba9b4
commit ec2679b991
19 files changed
+312 -52

No files matched your search

+1
View File
@@ -19,6 +19,7 @@
| 账号与设备 | Windows 和 Web 共用账号,支持用户名注册、登录、查看设备和远程撤销。 |
| 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 |
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
| 私聊会话 | 会话置顶随账号同步。当前设备的未读数可在重新登录后恢复,免打扰会话仍显示未读。 |
| 加密群聊 | 创建群组、通过联系人或一次性链接及二维码邀请、管理成员和转让群主。群主可发布加密公告。群列表显示本机未读,并按账号同步置顶和免打扰。 |
| 消息通知 | 可在本机启用私聊和群聊的系统通知。联系人和群组可单独免打扰,密文仍会同步。 |
| 加密附件 | 两端可在私聊和群聊发送、下载最多 8 MiB 的文件,并在本机预览图片和视频。群聊支持多选、拖拽发送,以及文件、图片和视频分类。 |
+5 -1
View File
@@ -19,6 +19,8 @@
| POST | /api/v1/contacts/{id} | 请求体包含 action,可选 alias 和 category,成功返回 204 |
| POST | /api/v1/inbox | 接收 messageId、recipientDevice、Base64 编码的 MLS 封包及可选的布尔值 silent,返回字符串 sequence |
| GET | /api/v1/inbox?after= | 按当前设备和递增游标取最多 64 条封包 |
| GET | /api/v1/inbox/unread | 返回当前设备的未读数,以联系人账号 ID 为键,省略为零的项 |
| POST | /api/v1/inbox/seen | 传 senderDevice 和字符串 sequence,更新当前设备对该发送设备的已查看游标 |
| GET | /api/v1/contacts/{id}/devices | 返回已接受联系人的有效设备与公开身份密钥 |
| POST | /api/v1/key-packages | 当前设备发布带设备签名的 MLS KeyPackage,成功返回 204 |
| GET | /api/v1/key-packages | 返回当前设备尚可领取的密钥包数量 available |
@@ -42,10 +44,12 @@
用户名为 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、mute 和 unmute。联系人列表和搜索返回当前账号的 `muted`。备注、分组和免打扰的变更只给设置者的设备发送 `contacts_changed`,客户端重新获取列表。
联系人操作包含 request、accept、reject、cancel、delete、block、unblock、preferences、mute、unmute、pin 和 unpin。联系人列表和搜索返回当前账号的 `muted` 与 `pinned`。备注、分组、免打扰和置顶的变更只给设置者的设备发送 `contacts_changed`,客户端重新获取列表。
设备投递当前要求双方是已接受的联系人,且两个设备均未撤销。接口校验 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 对象。重试发布同一封包不会再次开放领取。
MLS 凭据由标准 Base64 的 publicKey 和 signature 组成,使用 UTF-8 前缀 `XHChat MLS credential v1\n{userId}\n{deviceId}\n` 后接 32 字节 MLS Ed25519 公钥。设备目录返回可选的 mls 对象。已登记公钥仅允许原值重试。
+2 -1
View File
@@ -5,7 +5,8 @@
| users | UUID 主键,规范化用户名唯一,密码保存 Argon2id PHC,记录创建时间 |
| devices | UUID 主键,用户外键,用户内公钥唯一,记录平台、首次和最近活动时间、撤销时间 |
| sessions | 高熵令牌的 SHA-256 摘要为主键,关联设备,包含到期时间 |
| contact_relationships、contact_blocks、contact_preferences | 关系按账号对去重,拉黑有方向,备注、分组与免打扰按拥有者授权 |
| contact_relationships、contact_blocks、contact_preferences | 关系按账号对去重,拉黑有方向,备注、分组、免打扰和置顶按拥有者授权 |
| device_contact_seen | 每个接收设备和发送设备之间的已查看游标,只向前更新 |
| conversations、memberships | 会话与成员关系,记录角色和生效世代 |
| devices、device_key_packages | 公开设备凭据及签名的一次性密钥包,事务领取,撤销后停止发放 |
| device_envelopes | 二进制协议封包、投递游标和目标设备,按发送设备、接收设备和客户端消息 ID 幂等 |
+6
View File
@@ -210,3 +210,9 @@ Windows 和 Web 的账号侧栏提供本机通知开关,默认关闭。窗口
私聊新增应用内提醒,点击进入相应会话。Windows 和 Web 复用原设备系统通知开关,启用后后台通知只显示 XHChat 和通用消息提示。私聊和联系人页均可切换免打扰,账号内同步设置。静音、重试和 MLS 会话初始化仍可触发密文补拉,当前客户端对已读回执、编辑和撤回请求静默投递。
Windows Electron 与 Edge 实测通知 API 调用、提醒跳转及免打扰后的同步。接口测试覆盖对方不可见设置、备注与分组保留、欢迎封包和重复提交只提示补拉,以及解除免打扰后恢复提醒。
## 私聊会话置顶和设备未读
置顶会话排在普通会话之前,设置随账号同步。会话列表取当前设备的未读投递,包含免打扰联系人。设备在前台打开已验证的会话后,客户端提交本次已处理的游标。按接收设备和发送设备分别存储游标,已读回执仍由用户独立控制。升级前的投递保留原有历史,从升级后的新增消息开始计数。
接口测试验证同账号设备的计数隔离、游标权限、撤销后拒绝提交以及旧游标重试。Windows 与 Edge 验证置顶隔离、静音未读提示和会话查看后清除。
+12 -7
View File
@@ -17,6 +17,7 @@ type Contact struct {
Alias string `json:"alias"`
Category string `json:"category"`
Muted bool `json:"muted"`
Pinned bool `json:"pinned"`
}
type Store struct{ db *pgxpool.Pool }
@@ -30,7 +31,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.muted,false)
COALESCE(p.alias,''), COALESCE(p.category,''), COALESCE(p.muted,false), COALESCE(p.pinned,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)
@@ -43,7 +44,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, &c.Muted)
Scan(&c.ID, &c.Username, &c.State, &c.Alias, &c.Category, &c.Muted, &c.Pinned)
return c, err
}
@@ -58,7 +59,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, &c.Muted); err != nil {
if err := rows.Scan(&c.ID, &c.Username, &c.State, &c.Alias, &c.Category, &c.Muted, &c.Pinned); err != nil {
return nil, err
}
result = append(result, c)
@@ -148,12 +149,16 @@ func (s *Store) Change(ctx context.Context, owner, target, action, alias, catego
if err == nil && tag.RowsAffected() == 0 {
return ErrUnavailable
}
case "mute", "unmute":
case "mute", "unmute", "pin", "unpin":
column, enabled := "muted", action == "mute"
if action == "pin" || action == "unpin" {
column, enabled = "pinned", action == "pin"
}
tag, writeErr := tx.Exec(ctx, `
INSERT INTO contact_preferences(owner_id,contact_id,alias,category,muted)
INSERT INTO contact_preferences(owner_id,contact_id,alias,category,`+column+`)
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")
ON CONFLICT (owner_id,contact_id) DO UPDATE SET `+column+`=EXCLUDED.`+column,
owner, target, enabled)
err = writeErr
if err == nil && tag.RowsAffected() == 0 {
return ErrUnavailable
@@ -0,0 +1,13 @@
ALTER TABLE contact_preferences ADD COLUMN pinned boolean NOT NULL DEFAULT false;
ALTER TABLE device_envelopes ADD COLUMN counts_as_unread boolean NOT NULL DEFAULT false;
CREATE INDEX device_envelopes_unread ON device_envelopes(recipient_device, sender_device, sequence)
WHERE counts_as_unread;
CREATE TABLE device_contact_seen (
recipient_device uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
sender_device uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
sequence bigint NOT NULL CHECK (sequence > 0),
PRIMARY KEY (recipient_device, sender_device),
CHECK (recipient_device <> sender_device)
);
+4 -1
View File
@@ -46,6 +46,9 @@ var groupInviteLinkMigration string
//go:embed 013_contact_mute.sql
var contactMuteMigration string
//go:embed 014_private_conversations.sql
var privateConversationsMigration string
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx)
if err != nil {
@@ -61,7 +64,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, contactMuteMigration,
groupSeenMigration, groupInviteLinkMigration, contactMuteMigration, privateConversationsMigration,
} {
version := index + 1
var applied bool
+63
View File
@@ -0,0 +1,63 @@
package delivery
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
)
func (s *Store) Unread(ctx context.Context, recipient string) (map[string]int64, error) {
rows, err := s.db.Query(ctx, `
SELECT sender.user_id, count(*)
FROM device_envelopes e
JOIN devices sender ON sender.id=e.sender_device AND sender.revoked_at IS NULL
JOIN devices recipient ON recipient.id=e.recipient_device AND recipient.revoked_at IS NULL
JOIN contact_relationships r ON r.first_user=LEAST(sender.user_id,recipient.user_id)
AND r.second_user=GREATEST(sender.user_id,recipient.user_id) AND r.status='accepted'
LEFT JOIN device_contact_seen seen ON seen.recipient_device=e.recipient_device AND seen.sender_device=e.sender_device
WHERE e.recipient_device=$1 AND e.counts_as_unread AND e.sequence>COALESCE(seen.sequence,0)
AND e.created_at>=r.updated_at
GROUP BY sender.user_id
`, recipient)
if err != nil {
return nil, err
}
defer rows.Close()
counts := make(map[string]int64)
for rows.Next() {
var user string
var count int64
if err := rows.Scan(&user, &count); err != nil {
return nil, err
}
counts[user] = count
}
return counts, rows.Err()
}
func (s *Store) MarkSeen(ctx context.Context, recipient, sender string, sequence int64) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if err := authorizeDelivery(ctx, tx, sender, recipient); err != nil {
return err
}
var stored int64
err = tx.QueryRow(ctx, `
INSERT INTO device_contact_seen(recipient_device,sender_device,sequence)
SELECT recipient_device,sender_device,sequence FROM device_envelopes
WHERE recipient_device=$1 AND sender_device=$2 AND sequence=$3
ON CONFLICT (recipient_device,sender_device) DO UPDATE SET sequence=GREATEST(device_contact_seen.sequence,EXCLUDED.sequence)
RETURNING sequence
`, recipient, sender, sequence).Scan(&stored)
if errors.Is(err, pgx.ErrNoRows) {
return ErrUnavailable
}
if err != nil {
return err
}
return tx.Commit(ctx)
}
+6 -6
View File
@@ -27,7 +27,7 @@ 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, requestNotice bool) (string, bool, error) {
func (s *Store) Send(ctx context.Context, sender, recipient, message string, ciphertext []byte, countAsUnread bool) (string, bool, error) {
tx, err := s.db.Begin(ctx)
if err != nil {
return "", false, err
@@ -40,13 +40,13 @@ func (s *Store) Send(ctx context.Context, sender, recipient, message string, cip
var seq string
err = tx.QueryRow(ctx, `
INSERT INTO device_envelopes(message_id, sender_device, recipient_device, ciphertext)
VALUES ($1,$2,$3,$4)
INSERT INTO device_envelopes(message_id, sender_device, recipient_device, ciphertext, counts_as_unread)
VALUES ($1,$2,$3,$4,$5)
ON CONFLICT (sender_device, recipient_device, message_id) DO NOTHING
RETURNING sequence::text
`, message, sender, recipient, ciphertext).Scan(&seq)
`, message, sender, recipient, ciphertext, countAsUnread).Scan(&seq)
if errors.Is(err, pgx.ErrNoRows) {
requestNotice = false
countAsUnread = false
var previous []byte
err = tx.QueryRow(ctx, `
SELECT sequence::text,ciphertext FROM device_envelopes
@@ -60,7 +60,7 @@ func (s *Store) Send(ctx context.Context, sender, recipient, message string, cip
return "", false, err
}
var notify bool
if requestNotice {
if countAsUnread {
err = tx.QueryRow(ctx, `
SELECT NOT EXISTS (
SELECT 1 FROM contact_preferences p
+2
View File
@@ -52,6 +52,8 @@ func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *d
mux.HandleFunc("POST /api/v1/contacts/{id}", a.authorized(a.changeContact))
mux.HandleFunc("GET /api/v1/inbox", a.authorized(a.inbox))
mux.HandleFunc("POST /api/v1/inbox", a.authorized(a.sendEnvelope))
mux.HandleFunc("GET /api/v1/inbox/unread", a.authorized(a.privateUnread))
mux.HandleFunc("POST /api/v1/inbox/seen", a.authorized(a.markPrivateSeen))
mux.HandleFunc("GET /api/v1/contacts/{id}/devices", a.authorized(a.contactDevices))
mux.HandleFunc("POST /api/v1/contacts/{id}/devices/{device}/claim", a.authorized(a.claimPackage))
mux.HandleFunc("POST /api/v1/key-packages", a.authorized(a.publishPackage))
+3 -1
View File
@@ -78,7 +78,9 @@ 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" && input.Action != "mute" && input.Action != "unmute" {
switch input.Action {
case "preferences", "mute", "unmute", "pin", "unpin":
default:
pipe.Publish(r.Context(), "xhchat:contacts:"+strings.ToLower(target), "changed")
}
_, _ = pipe.Exec(r.Context())
+40
View File
@@ -74,3 +74,43 @@ func (a *API) inbox(w http.ResponseWriter, r *http.Request, _ string, identity a
}
respond(w, 200, items)
}
func (a *API) privateUnread(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
if !a.limit(w, r, "private-unread:"+identity.Device.ID, 180) {
return
}
counts, err := a.delivery.Unread(r.Context(), identity.Device.ID)
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, counts)
}
func (a *API) markPrivateSeen(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
var input struct {
SenderDevice string `json:"senderDevice"`
Sequence string `json:"sequence"`
}
if !parse(w, r, &input) {
return
}
sequence, err := strconv.ParseInt(input.Sequence, 10, 64)
if !uuidPattern.MatchString(input.SenderDevice) || err != nil || sequence <= 0 || strconv.FormatInt(sequence, 10) != input.Sequence {
problem(w, 400, "invalid_cursor", "无效的设备或已查看游标")
return
}
if !a.limit(w, r, "private-seen:"+identity.Device.ID, 180) {
return
}
err = a.delivery.MarkSeen(r.Context(), identity.Device.ID, strings.ToLower(input.SenderDevice), sequence)
if errors.Is(err, delivery.ErrUnavailable) {
problem(w, 404, "delivery_unavailable", "找不到当前设备可见的投递记录")
return
}
if err != nil {
unavailable(w, err)
return
}
w.WriteHeader(204)
}
+42 -10
View File
@@ -24,17 +24,21 @@ async function json(path, method, token, body, status = 200) {
return response.json()
}
async function register({ publicKey, privateKey } = generateKeyPairSync('ed25519')) {
async function authenticate(mode, username, password, { publicKey, privateKey } = generateKeyPairSync('ed25519')) {
const { challenge } = await json('/auth/challenge', 'POST')
return json('/auth/register', 'POST', null, {
username: 'qa_' + randomBytes(6).toString('hex'),
password: randomBytes(24).toString('hex'),
return json('/auth/' + mode, 'POST', null, {
username,
password,
deviceName: '投递验收设备',
platform: 'web',
challenge,
publicKey: publicKey.export({ format: 'jwk' }).x,
signature: sign(null, Buffer.from('XHChat device authentication v1\n' + challenge), privateKey).toString('base64url'),
}, 201)
}, mode === 'register' ? 201 : 200)
}
function register(keys, password = randomBytes(24).toString('hex')) {
return authenticate('register', 'qa_' + randomBytes(6).toString('hex'), password, keys)
}
async function contact(actor, target, action) {
@@ -335,14 +339,21 @@ test('群密文和实时提示只投递到名单设备,移除或撤销阻断
test('设备密文投递、幂等、离线补拉、免打扰与撤销', { timeout: 25000 }, async (t) => {
const sender = await register()
const recipient = await register()
const recipientPassword = randomBytes(24).toString('hex')
const recipient = await register(undefined, recipientPassword)
const other = await register()
const payload = { messageId: randomUUID(), recipientDevice: recipient.device.id, ciphertext: frame() }
const preferences = '/contacts/' + sender.user.id
const unread = (actor) => json('/inbox/unread', 'GET', actor.token)
const markSeen = (actor, sequence, senderDevice = sender.device.id) =>
call('/inbox/seen', 'POST', actor.token, { senderDevice, sequence })
await json('/inbox', 'POST', sender.token, payload, 404)
await json(preferences, 'POST', recipient.token, { action: 'mute' }, 409)
await json(preferences, 'POST', recipient.token, { action: 'pin' }, 409)
await contact(sender, recipient, 'request')
await contact(recipient, sender, 'accept')
const sibling = await authenticate('login', recipient.user.username, recipientPassword)
assert.notEqual(sibling.device.id, recipient.device.id)
await json('/inbox', 'POST', sender.token, { ...payload, ciphertext: Buffer.from('plaintext').toString('base64') }, 400)
await json('/inbox', 'POST', sender.token, { ...payload, text: 'plaintext' }, 400)
@@ -356,6 +367,13 @@ test('设备密文投递、幂等、离线补拉、免打扰与撤销', { timeou
assert.deepEqual(await json('/inbox?after=' + first.sequence, 'GET', recipient.token), [])
assert.deepEqual(await json('/inbox', 'GET', sender.token), [])
assert.deepEqual(await json('/inbox', 'GET', other.token), [])
assert.deepEqual(await unread(recipient), { [sender.user.id]: 1 })
assert.deepEqual(await unread(other), {})
assert.deepEqual(await unread(sibling), {})
await json('/inbox', 'POST', sender.token, { ...payload, recipientDevice: sibling.device.id })
assert.deepEqual(await unread(sibling), { [sender.user.id]: 1 })
assert.equal((await markSeen(other, first.sequence)).status, 404)
assert.equal((await markSeen(recipient, first.sequence, other.device.id)).status, 404)
const [socket, senderSocket] = await Promise.all([recipient, sender].map((actor) => watchRealtime(actor, t)))
const senderEvents = []
@@ -378,27 +396,41 @@ test('设备密文投递、幂等、离线补拉、免打扰与撤销', { timeou
await deliver(syncOnly, { ...newPayload(), silent: true })
await expectEvent(contactsChanged, () => contact(recipient, sender, 'mute'))
await expectEvent(contactsChanged, () => contact(recipient, sender, 'pin'))
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,
id: sender.user.id, username: sender.user.username, state: 'friend', alias: '朋友', category: '测试', muted: true, pinned: true,
})
assert.equal((await json('/contacts', 'GET', sender.token))[0].muted, false)
const senderView = (await json('/contacts', 'GET', sender.token))[0]
assert.deepEqual([senderView.muted, senderView.pinned], [false, false])
const siblingView = (await json('/contacts', 'GET', sibling.token))[0]
assert.deepEqual([siblingView.muted, siblingView.pinned], [true, true])
const muted = newPayload()
await deliver(syncOnly, muted)
const mutedResult = await deliver(syncOnly, muted)
assert.deepEqual(await unread(recipient), { [sender.user.id]: 3 })
assert.equal((await markSeen(recipient, result.sequence)).status, 204)
assert.equal((await markSeen(recipient, first.sequence)).status, 204)
assert.deepEqual(await unread(recipient), { [sender.user.id]: 1 })
assert.equal((await markSeen(recipient, mutedResult.sequence)).status, 204)
assert.deepEqual(await unread(recipient), {})
assert.deepEqual(await unread(sibling), { [sender.user.id]: 1 })
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, '朋友', '测试'])
assert.deepEqual([unmuted.muted, unmuted.pinned, unmuted.alias, unmuted.category], [false, true, '朋友', '测试'])
await expectEvent(contactsChanged, () => contact(recipient, sender, 'unpin'))
assert.equal((await json('/contacts', 'GET', recipient.token))[0].pinned, 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)
assert.equal((await markSeen(recipient, mutedResult.sequence)).status, 401)
await json('/inbox', 'POST', sender.token, newPayload(), 404)
})
+18
View File
@@ -99,6 +99,11 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
assert.equal(await web.getByRole('button', { name: '发送', exact: true }).count(), 0)
await trust(web, desktopCode)
await trust(windows, webCode)
const pin = web.getByRole('button', { name: '会话置顶', exact: true })
await pin.click()
await conversation.getByText('已置顶', { exact: true }).waitFor()
assert.equal(await pin.getAttribute('aria-pressed'), 'true')
assert.equal(await windows.getByRole('button', { name: '会话置顶' }).getAttribute('aria-pressed'), 'false')
const text = 'Web 到 Windows ' + randomBytes(8).toString('hex')
const packets = []
@@ -297,6 +302,12 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
await web.waitForURL(webChat)
await enable(web)
await web.getByText(webNoticeText, { exact: true }).waitFor()
await conversation.getByText('已置顶', { exact: true }).waitFor()
await pin.click()
await conversation.getByText('已置顶', { exact: true }).waitFor({ state: 'detached' })
await conversation.locator('.unread-badge').waitFor()
await web.evaluate(() => { document.hasFocus = () => true; window.dispatchEvent(new Event('focus')) })
await conversation.locator('.unread-badge').waitFor({ state: 'detached' })
await muteToggle(web).click()
await web.getByRole('button', { name: '消息免打扰', pressed: true }).waitFor()
@@ -306,9 +317,16 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
await web.getByRole('button', { name: '消息免打扰', pressed: true }).waitFor()
const mutedText = '免打扰仍能同步 ' + randomBytes(8).toString('hex')
await send(windows, mutedText)
await work(web).getByRole('link', { name: '消息', exact: true }).click()
const badge = conversation.getByRole('link', { name: new RegExp(b) }).locator('.unread-badge.muted')
await badge.waitFor()
assert.equal(await badge.locator('.unread-label').textContent(), '1 条未读')
await work(web).getByRole('link', { name: '联系人' }).click()
await web.getByRole('button', { name: new RegExp(b) }).click()
await web.getByRole('link', { name: '打开加密聊天' }).click()
await enable(web)
await web.getByText(mutedText, { exact: true }).waitFor()
await badge.waitFor({ state: 'detached' })
assert.equal(await privateNotice(web).count(), 0)
assert.equal(await web.evaluate(() => window.privateNotificationLog.length), 1)
+4 -1
View File
@@ -42,6 +42,7 @@ interface ChatState {
engine: string
cursor: string
pending: Incoming[]
received?: Record<string, string>
outbox: Outgoing[]
lines: ChatLine[]
pinned: Record<string, string>
@@ -331,6 +332,7 @@ export function setReadReceipts(identity: ChatIdentity, enabled: boolean) {
export function synchronize(identity: ChatIdentity, user: string, call: Call) {
return update(identity, async (state, save, factory) => {
const received = state.received ??= {}
const peers = await directory(call, user)
const peerIDs = new Set(peers.map((peer) => peer.id))
let backfilled = false
@@ -385,6 +387,7 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) {
} finally {
engine.free()
}
received[peer.id] = item.sequence
state.pending = state.pending.filter((pending) => pending.sequence !== item.sequence)
await save(state)
}
@@ -405,7 +408,7 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) {
engine.free()
}
}
return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError, shareRead: state.shareRead === true,
return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError, received, shareRead: state.shareRead === true,
unsent: state.outbox.map((item) => item.mutationTarget ?? item.messageId) }
})
}
+2 -1
View File
@@ -5,6 +5,7 @@ export interface Contact {
alias: string
category: string
muted: boolean
pinned: boolean
}
export type ContactAction = 'request' | 'accept' | 'reject' | 'cancel' | 'delete' | 'block' | 'unblock' | 'preferences' | 'mute' | 'unmute'
export type ContactAction = 'request' | 'accept' | 'reject' | 'cancel' | 'delete' | 'block' | 'unblock' | 'preferences' | 'mute' | 'unmute' | 'pin' | 'unpin'
+12
View File
@@ -65,6 +65,18 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so
.contact-item { display: flex; align-items: center; gap: 8px; width: 100%; text-align: left; padding: 8px; border-radius: 8px; border: 0; background: transparent; color: var(--text); overflow-wrap: anywhere; }
.contact-item[aria-pressed="true"] { background: var(--green-soft); }
.contact-item small { display: block; }
.unread-badge {
margin-inline-start: auto;
min-width: 1.5rem;
padding-inline: .35rem;
border-radius: 1rem;
background: var(--green-soft);
color: var(--green);
font-size: .8rem;
text-align: center;
}
.unread-badge.muted { background: var(--base); color: var(--muted); }
.unread-label { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.contact-detail { padding: 24px clamp(12px, 4vw, 36px); min-width: 0; overflow-wrap: anywhere; }
.contact-heading, .contact-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 18px; }
.contact-heading h1 { font-size: 22px; }
+76 -7
View File
@@ -2,6 +2,7 @@
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useSession } from '../session'
import { APIError } from '../api'
import { enableChat, localMessageAction, markRead, mutateMessage, readPrivateForward, recentConversations, send, setReadReceipts, synchronize, trust } from '../chat/chat'
import type { ChatLine } from '../chat/chat'
import { forwardContent } from '../chat/group-chat'
@@ -33,6 +34,7 @@ const error = ref('')
const busy = ref(false)
const contacts = ref<Contact[]>([])
const recent = ref<Record<string, string>>({})
const unread = ref<Record<string, number>>({})
const conversationQuery = ref('')
const history = ref<HTMLOListElement>()
const shareRead = ref(false)
@@ -47,7 +49,7 @@ const conversations = computed(() => {
const query = conversationQuery.value.trim().toLowerCase()
return contacts.value.filter((item) => item.state === 'friend' &&
[item.alias, item.username].some((value) => value.toLowerCase().includes(query)))
.sort((a, b) => (recent.value[b.id] ?? '').localeCompare(recent.value[a.id] ?? '') ||
.sort((a, b) => Number(b.pinned) - Number(a.pinned) || (recent.value[b.id] ?? '').localeCompare(recent.value[a.id] ?? '') ||
(a.alias || a.username).localeCompare(b.alias || b.username))
})
const lines = computed(() => {
@@ -58,13 +60,21 @@ const lines = computed(() => {
})
let timer: ReturnType<typeof setInterval>
let receiptTimer: ReturnType<typeof setTimeout> | undefined
let seenTimer: ReturnType<typeof setTimeout> | undefined
let unreadTimer: ReturnType<typeof setTimeout> | undefined
let unreadVersion = 0
let conversationVersion = 0
let markingSeen = false
let active = true
const seen = new Map<string, string>()
async function loadConversations() {
const identity = session.identity
if (!identity) return
const version = ++conversationVersion
try {
const [people, dates] = await Promise.all([session.contacts(), recentConversations(identity)])
if (session.identity?.device.id !== identity.device.id) return
if (version !== conversationVersion || session.identity?.device.id !== identity.device.id) return
contacts.value = people
recent.value = dates
} catch (cause) {
@@ -72,6 +82,43 @@ async function loadConversations() {
}
}
function queueUnread() {
if (!active) return
clearTimeout(unreadTimer)
const version = ++unreadVersion
unreadTimer = setTimeout(async () => {
try {
const counts = await session.authorized<Record<string, number>>('/inbox/unread')
if (version === unreadVersion) unread.value = counts
} catch {
// Retain the latest badges while the service is unavailable.
}
}, 200)
}
function queueSeen() {
if (!active) return
clearTimeout(seenTimer)
seenTimer = setTimeout(async () => {
const device = peer.value?.id
const sequence = device && view.value?.received[device]
if (!device || !sequence || !trusted.value || markingSeen || seen.get(device) === sequence ||
document.visibilityState !== 'visible' || !document.hasFocus()) return
markingSeen = true
try {
await session.authorized('/inbox/seen', 'POST', { senderDevice: device, sequence })
seen.set(device, sequence)
queueUnread()
queueSeen()
} catch (error) {
// The server may expire a delivery before the device reports it as seen.
if (error instanceof APIError && error.status === 404) seen.set(device, sequence)
} finally {
markingSeen = false
}
}, 200)
}
async function execute(action: () => Promise<void>) {
if (busy.value || !session.identity) return
busy.value = true
@@ -100,13 +147,15 @@ async function refresh() {
}
}
if (!current.peers.some((device) => device.id === selected.value)) selected.value = current.peers[0]?.id ?? ''
queueSeen()
}
function toggleMute() {
function togglePreference(preference: 'mute' | 'pin') {
const contact = activeContact.value
if (!contact) return
const enabled = preference === 'mute' ? contact.muted : contact.pinned
void execute(async () => {
await session.changeContact(contact.id, contact.muted ? 'unmute' : 'mute')
await session.changeContact(contact.id, enabled ? `un${preference}` : preference)
await loadConversations()
})
}
@@ -275,21 +324,32 @@ watch(selected, () => {
pendingFile.value = undefined
draft.value = ''
scheduleReceipt()
queueSeen()
})
watch(() => [session.inboxChanges, session.contactChanges, session.connection], sync)
watch(() => [session.inboxChanges, session.contactChanges, session.connection], queueUnread)
watch(() => [session.contactChanges, session.connection], () => void loadConversations())
watch([search, favoritesOnly], scheduleReceipt)
onMounted(() => {
void loadConversations()
timer = setInterval(sync, 10_000)
queueUnread()
timer = setInterval(() => { sync(); queueUnread() }, 10_000)
window.addEventListener('focus', scheduleReceipt)
window.addEventListener('focus', queueSeen)
document.addEventListener('visibilitychange', scheduleReceipt)
document.addEventListener('visibilitychange', queueSeen)
})
onBeforeUnmount(() => {
active = false
clearInterval(timer)
clearTimeout(receiptTimer)
clearTimeout(seenTimer)
clearTimeout(unreadTimer)
unreadVersion++
window.removeEventListener('focus', scheduleReceipt)
window.removeEventListener('focus', queueSeen)
document.removeEventListener('visibilitychange', scheduleReceipt)
document.removeEventListener('visibilitychange', queueSeen)
})
</script>
@@ -298,7 +358,9 @@ onBeforeUnmount(() => {
<header class="page-header">
<h1>加密聊天</h1>
<button v-if="activeContact" type="button" class="plain" :aria-pressed="activeContact.muted" :disabled="busy"
@click="toggleMute">消息免打扰</button>
@click="togglePreference('mute')">消息免打扰</button>
<button v-if="activeContact" type="button" class="plain" :aria-pressed="activeContact.pinned" :disabled="busy"
@click="togglePreference('pin')">会话置顶</button>
<button v-if="ownCode" class="plain" :disabled="busy" @click="sync">刷新</button>
</header>
<div class="conversation-layout">
@@ -306,7 +368,14 @@ onBeforeUnmount(() => {
<label>查找会话<input v-model="conversationQuery" type="search" maxlength="120"></label>
<RouterLink v-for="contact in conversations" :key="contact.id" class="contact-item" :to="'/chat/' + contact.id">
<span class="avatar" aria-hidden="true">{{ contact.username[0]?.toUpperCase() }}</span>
<span><strong>{{ contact.alias || contact.username }}</strong><small v-if="recent[contact.id]">{{ new Date(recent[contact.id]).toLocaleDateString('zh-CN') }}</small></span>
<span><strong>{{ contact.alias || contact.username }}</strong>
<small v-if="contact.pinned">已置顶</small>
<small v-if="recent[contact.id]">{{ new Date(recent[contact.id]).toLocaleDateString('zh-CN') }}</small>
</span>
<span v-if="unread[contact.id]" class="unread-badge" :class="{ muted: contact.muted }">
<span aria-hidden="true">{{ unread[contact.id]! >= 100 ? '99+' : unread[contact.id] }}</span>
<span class="unread-label">{{ unread[contact.id]! >= 100 ? '99 条以上未读' : unread[contact.id] + ' 条未读' }}</span>
</span>
</RouterLink>
<p v-if="!conversations.length" class="muted">{{ conversationQuery ? '没有匹配的会话。' : '添加好友后可开始聊天。' }}</p>
</aside>
+1 -16
View File
@@ -182,7 +182,7 @@ onBeforeUnmount(() => {
<strong>{{ group.name }}</strong>
<small>{{ group.state === 'invited' ? '待接受邀请' : roles[group.role] }}<template v-if="group.pinned"> · 已置顶</template><template v-if="group.muted"> · 免打扰</template></small>
</span>
<span v-if="group.unread" class="group-unread" :class="{ muted: group.muted }">
<span v-if="group.unread" class="unread-badge" :class="{ muted: group.muted }">
<span aria-hidden="true">{{ group.unread >= 100 ? '99+' : group.unread }}</span>
<span class="unread-label">{{ group.unread >= 100 ? '99 条以上未读' : group.unread + ' 条未读' }}</span>
</span>
@@ -252,18 +252,3 @@ onBeforeUnmount(() => {
</div>
</section>
</template>
<style scoped>
.group-unread {
margin-inline-start: auto;
min-width: 1.5rem;
padding-inline: .35rem;
border-radius: 1rem;
background: var(--green-soft);
color: var(--green);
font-size: .8rem;
text-align: center;
}
.group-unread.muted { background: var(--base); color: var(--muted); }
.unread-label { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
</style>