增加群聊置顶、免打扰和应用内提醒 #33

Merged
xhgit merged 3 commits from xhgit/group-preferences into main 2026-11-15 17:05:15 +08:00
21 changed files with 412 additions and 60 deletions

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@
| 账号与设备 | Windows 和 Web 共用账号,支持用户名注册、登录、查看设备和远程撤销。 | | 账号与设备 | Windows 和 Web 共用账号,支持用户名注册、登录、查看设备和远程撤销。 |
| 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 | | 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 |
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 | | 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
| 加密群聊 | 创建群组、邀请联系人和管理成员。每个账号选一台已核验设备参与 MLS 加密文字聊天。 | | 加密群聊 | 创建群组、邀请联系人和管理成员。群列表显示本机未读,并按账号同步置顶和免打扰。每个账号选一台已核验设备参与 MLS 加密文字聊天。 |
| 加密附件 | 两端可在私聊和群聊发送、下载最多 8 MiB 的文件,并在本机预览图片和视频。 | | 加密附件 | 两端可在私聊和群聊发送、下载最多 8 MiB 的文件,并在本机预览图片和视频。 |
| 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 | | 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 |
| 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索和收藏。消息可转发到已建立加密会话的群或已核验的联系人设备。私聊支持可选加密已读回执。 | | 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索和收藏。消息可转发到已建立加密会话的群或已核验的联系人设备。私聊支持可选加密已读回执。 |
+7 -1
View File
@@ -28,6 +28,8 @@
| GET | /api/v1/attachments/{id} | 原发送或接收设备获取附件密文 | | GET | /api/v1/attachments/{id} | 原发送或接收设备获取附件密文 |
| GET / POST | /api/v1/groups | 列出当前账号所属群组与邀请,或创建群组 | | GET / POST | /api/v1/groups | 列出当前账号所属群组与邀请,或创建群组 |
| GET / POST | /api/v1/groups/{id} | 查看群组详情或执行邀请、接受、拒绝、改名、升降管理员、移除、退出或解散 | | GET / POST | /api/v1/groups/{id} | 查看群组详情或执行邀请、接受、拒绝、改名、升降管理员、移除、退出或解散 |
| POST | /api/v1/groups/{id}/preferences | 更新当前账号的 `pinned` 和 `muted`,可只传其中一项 |
| POST | /api/v1/groups/{id}/seen | 提交当前设备已同步的消息游标 `sequence`,成功返回 204 |
| GET | /api/v1/groups/{id}/devices | 获取群成员的有效设备与 MLS 公钥 | | GET | /api/v1/groups/{id}/devices | 获取群成员的有效设备与 MLS 公钥 |
| POST | /api/v1/groups/{id}/devices/{device}/claim | 群主一次性领取群成员设备的 KeyPackage | | POST | /api/v1/groups/{id}/devices/{device}/claim | 群主一次性领取群成员设备的 KeyPackage |
| GET / POST | /api/v1/groups/{id}/epochs | 读取当前设备可访问的会话信息或由群主发布新世代 | | GET / POST | /api/v1/groups/{id}/epochs | 读取当前设备可访问的会话信息或由群主发布新世代 |
@@ -54,7 +56,11 @@ MLS 凭据由标准 Base64 的 publicKey 和 signature 组成,使用 UTF-8 前
群组密文投递使用 `/groups/{id}/epochs` 和 `/groups/{id}/messages`。群主发布带 membershipVersion 的世代,选取每个有效成员的一台已登记 MLS 设备,提交其他设备的 Welcome。GET epochs 返回当前有效世代的设备名单和本设备获准接收的 Welcome,旧世代仅向在本次成员资格期间加入过该世代的设备返回。POST messages 接受当前世代的 MLS PrivateMessage,GET messages 通过 after 游标返回本设备有权读取的密文。 群组密文投递使用 `/groups/{id}/epochs` 和 `/groups/{id}/messages`。群主发布带 membershipVersion 的世代,选取每个有效成员的一台已登记 MLS 设备,提交其他设备的 Welcome。GET epochs 返回当前有效世代的设备名单和本设备获准接收的 Welcome,旧世代仅向在本次成员资格期间加入过该世代的设备返回。POST messages 接受当前世代的 MLS PrivateMessage,GET messages 通过 after 游标返回本设备有权读取的密文。
群世代和密文提交后,WebSocket 向该世代的设备发送 `group_changed`,事件只包含 `type` 和 `groupId`。客户端收到提示、重连或到达兜底轮询周期时,按持久化的游标向授权接口补拉。提示由 Redis 尽力送达,数据库保存投递记录。 群世代和密文提交后,WebSocket 向该世代的设备发送 `group_changed`,包含 `type` 和 `groupId`。新投递给其他设备的密文在该账号未开启免打扰时附带 `notify: true`。客户端收到提示、重连或到达兜底轮询周期时,按持久化的游标向授权接口补拉。提示由 Redis 尽力送达,数据库保存投递记录。
群列表和详情返回当前账号的 `pinned` 和 `muted`。群列表先排序置顶群,随后按创建时间排序。设置修改后,同一账号的在线设备收到刷新提示。离开群组或被移除后,当前成员资格的设置随之清除。
群列表同时返回当前设备的 `unread`,上限为 100,用于客户端显示 `99+`。统计当前成员资格内、设备获准接收且由其他设备发送的密文投递。`sequence` 是正整数字符串,须指向当前设备在该群有权读取的消息,更新不会回退游标。成员列表和其他账号的 API 响应不包含该设备的查看状态。
有效成员可通过 `GET /groups/{id}/devices` 获取群内有效设备凭据。群主通过 `POST /groups/{id}/devices/{device}/claim` 一次性领取其他有效成员的设备密钥包。邀请待接受的账号、已离群的账号和撤销设备无法访问群设备目录。 有效成员可通过 `GET /groups/{id}/devices` 获取群内有效设备凭据。群主通过 `POST /groups/{id}/devices/{device}/claim` 一次性领取其他有效成员的设备密钥包。邀请待接受的账号、已离群的账号和撤销设备无法访问群设备目录。
+12
View File
@@ -156,3 +156,15 @@ Windows 和 Web 的私聊与群聊共用转发目标选择。私聊支持把文
群成员、邀请与群资料更新事务提交后,受影响账号的在线设备收到刷新提示。提示只含事件类型。群组页合并提示,通过现有授权接口刷新列表和当前群详情,重连时也会刷新,并保留 15 秒兜底轮询。群成员权限仍取决于服务端的实时授权结果。 群成员、邀请与群资料更新事务提交后,受影响账号的在线设备收到刷新提示。提示只含事件类型。群组页合并提示,通过现有授权接口刷新列表和当前群详情,重连时也会刷新,并保留 15 秒兜底轮询。群成员权限仍取决于服务端的实时授权结果。
Windows Electron 和 Edge 验证了群组页在兜底轮询前显示邀请、成员接受和成员移除。服务端测试验证普通成员收不到其他人的待处理邀请提示,未加入账号收不到群事件,解散会通知仍待接受邀请的账号。 Windows Electron 和 Edge 验证了群组页在兜底轮询前显示邀请、成员接受和成员移除。服务端测试验证普通成员收不到其他人的待处理邀请提示,未加入账号收不到群事件,解散会通知仍待接受邀请的账号。
## 群置顶和免打扰
两端可按账号设置群置顶和免打扰,置顶群排在群列表前面。离开群页面时,未静音的新群投递可显示通用的应用内提醒,点击返回群组。免打扰保留 WebSocket 补拉提示,省略应用内提醒标记。原生系统通知和 Web Push 仍待实现。
测试覆盖迁移 010、邀请者和外部账号不可修改群设置、不同账号的设置隔离、双端静音收取和提醒入口,以及同一账号的两台设备实时同步偏好。
## 群聊未读角标
Windows 和 Web 的群列表按当前设备显示未读投递数量,免打扰群使用低强调角标。打开可见的群聊并同步后,客户端提交本机游标。统计排除本机发送的消息,页面后台时保留角标。游标由服务端按设备保存,其他成员看不到逐条已读状态。编辑和撤回也是群密文投递,会计入尚未同步的数量。
接口测试覆盖发送设备排除、游标单调递增、越权及重新入群隔离。Windows Electron 与 Edge 验证免打扰时显示未读、启用群安全会话后同步并清除角标,以及群消息和私聊附件回归。私聊文件选择在同步繁忙时也会排队提交。
@@ -0,0 +1,4 @@
ALTER TABLE group_members
ADD COLUMN pinned boolean NOT NULL DEFAULT false,
ADD COLUMN muted boolean NOT NULL DEFAULT false,
ADD CHECK (state = 'active' OR (NOT pinned AND NOT muted));
@@ -0,0 +1,9 @@
CREATE TABLE group_seen (
group_id uuid NOT NULL,
user_id uuid NOT NULL,
device_id uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
sequence bigint NOT NULL CHECK (sequence > 0),
PRIMARY KEY (group_id,device_id),
FOREIGN KEY (group_id,user_id) REFERENCES group_members(group_id,user_id) ON DELETE CASCADE
);
CREATE INDEX group_seen_membership ON group_seen(group_id,user_id);
+8 -1
View File
@@ -34,6 +34,12 @@ var groupTransportMigration string
//go:embed 009_group_attachments.sql //go:embed 009_group_attachments.sql
var groupAttachmentsMigration string var groupAttachmentsMigration string
//go:embed 010_group_preferences.sql
var groupPreferencesMigration string
//go:embed 011_group_seen.sql
var groupSeenMigration string
func Migrate(ctx context.Context, pool *pgxpool.Pool) error { func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx) tx, err := pool.Begin(ctx)
if err != nil { if err != nil {
@@ -48,7 +54,8 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
} }
for index, migration := range []string{ for index, migration := range []string{
identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration, identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration,
attachmentsMigration, groupsMigration, groupTransportMigration, groupAttachmentsMigration, attachmentsMigration, groupsMigration, groupTransportMigration, groupAttachmentsMigration, groupPreferencesMigration,
groupSeenMigration,
} { } {
version := index + 1 version := index + 1
var applied bool var applied bool
+38
View File
@@ -0,0 +1,38 @@
package groups
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
)
func (s *Store) MarkSeen(ctx context.Context, group, user, device string, sequence int64) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if _, _, err := lockTransport(ctx, tx, group, user, device); err != nil {
return err
}
var seen int64
err = tx.QueryRow(ctx, `
INSERT INTO group_seen(group_id,user_id,device_id,sequence)
SELECT m.group_id,m.user_id,d.id,x.sequence FROM group_messages x
JOIN group_epoch_devices e ON (e.group_id,e.epoch_id)=(x.group_id,x.epoch_id) AND e.device_id=$3
JOIN group_epochs epoch ON (epoch.group_id,epoch.id)=(x.group_id,x.epoch_id)
JOIN group_members m ON m.group_id=x.group_id AND m.user_id=$2 AND m.state='active'
JOIN devices d ON d.id=e.device_id AND d.user_id=m.user_id AND d.revoked_at IS NULL
WHERE x.group_id=$1 AND x.sequence=$4 AND epoch.membership_version>=m.joined_version
ON CONFLICT (group_id,device_id) DO UPDATE SET sequence=GREATEST(group_seen.sequence,EXCLUDED.sequence)
RETURNING sequence
`, group, user, device, sequence).Scan(&seen)
if errors.Is(err, pgx.ErrNoRows) {
return ErrUnavailable
}
if err != nil {
return err
}
return tx.Commit(ctx)
}
+49 -8
View File
@@ -18,6 +18,17 @@ type Group struct {
State string `json:"state"` State string `json:"state"`
Role string `json:"role"` Role string `json:"role"`
Version string `json:"membershipVersion"` Version string `json:"membershipVersion"`
Preferences
}
type ListedGroup struct {
Group
Unread int `json:"unread"`
}
type Preferences struct {
Pinned bool `json:"pinned"`
Muted bool `json:"muted"`
} }
type Member struct { type Member struct {
@@ -52,21 +63,31 @@ func (s *Store) Create(ctx context.Context, owner, name string) (Group, error) {
return result, err return result, err
} }
const groupColumns = `g.id,g.name,m.state,CASE WHEN g.owner_id=m.user_id THEN 'owner' ELSE m.role END,g.membership_version::text,m.pinned,m.muted`
const groupRows = ` const groupRows = `
SELECT g.id,g.name,m.state,CASE WHEN g.owner_id=m.user_id THEN 'owner' ELSE m.role END,g.membership_version::text
FROM chat_groups g JOIN group_members m ON m.group_id=g.id WHERE m.user_id=$1 FROM chat_groups g JOIN group_members m ON m.group_id=g.id WHERE m.user_id=$1
` `
func (s *Store) List(ctx context.Context, user string) ([]Group, error) { func (s *Store) List(ctx context.Context, user, device string) ([]ListedGroup, error) {
rows, err := s.db.Query(ctx, groupRows+" ORDER BY g.created_at DESC, g.id LIMIT 200", user) rows, err := s.db.Query(ctx, "SELECT "+groupColumns+`, (
SELECT count(*) FROM (
SELECT 1 FROM group_messages x
JOIN group_epoch_devices enrolled ON (enrolled.group_id,enrolled.epoch_id)=(x.group_id,x.epoch_id) AND enrolled.device_id=$2
JOIN group_epochs epoch ON (epoch.group_id,epoch.id)=(x.group_id,x.epoch_id)
JOIN devices d ON d.id=enrolled.device_id AND d.revoked_at IS NULL
WHERE x.group_id=g.id AND epoch.membership_version>=m.joined_version AND x.sender_device<>$2
AND x.sequence>COALESCE((SELECT seen.sequence FROM group_seen seen WHERE seen.group_id=g.id AND seen.device_id=$2),0)
ORDER BY x.sequence LIMIT 100
) AS unread
)`+groupRows+" ORDER BY m.pinned DESC, g.created_at DESC, g.id LIMIT 200", user, device)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close()
result := make([]Group, 0) result := make([]ListedGroup, 0)
for rows.Next() { for rows.Next() {
var g Group var g ListedGroup
if err := rows.Scan(&g.ID, &g.Name, &g.State, &g.Role, &g.Version); err != nil { if err := rows.Scan(&g.ID, &g.Name, &g.State, &g.Role, &g.Version, &g.Pinned, &g.Muted, &g.Unread); err != nil {
return nil, err return nil, err
} }
result = append(result, g) result = append(result, g)
@@ -81,8 +102,8 @@ func (s *Store) Detail(ctx context.Context, user, id string) (Detail, error) {
return result, err return result, err
} }
defer tx.Rollback(ctx) defer tx.Rollback(ctx)
err = tx.QueryRow(ctx, groupRows+" AND g.id=$2", user, id). err = tx.QueryRow(ctx, "SELECT "+groupColumns+" "+groupRows+" AND g.id=$2", user, id).
Scan(&result.ID, &result.Name, &result.State, &result.Role, &result.Version) Scan(&result.ID, &result.Name, &result.State, &result.Role, &result.Version, &result.Pinned, &result.Muted)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return result, ErrUnavailable return result, ErrUnavailable
} }
@@ -115,6 +136,26 @@ func (s *Store) Detail(ctx context.Context, user, id string) (Detail, error) {
return result, tx.Commit(ctx) return result, tx.Commit(ctx)
} }
func (s *Store) SetPreferences(ctx context.Context, id, user, device string, pinned, muted *bool) (Preferences, error) {
var result Preferences
tx, err := s.db.Begin(ctx)
if err != nil {
return result, err
}
defer tx.Rollback(ctx)
if _, _, err := lockTransport(ctx, tx, id, user, device); err != nil {
return result, err
}
err = tx.QueryRow(ctx, `
UPDATE group_members SET pinned=COALESCE($3,pinned), muted=COALESCE($4,muted)
WHERE group_id=$1 AND user_id=$2 AND state='active' RETURNING pinned,muted
`, id, user, pinned, muted).Scan(&result.Pinned, &result.Muted)
if err != nil {
return result, err
}
return result, tx.Commit(ctx)
}
func (s *Store) Change(ctx context.Context, user, id string, change Change) ([]string, error) { func (s *Store) Change(ctx context.Context, user, id string, change Change) ([]string, error) {
tx, err := s.db.Begin(ctx) tx, err := s.db.Begin(ctx)
if err != nil { if err != nil {
+21 -14
View File
@@ -150,7 +150,12 @@ func retryEpoch(ctx context.Context, tx pgx.Tx, group, sender string, input Epoc
return tx.Commit(ctx) return tx.Commit(ctx)
} }
func lockSendingEpoch(ctx context.Context, tx pgx.Tx, group, user, device, epoch string) ([]string, error) { type EpochDevice struct {
ID string
Muted bool
}
func lockSendingEpoch(ctx context.Context, tx pgx.Tx, group, user, device, epoch string) ([]EpochDevice, error) {
version, _, err := lockTransport(ctx, tx, group, user, device) version, _, err := lockTransport(ctx, tx, group, user, device)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -171,37 +176,38 @@ func lockSendingEpoch(ctx context.Context, tx pgx.Tx, group, user, device, epoch
// Match the device revocation transaction's row lock. Once a bound device is // Match the device revocation transaction's row lock. Once a bound device is
// revoked the generation cannot accept any further application ciphertext. // revoked the generation cannot accept any further application ciphertext.
rows, err := tx.Query(ctx, ` rows, err := tx.Query(ctx, `
SELECT d.id,d.revoked_at IS NULL FROM group_epoch_devices e JOIN devices d ON d.id=e.device_id SELECT d.id,d.revoked_at IS NULL,m.muted FROM group_epoch_devices e JOIN devices d ON d.id=e.device_id
JOIN group_members m ON m.group_id=e.group_id AND m.user_id=d.user_id AND m.state='active'
WHERE e.group_id=$1 AND e.epoch_id=$2 ORDER BY d.id FOR UPDATE OF d WHERE e.group_id=$1 AND e.epoch_id=$2 ORDER BY d.id FOR UPDATE OF d
`, group, epoch) `, group, epoch)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close()
devices := make([]string, 0, 32) devices := make([]EpochDevice, 0, 32)
for rows.Next() { for rows.Next() {
var id string var member EpochDevice
var active bool var active bool
if err = rows.Scan(&id, &active); err != nil { if err = rows.Scan(&member.ID, &active, &member.Muted); err != nil {
return nil, err return nil, err
} }
if !active { if !active {
return nil, ErrVersion return nil, ErrVersion
} }
devices = append(devices, id) devices = append(devices, member)
} }
return devices, rows.Err() return devices, rows.Err()
} }
func (s *Store) Send(ctx context.Context, group, user, device string, message Message) (string, []string, error) { func (s *Store) Send(ctx context.Context, group, user, device string, message Message) (string, []EpochDevice, bool, error) {
tx, err := s.db.Begin(ctx) tx, err := s.db.Begin(ctx)
if err != nil { if err != nil {
return "", nil, err return "", nil, false, err
} }
defer tx.Rollback(ctx) defer tx.Rollback(ctx)
devices, err := lockSendingEpoch(ctx, tx, group, user, device, message.Epoch) devices, err := lockSendingEpoch(ctx, tx, group, user, device, message.Epoch)
if err != nil { if err != nil {
return "", nil, err return "", nil, false, err
} }
if message.AttachmentID != nil { if message.AttachmentID != nil {
var found string var found string
@@ -209,10 +215,10 @@ func (s *Store) Send(ctx context.Context, group, user, device string, message Me
SELECT id FROM group_attachments WHERE group_id=$1 AND epoch_id=$2 AND sender_device=$3 AND id=$4 FOR KEY SHARE SELECT id FROM group_attachments WHERE group_id=$1 AND epoch_id=$2 AND sender_device=$3 AND id=$4 FOR KEY SHARE
`, group, message.Epoch, device, message.AttachmentID).Scan(&found) `, group, message.Epoch, device, message.AttachmentID).Scan(&found)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return "", nil, ErrAttachment return "", nil, false, ErrAttachment
} }
if err != nil { if err != nil {
return "", nil, err return "", nil, false, err
} }
} }
@@ -221,6 +227,7 @@ func (s *Store) Send(ctx context.Context, group, user, device string, message Me
INSERT INTO group_messages(group_id,epoch_id,sender_device,message_id,ciphertext,attachment_id) INSERT INTO group_messages(group_id,epoch_id,sender_device,message_id,ciphertext,attachment_id)
VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT DO NOTHING RETURNING sequence::text VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT DO NOTHING RETURNING sequence::text
`, group, message.Epoch, device, message.ID, message.Wire, message.AttachmentID).Scan(&sequence) `, group, message.Epoch, device, message.ID, message.Wire, message.AttachmentID).Scan(&sequence)
created := err == nil
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
var same bool var same bool
err = tx.QueryRow(ctx, ` err = tx.QueryRow(ctx, `
@@ -228,13 +235,13 @@ func (s *Store) Send(ctx context.Context, group, user, device string, message Me
WHERE group_id=$1 AND epoch_id=$2 AND sender_device=$3 AND message_id=$4 WHERE group_id=$1 AND epoch_id=$2 AND sender_device=$3 AND message_id=$4
`, group, message.Epoch, device, message.ID, message.Wire, message.AttachmentID).Scan(&sequence, &same) `, group, message.Epoch, device, message.ID, message.Wire, message.AttachmentID).Scan(&sequence, &same)
if errors.Is(err, pgx.ErrNoRows) || err == nil && !same { if errors.Is(err, pgx.ErrNoRows) || err == nil && !same {
return "", nil, ErrVersion return "", nil, false, ErrVersion
} }
} }
if err != nil { if err != nil {
return "", nil, err return "", nil, false, err
} }
return sequence, devices, tx.Commit(ctx) return sequence, devices, created, tx.Commit(ctx)
} }
func (s *Store) Inbox(ctx context.Context, group, user, device string, after int64) ([]Message, error) { func (s *Store) Inbox(ctx context.Context, group, user, device string, after int64) ([]Message, error) {
+2
View File
@@ -64,6 +64,8 @@ func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *d
mux.HandleFunc("POST /api/v1/groups", a.authorized(a.createGroup)) mux.HandleFunc("POST /api/v1/groups", a.authorized(a.createGroup))
mux.HandleFunc("GET /api/v1/groups/{id}", a.authorized(a.groupDetail)) mux.HandleFunc("GET /api/v1/groups/{id}", a.authorized(a.groupDetail))
mux.HandleFunc("POST /api/v1/groups/{id}", a.authorized(a.changeGroup)) mux.HandleFunc("POST /api/v1/groups/{id}", a.authorized(a.changeGroup))
mux.HandleFunc("POST /api/v1/groups/{id}/preferences", a.authorized(a.setGroupPreferences))
mux.HandleFunc("POST /api/v1/groups/{id}/seen", a.authorized(a.markGroupSeen))
mux.HandleFunc("GET /api/v1/groups/{id}/epochs", a.authorized(a.groupEpochs)) mux.HandleFunc("GET /api/v1/groups/{id}/epochs", a.authorized(a.groupEpochs))
mux.HandleFunc("POST /api/v1/groups/{id}/epochs", a.authorized(a.publishGroupEpoch)) mux.HandleFunc("POST /api/v1/groups/{id}/epochs", a.authorized(a.publishGroupEpoch))
mux.HandleFunc("GET /api/v1/groups/{id}/messages", a.authorized(a.groupInbox)) mux.HandleFunc("GET /api/v1/groups/{id}/messages", a.authorized(a.groupInbox))
+39 -7
View File
@@ -97,11 +97,11 @@ func (a *API) publishGroupEpoch(w http.ResponseWriter, r *http.Request, _ string
groupError(w, err) groupError(w, err)
return return
} }
devices := make([]string, 0, len(input.Devices)) devices := make([]groups.EpochDevice, 0, len(input.Devices))
for _, device := range input.Devices { for _, device := range input.Devices {
devices = append(devices, device.Device) devices = append(devices, groups.EpochDevice{ID: device.Device})
} }
a.hintGroup(r.Context(), id, devices) a.hintGroup(r.Context(), id, devices, "", false)
w.WriteHeader(204) w.WriteHeader(204)
} }
@@ -129,21 +129,26 @@ func (a *API) sendGroupMessage(w http.ResponseWriter, r *http.Request, _ string,
return return
} }
message := groups.Message{ID: input.ID, Epoch: input.Epoch, Wire: input.Wire, AttachmentID: input.AttachmentID} message := groups.Message{ID: input.ID, Epoch: input.Epoch, Wire: input.Wire, AttachmentID: input.AttachmentID}
sequence, devices, err := a.groups.Send(r.Context(), id, actor.User.ID, actor.Device.ID, message) sequence, devices, created, err := a.groups.Send(r.Context(), id, actor.User.ID, actor.Device.ID, message)
if err != nil { if err != nil {
groupError(w, err) groupError(w, err)
return return
} }
a.hintGroup(r.Context(), id, devices) a.hintGroup(r.Context(), id, devices, actor.Device.ID, created)
respond(w, 200, map[string]string{"sequence": sequence}) respond(w, 200, map[string]string{"sequence": sequence})
} }
func (a *API) hintGroup(ctx context.Context, group string, devices []string) { func (a *API) hintGroup(ctx context.Context, group string, devices []groups.EpochDevice, sender string, newMessage bool) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 250*time.Millisecond) ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 250*time.Millisecond)
defer cancel() defer cancel()
pipe := a.redis.Pipeline() pipe := a.redis.Pipeline()
group = strings.ToLower(group)
for _, device := range devices { for _, device := range devices {
pipe.Publish(ctx, "xhchat:inbox:"+device, "group:"+strings.ToLower(group)) prefix := "group:"
if newMessage && !device.Muted && sender != device.ID {
prefix = "group-notify:"
}
pipe.Publish(ctx, "xhchat:inbox:"+device.ID, prefix+group)
} }
// Hints are best effort. The durable cursor is also polled by clients. // Hints are best effort. The durable cursor is also polled by clients.
_, _ = pipe.Exec(ctx) _, _ = pipe.Exec(ctx)
@@ -178,3 +183,30 @@ func (a *API) groupInbox(w http.ResponseWriter, r *http.Request, _ string, actor
} }
respond(w, 200, items) respond(w, 200, items)
} }
func (a *API) markGroupSeen(w http.ResponseWriter, r *http.Request, _ string, actor account.Identity) {
group := r.PathValue("id")
if !uuidPattern.MatchString(group) {
groupError(w, groups.ErrUnavailable)
return
}
var input struct {
Sequence string `json:"sequence"`
}
if !parse(w, r, &input) {
return
}
sequence, err := strconv.ParseInt(input.Sequence, 10, 64)
if err != nil || sequence <= 0 || strconv.FormatInt(sequence, 10) != input.Sequence {
problem(w, 400, "invalid_cursor", "无效的已查看游标")
return
}
if !a.limit(w, r, "group-seen:"+actor.Device.ID, 240) {
return
}
if err = a.groups.MarkSeen(r.Context(), group, actor.User.ID, actor.Device.ID, sequence); err != nil {
groupError(w, err)
return
}
w.WriteHeader(204)
}
+30 -1
View File
@@ -59,7 +59,7 @@ func (a *API) createGroup(w http.ResponseWriter, r *http.Request, _ string, id a
} }
func (a *API) listGroups(w http.ResponseWriter, r *http.Request, _ string, id account.Identity) { func (a *API) listGroups(w http.ResponseWriter, r *http.Request, _ string, id account.Identity) {
result, err := a.groups.List(r.Context(), id.User.ID) result, err := a.groups.List(r.Context(), id.User.ID, id.Device.ID)
if err != nil { if err != nil {
groupError(w, err) groupError(w, err)
return return
@@ -134,3 +134,32 @@ func (a *API) hintGroupList(ctx context.Context, users []string) {
} }
_, _ = pipe.Exec(ctx) _, _ = pipe.Exec(ctx)
} }
func (a *API) setGroupPreferences(w http.ResponseWriter, r *http.Request, _ string, actor account.Identity) {
group := r.PathValue("id")
if !uuidPattern.MatchString(group) {
groupError(w, groups.ErrUnavailable)
return
}
var input struct {
Pinned *bool `json:"pinned"`
Muted *bool `json:"muted"`
}
if !parse(w, r, &input) {
return
}
if input.Pinned == nil && input.Muted == nil {
problem(w, 400, "invalid_group_preferences", "请选择要修改的群设置")
return
}
if !a.limit(w, r, "group-change:"+actor.User.ID, 60) {
return
}
result, err := a.groups.SetPreferences(r.Context(), group, actor.User.ID, actor.Device.ID, input.Pinned, input.Muted)
if err != nil {
groupError(w, err)
return
}
a.hintGroupList(r.Context(), []string{actor.User.ID})
respond(w, 200, result)
}
+6 -2
View File
@@ -103,15 +103,19 @@ func (a *API) realtime(w http.ResponseWriter, r *http.Request) {
return return
} }
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second) writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
event := map[string]string{"type": "contacts_changed"} event := map[string]any{"type": "contacts_changed"}
switch change.Channel { switch change.Channel {
case groupsChannel: case groupsChannel:
event["type"] = "group_list_changed" event["type"] = "group_list_changed"
case inboxChannel: case inboxChannel:
event["type"] = "inbox_changed" event["type"] = "inbox_changed"
if group, found := strings.CutPrefix(change.Payload, "group:"); found && uuidPattern.MatchString(group) { kind, group, _ := strings.Cut(change.Payload, ":")
if (kind == "group" || kind == "group-notify") && uuidPattern.MatchString(group) {
event["type"] = "group_changed" event["type"] = "group_changed"
event["groupId"] = group event["groupId"] = group
if kind == "group-notify" {
event["notify"] = true
}
} }
} }
err := wsjson.Write(writeCtx, conn, event) err := wsjson.Write(writeCtx, conn, event)
+40 -1
View File
@@ -62,6 +62,7 @@ test('群组邀请、授权、成员移除、版本变更与实时提示', { tim
const other = await register() const other = await register()
const group = await json('/groups', 'POST', owner.token, { name: '发布验收群' }, 201) const group = await json('/groups', 'POST', owner.token, { name: '发布验收群' }, 201)
const path = '/groups/' + group.id const path = '/groups/' + group.id
const preferences = path + '/preferences'
const act = async (actor, action, target, expected = 204, name) => { const act = async (actor, action, target, expected = 204, name) => {
const reply = await call(path, 'POST', actor.token, { action, target, name }) const reply = await call(path, 'POST', actor.token, { action, target, name })
assert.equal(reply.status, expected, await reply.text()) assert.equal(reply.status, expected, await reply.text())
@@ -81,6 +82,8 @@ test('群组邀请、授权、成员移除、版本变更与实时提示', { tim
await expectHint([ownerSocket, memberSocket], () => act(owner, 'invite', member.user.id)) await expectHint([ownerSocket, memberSocket], () => act(owner, 'invite', member.user.id))
const invitation = await json(path, 'GET', member.token) const invitation = await json(path, 'GET', member.token)
assert.equal(invitation.state, 'invited') assert.equal(invitation.state, 'invited')
await json(preferences, 'POST', member.token, { muted: true }, 404)
await json(preferences, 'POST', other.token, { pinned: true }, 404)
assert.deepEqual(invitation.members, []) assert.deepEqual(invitation.members, [])
assert.equal(invitation.membershipVersion, '1') assert.equal(invitation.membershipVersion, '1')
await expectHint([ownerSocket, memberSocket], () => act(member, 'decline')) await expectHint([ownerSocket, memberSocket], () => act(member, 'decline'))
@@ -88,6 +91,21 @@ test('群组邀请、授权、成员移除、版本变更与实时提示', { tim
await expectHint([ownerSocket, memberSocket], () => act(owner, 'invite', member.user.id)) await expectHint([ownerSocket, memberSocket], () => act(owner, 'invite', member.user.id))
await expectHint([ownerSocket, memberSocket], () => act(member, 'accept')) await expectHint([ownerSocket, memberSocket], () => act(member, 'accept'))
const active = await json(path, 'GET', member.token) const active = await json(path, 'GET', member.token)
assert.equal(active.pinned, false)
assert.equal(active.muted, false)
const preferenceHint = once(memberSocket, 'message', { signal: AbortSignal.timeout(4000) })
assert.deepEqual(await json(preferences, 'POST', member.token, { pinned: true, muted: true }), { pinned: true, muted: true })
assert.deepEqual(JSON.parse((await preferenceHint)[0]), { type: 'group_list_changed' })
const [ownView, otherView] = await Promise.all([member, owner].map((actor) => json(path, 'GET', actor.token)))
assert.deepEqual([ownView.pinned, ownView.muted, otherView.pinned, otherView.muted], [true, true, false, false])
let nextGroup
await expectHint([memberSocket], async () => {
nextGroup = await json('/groups', 'POST', member.token, { name: '较新的群' }, 201)
})
assert.deepEqual((await json('/groups', 'GET', member.token)).map((item) => item.id), [group.id, nextGroup.id])
await expectHint([memberSocket], async () => {
assert.equal((await call('/groups/' + nextGroup.id, 'POST', member.token, { action: 'disband' })).status, 204)
})
assert.equal(active.membershipVersion, '2') assert.equal(active.membershipVersion, '2')
assert.deepEqual(active.members.map((item) => item.role).sort(), ['member', 'owner']) assert.deepEqual(active.members.map((item) => item.role).sort(), ['member', 'owner'])
await act(member, 'remove', owner.user.id, 409) await act(member, 'remove', owner.user.id, 409)
@@ -182,7 +200,9 @@ test('群密文和实时提示只投递到名单设备,移除或撤销阻断
await publish(member, { ...second, devices: [{ device: member.device.id }, { device: owner.device.id, wire: welcome }] }, 409) await publish(member, { ...second, devices: [{ device: member.device.id }, { device: owner.device.id, wire: welcome }] }, 409)
const [ownerSocket, memberSocket, outsiderSocket] = await Promise.all([owner, member, outsider].map((actor) => watchRealtime(actor, t))) const [ownerSocket, memberSocket, outsiderSocket] = await Promise.all([owner, member, outsider].map((actor) => watchRealtime(actor, t)))
const outsiderEvents = [] const outsiderEvents = []
const memberEvents = []
outsiderSocket.on('message', (data) => outsiderEvents.push(JSON.parse(data))) outsiderSocket.on('message', (data) => outsiderEvents.push(JSON.parse(data)))
memberSocket.on('message', (data) => memberEvents.push(JSON.parse(data)))
const hint = { type: 'group_changed', groupId: group.id } const hint = { type: 'group_changed', groupId: group.id }
const epochHint = once(memberSocket, 'message', { signal: AbortSignal.timeout(4000) }) const epochHint = once(memberSocket, 'message', { signal: AbortSignal.timeout(4000) })
await publish(owner, second) await publish(owner, second)
@@ -196,10 +216,19 @@ test('群密文和实时提示只投递到名单设备,移除或撤销阻断
const message = { id: randomUUID(), epoch: second.id, wire: frame() } const message = { id: randomUUID(), epoch: second.id, wire: frame() }
const messageHint = once(ownerSocket, 'message', { signal: AbortSignal.timeout(4000) }) const messageHint = once(ownerSocket, 'message', { signal: AbortSignal.timeout(4000) })
const sequence = await json(path + '/messages', 'POST', member.token, message) const sequence = await json(path + '/messages', 'POST', member.token, message)
assert.deepEqual(JSON.parse((await messageHint)[0]), hint) assert.deepEqual(JSON.parse((await messageHint)[0]), { ...hint, notify: true })
assert.deepEqual(await json(path + '/messages', 'POST', member.token, message), sequence) assert.deepEqual(await json(path + '/messages', 'POST', member.token, message), sequence)
const received = await json(path + '/messages', 'GET', member.token) const received = await json(path + '/messages', 'GET', member.token)
assert.deepEqual(received.map((item) => item.wire), [message.wire]) assert.deepEqual(received.map((item) => item.wire), [message.wire])
const unread = async (actor) => (await json('/groups', 'GET', actor.token)).find((entry) => entry.id === group.id)?.unread
const seen = (actor, cursor) => call(path + '/seen', 'POST', actor.token, { sequence: cursor })
assert.equal(await unread(owner), 1)
assert.equal(await unread(member), 0)
assert.equal(await unread(outsider), undefined)
assert.equal((await seen(outsider, sequence.sequence)).status, 404)
assert.equal((await seen(member, '0')).status, 400)
await json(path + '/preferences', 'POST', member.token, { muted: true })
const attachmentId = randomUUID() const attachmentId = randomUUID()
const attachment = path + '/attachments/' + attachmentId const attachment = path + '/attachments/' + attachmentId
@@ -220,6 +249,11 @@ test('群密文和实时提示只投递到名单设备,移除或撤销阻断
await json(attachment, 'GET', member.token, undefined, 404) await json(attachment, 'GET', member.token, undefined, 404)
await json(path + '/messages', 'POST', member.token, linked, 409) await json(path + '/messages', 'POST', member.token, linked, 409)
const posted = await json(path + '/messages', 'POST', owner.token, linked) const posted = await json(path + '/messages', 'POST', owner.token, linked)
assert.equal(await unread(member), 1)
assert.equal((await seen(member, posted.sequence)).status, 204)
assert.equal((await seen(member, sequence.sequence)).status, 204)
assert.equal(await unread(member), 0)
assert.equal(await unread(owner), 1)
assert.deepEqual(await json(path + '/messages', 'POST', owner.token, linked), posted) assert.deepEqual(await json(path + '/messages', 'POST', owner.token, linked), posted)
await json(path + '/messages', 'POST', owner.token, { ...linked, id: randomUUID() }, 409) await json(path + '/messages', 'POST', owner.token, { ...linked, id: randomUUID() }, 409)
await json(path + '/messages', 'POST', owner.token, { ...linked, attachmentId: undefined }, 409) await json(path + '/messages', 'POST', owner.token, { ...linked, attachmentId: undefined }, 409)
@@ -230,11 +264,14 @@ test('群密文和实时提示只投递到名单设备,移除或撤销阻断
assert.deepEqual(Buffer.from(await download.arrayBuffer()), bytes) assert.deepEqual(Buffer.from(await download.arrayBuffer()), bytes)
await json(attachment, 'GET', outsider.token, undefined, 404) await json(attachment, 'GET', outsider.token, undefined, 404)
await change(owner, 'remove', member.user.id) await change(owner, 'remove', member.user.id)
assert.equal((await seen(member, posted.sequence)).status, 404)
await json(path + '/messages', 'GET', member.token, undefined, 404) await json(path + '/messages', 'GET', member.token, undefined, 404)
await json(attachment, 'GET', member.token, undefined, 404) await json(attachment, 'GET', member.token, undefined, 404)
await json(path + '/messages', 'POST', owner.token, { ...message, id: randomUUID() }, 409) await json(path + '/messages', 'POST', owner.token, { ...message, id: randomUUID() }, 409)
await change(owner, 'invite', member.user.id) await change(owner, 'invite', member.user.id)
await change(member, 'accept') await change(member, 'accept')
assert.equal(await unread(member), 0)
assert.equal((await seen(member, posted.sequence)).status, 404)
await json(attachment, 'GET', member.token, undefined, 404) await json(attachment, 'GET', member.token, undefined, 404)
assert.equal((await call(attachment, 'GET', owner.token)).status, 200) assert.equal((await call(attachment, 'GET', owner.token)).status, 200)
assert.deepEqual(await json(path + '/messages', 'GET', member.token), []) assert.deepEqual(await json(path + '/messages', 'GET', member.token), [])
@@ -246,6 +283,8 @@ test('群密文和实时提示只投递到名单设备,移除或撤销阻断
assert.equal((await json(path + '/epochs', 'GET', owner.token)).every((epoch) => !epoch.current), true) assert.equal((await json(path + '/epochs', 'GET', owner.token)).every((epoch) => !epoch.current), true)
await change(owner, 'disband') await change(owner, 'disband')
await json(attachment, 'GET', owner.token, undefined, 404) await json(attachment, 'GET', owner.token, undefined, 404)
assert.ok(memberEvents.some((event) => event.type === 'group_changed' && event.groupId === group.id))
assert.ok(memberEvents.every((event) => event.notify === undefined))
assert.deepEqual(outsiderEvents, []) assert.deepEqual(outsiderEvents, [])
}) })
+36 -5
View File
@@ -155,6 +155,25 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
await owner.getByRole('heading', { name: group }).waitFor() await owner.getByRole('heading', { name: group }).waitFor()
await invite(owner, windows, names[1], group) await invite(owner, windows, names[1], group)
await invite(owner, removed, names[2], group) await invite(owner, removed, names[2], group)
const settings = (page, name) => page.getByRole('button', { name, exact: true })
await settings(removed, '群聊免打扰').click()
await removed.getByRole('button', { name: '群聊免打扰', pressed: true }).waitFor()
assert.equal(await settings(owner, '群聊免打扰').getAttribute('aria-pressed'), 'false')
await settings(owner, '置顶群聊').click()
await owner.getByRole('button', { name: '置顶群聊', pressed: true }).waitFor()
const ownerCompanion = await browser.newPage()
await ownerCompanion.goto(base)
await ownerCompanion.getByLabel('用户名').fill(names[0])
await ownerCompanion.getByLabel('密码', { exact: true }).fill(password)
await ownerCompanion.locator('button.primary').click()
await ownerCompanion.getByText('实时连接已建立').waitFor()
await work(ownerCompanion).getByRole('link', { name: '群组' }).click()
await ownerCompanion.getByRole('link', { name: new RegExp(group + '.*已置顶') }).click()
await settings(ownerCompanion, '群聊免打扰').click()
await owner.getByRole('button', { name: '群聊免打扰', pressed: true }).waitFor({ timeout: 4500 })
await settings(ownerCompanion, '群聊免打扰').click()
await owner.getByRole('button', { name: '群聊免打扰', pressed: false }).waitFor({ timeout: 4500 })
await ownerCompanion.close()
const codes = await Promise.all(pages.map(async (page) => { const codes = await Promise.all(pages.map(async (page) => {
await chat(page).getByRole('button', { name: '启用本机群聊' }).click() await chat(page).getByRole('button', { name: '启用本机群聊' }).click()
const code = page.locator('.group-security-code') const code = page.locator('.group-security-code')
@@ -180,10 +199,15 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
holdConnection = false holdConnection = false
await owner.getByText('实时连接已建立', { exact: true }).waitFor() await owner.getByText('实时连接已建立', { exact: true }).waitFor()
await Promise.all([owner, windows].map((page) => chat(page).getByText(first, { exact: true }).waitFor({ timeout: 3500 }))) 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)
await work(removed).getByRole('link', { name: '群组' }).click() await work(removed).getByRole('link', { name: '群组' }).click()
await removed.getByRole('link', { name: new RegExp(group) }).click() const unreadGroup = removed.getByRole('link', { name: new RegExp(group + '.*1 条未读') })
await unreadGroup.click()
await unreadGroup.waitFor()
await chat(removed).getByRole('button', { name: '启用本机群聊' }).click() await chat(removed).getByRole('button', { name: '启用本机群聊' }).click()
await chat(removed).getByText(first, { exact: true }).waitFor() await chat(removed).getByText(first, { exact: true }).waitFor()
await unreadGroup.waitFor({ state: 'detached', timeout: 4500 })
assert.equal(await windows.getByRole('link', { name: new RegExp(group + '.*未读') }).count(), 0)
const original = chat(owner).getByRole('listitem').filter({ hasText: first }) const original = chat(owner).getByRole('listitem').filter({ hasText: first })
assert.equal(await original.getByRole('button', { name: '编辑', exact: true }).count(), 0) assert.equal(await original.getByRole('button', { name: '编辑', exact: true }).count(), 0)
@@ -193,15 +217,18 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
assert.equal(await send(owner, reply), epoch) assert.equal(await send(owner, reply), epoch)
const receivedReply = chat(windows).getByRole('listitem').filter({ hasText: reply }) const receivedReply = chat(windows).getByRole('listitem').filter({ hasText: reply })
await receivedReply.locator('blockquote').getByText(first, { exact: true }).waitFor({ timeout: 3500 }) await receivedReply.locator('blockquote').getByText(first, { exact: true }).waitFor({ timeout: 3500 })
await settings(removed, '群聊免打扰').click()
await removed.getByRole('button', { name: '群聊免打扰', pressed: false }).waitFor()
await work(removed).getByRole('link', { name: '联系人' }).click() await work(removed).getByRole('link', { name: '联系人' }).click()
const own = chat(windows).getByRole('listitem').filter({ has: windows.getByText(first, { exact: true }) }).first() const own = chat(windows).getByRole('listitem').filter({ has: windows.getByText(first, { exact: true }) }).first()
await own.getByRole('button', { name: '编辑', exact: true }).click() await own.getByRole('button', { name: '编辑', exact: true }).click()
const edited = '已修改群消息 ' + id() const edited = '已修改群消息 ' + id()
assert.equal(await send(windows, edited, '保存编辑'), epoch) assert.equal(await send(windows, edited, '保存编辑'), epoch)
const notice = removed.getByRole('link', { name: '有新的群消息' })
await notice.waitFor({ timeout: 4500 })
const incomingEdit = chat(owner).getByRole('listitem').filter({ has: owner.getByText(edited, { exact: true }) }) const incomingEdit = chat(owner).getByRole('listitem').filter({ has: owner.getByText(edited, { exact: true }) })
await incomingEdit.getByText('已编辑', { exact: true }).waitFor() await incomingEdit.getByText('已编辑', { exact: true }).waitFor()
await work(removed).getByRole('link', { name: '群组' }).click() await notice.click()
await removed.getByRole('link', { name: new RegExp(group) }).click()
await chat(removed).getByRole('button', { name: '启用本机群聊' }).click() await chat(removed).getByRole('button', { name: '启用本机群聊' }).click()
await chat(removed).getByText(edited, { exact: true }).waitFor() await chat(removed).getByText(edited, { exact: true }).waitFor()
@@ -343,6 +370,7 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
await owner.getByLabel('群名称', { exact: true }).fill(targetGroup) await owner.getByLabel('群名称', { exact: true }).fill(targetGroup)
await owner.getByRole('button', { name: '创建群组' }).click() await owner.getByRole('button', { name: '创建群组' }).click()
await owner.getByRole('heading', { name: targetGroup }).waitFor() await owner.getByRole('heading', { name: targetGroup }).waitFor()
assert.match(await owner.getByRole('complementary', { name: '群组列表' }).getByRole('link').first().textContent(), /已置顶/)
await owner.getByLabel('邀请联系人').selectOption({ label: names[1] }) await owner.getByLabel('邀请联系人').selectOption({ label: names[1] })
await owner.getByRole('button', { name: '发送邀请' }).click() await owner.getByRole('button', { name: '发送邀请' }).click()
await windows.getByRole('link', { name: new RegExp(targetGroup) }).click() await windows.getByRole('link', { name: new RegExp(targetGroup) }).click()
@@ -407,8 +435,11 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
await windows.getByRole('button', { name: '启用本机加密聊天' }).click() await windows.getByRole('button', { name: '启用本机加密聊天' }).click()
const privateFile = '私聊文件-' + id() + '.txt' const privateFile = '私聊文件-' + id() + '.txt'
const originalUpload = windows.waitForResponse((item) => /\/api\/v1\/attachments\//.test(item.url()) && item.request().method() === 'POST') const originalUpload = windows.waitForResponse((item) => /\/api\/v1\/attachments\//.test(item.url()) && item.request().method() === 'POST')
await windows.getByLabel('发送附件').setInputFiles({ name: privateFile, mimeType: 'text/plain', buffer: contents }) const attachmentInput = windows.locator('input[type=file]:enabled')
const originalFile = await originalUpload const [originalFile] = await Promise.all([
originalUpload,
attachmentInput.setInputFiles({ name: privateFile, mimeType: 'text/plain', buffer: contents }),
])
assert.equal(originalFile.status(), 204) assert.equal(originalFile.status(), 204)
const originalBytes = originalFile.request().postDataBuffer() const originalBytes = originalFile.request().postDataBuffer()
assert.ok(originalBytes && originalBytes.length === contents.length + 16) assert.ok(originalBytes && originalBytes.length === contents.length + 16)
+24 -2
View File
@@ -1,6 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useSession } from '../session' import { useSession } from '../session'
import { APIError } from '../api'
import { downloadAttachment } from './attachments' import { downloadAttachment } from './attachments'
import type { Attachment } from './attachments' import type { Attachment } from './attachments'
import MediaPreview from './MediaPreview.vue' import MediaPreview from './MediaPreview.vue'
@@ -12,6 +13,7 @@ import { discardPendingGroupMessage, forwardGroupMessage, groupAttachmentPath, g
import type { ForwardDestination, GroupDetail, GroupDevice, GroupLine } from './group-chat' import type { ForwardDestination, GroupDetail, GroupDevice, GroupLine } from './group-chat'
const props = defineProps<{ group: GroupDetail }>() const props = defineProps<{ group: GroupDetail }>()
const emit = defineEmits<{ seen: [] }>()
const session = useSession() const session = useSession()
const view = ref<Awaited<ReturnType<typeof synchronizeGroup>>>() const view = ref<Awaited<ReturnType<typeof synchronizeGroup>>>()
const code = ref('') const code = ref('')
@@ -43,6 +45,8 @@ const canPublish = computed(() => Boolean(view.value && !view.value.current && m
let timer: ReturnType<typeof setInterval> let timer: ReturnType<typeof setInterval>
let refreshTimer: ReturnType<typeof setTimeout> | undefined let refreshTimer: ReturnType<typeof setTimeout> | undefined
let refreshPending = false let refreshPending = false
let lastSeen = '0'
let active = true
function pinned(device: GroupDevice) { function pinned(device: GroupDevice) {
return view.value?.pinned[device.id] === device.publicKey return view.value?.pinned[device.id] === device.publicKey
@@ -52,12 +56,25 @@ async function refresh() {
const identity = session.identity const identity = session.identity
if (!code.value || !identity) return if (!code.value || !identity) return
view.value = await synchronizeGroup(identity, props.group, session.authorized) view.value = await synchronizeGroup(identity, props.group, session.authorized)
if (!active) return
for (const member of members.value) { for (const member of members.value) {
const devices = view.value.devices.filter((device) => device.user === member.id) const devices = view.value.devices.filter((device) => device.user === member.id)
if (!devices.some((device) => device.id === selected.value[member.id] && pinned(device))) { if (!devices.some((device) => device.id === selected.value[member.id] && pinned(device))) {
selected.value[member.id] = devices.find(pinned)?.id ?? '' selected.value[member.id] = devices.find(pinned)?.id ?? ''
} }
} }
if (view.value.hasMore) queueRefresh()
const { cursor } = view.value
if (!ready.value || document.visibilityState !== 'visible' || cursor === lastSeen || cursor === '0') return
try {
await session.authorized('/groups/' + encodeURIComponent(props.group.id) + '/seen', 'POST', { sequence: cursor })
} catch (cause) {
// Retention or member changes can invalidate an already cached cursor.
if (!(cause instanceof APIError) || cause.status !== 404) throw cause
}
if (!active) return
lastSeen = cursor
emit('seen')
} }
async function run(action: () => Promise<void>, manual = true) { async function run(action: () => Promise<void>, manual = true) {
@@ -75,7 +92,7 @@ async function run(action: () => Promise<void>, manual = true) {
} }
function queueRefresh() { function queueRefresh() {
if (!code.value) return if (!active || !code.value) return
refreshPending = true refreshPending = true
if (busy.value || refreshTimer) return if (busy.value || refreshTimer) return
refreshTimer = setTimeout(() => { refreshTimer = setTimeout(() => {
@@ -223,11 +240,16 @@ watch([pendingVoice, busy, currentEpoch, () => view.value?.hasPending], ([voice,
await refresh() await refresh()
}) })
}) })
onMounted(() => { timer = setInterval(queueRefresh, 15_000) }) onMounted(() => {
timer = setInterval(queueRefresh, 15_000)
document.addEventListener('visibilitychange', queueRefresh)
})
onBeforeUnmount(() => { onBeforeUnmount(() => {
active = false
refreshPending = false refreshPending = false
clearTimeout(refreshTimer) clearTimeout(refreshTimer)
clearInterval(timer) clearInterval(timer)
document.removeEventListener('visibilitychange', queueRefresh)
}) })
</script> </script>
+5 -2
View File
@@ -7,7 +7,9 @@ import type { Attachment, Mutation } from './attachments'
export type GroupMember = { id: string; username: string; state: 'active' | 'invited'; role: 'owner' | 'admin' | 'member' } export type GroupMember = { id: string; username: string; state: 'active' | 'invited'; role: 'owner' | 'admin' | 'member' }
export type GroupDetail = { id: string; membershipVersion: string; members: GroupMember[]; role: GroupMember['role'] } export type GroupDetail = { id: string; membershipVersion: string; members: GroupMember[]; role: GroupMember['role'] }
export type GroupSummary = Omit<GroupDetail, 'members'> & { name: string; state: GroupMember['state'] } export type GroupPreferences = { pinned: boolean; muted: boolean }
export type GroupSummary = Omit<GroupDetail, 'members'> & GroupPreferences & { name: string; state: GroupMember['state'] }
export type ListedGroup = GroupSummary & { unread: number }
export type GroupDevice = Peer & { user: string } export type GroupDevice = Peer & { user: string }
type Epoch = { id: string; creatorDevice: string; membershipVersion: string; welcome?: string; current: boolean; roster: string[] } type Epoch = { id: string; creatorDevice: string; membershipVersion: string; welcome?: string; current: boolean; roster: string[] }
type Publishing = { id: string; membershipVersion: string; devices: { device: string; wire?: string }[] } type Publishing = { id: string; membershipVersion: string; devices: { device: string; wire?: string }[] }
@@ -270,7 +272,8 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
const engine = factory.DeviceMls.restore(decode(state.engine)) const engine = factory.DeviceMls.restore(decode(state.engine))
try { await replenishPackages(identity, call, state, save, engine) } catch { warning ||= '密钥包补充失败' } finally { engine.free() } try { await replenishPackages(identity, call, state, save, engine) } catch { warning ||= '密钥包补充失败' } finally { engine.free() }
} }
return { devices, lines: chat.lines, pinned: state.pinned, ready, current, warning, const hasMore = packets.length === 64 && packets.at(-1)?.sequence === chat.cursor
return { devices, lines: chat.lines, pinned: state.pinned, ready, current, warning, cursor: chat.cursor, hasMore,
hasPending: Boolean(chat.pendingMessage), stalePending: Boolean(chat.pendingMessage && chat.pendingMessage.epoch !== current?.id) } hasPending: Boolean(chat.pendingMessage), stalePending: Boolean(chat.pendingMessage && chat.pendingMessage.epoch !== current?.id) }
}) })
} }
+3 -3
View File
@@ -26,7 +26,7 @@ export const useSession = defineStore('session', () => {
const connection = ref('离线') const connection = ref('离线')
const contactChanges = ref(0) const contactChanges = ref(0)
const inboxChanges = ref(0) const inboxChanges = ref(0)
const groupChange = shallowRef<{ groupId: string }>() const groupChange = shallowRef<{ groupId: string; notify: boolean }>()
const groupListChanges = ref(0) const groupListChanges = ref(0)
let token = '' let token = ''
let socket: WebSocket | undefined let socket: WebSocket | undefined
@@ -54,14 +54,14 @@ export const useSession = defineStore('session', () => {
socket = active socket = active
active.onmessage = (event) => { active.onmessage = (event) => {
if (socket !== active) return if (socket !== active) return
const { type, groupId } = JSON.parse(event.data) const { type, groupId, notify } = JSON.parse(event.data)
if (type === 'ready') { if (type === 'ready') {
connection.value = '实时连接已建立' connection.value = '实时连接已建立'
attempts = 0 attempts = 0
} }
if (type === 'contacts_changed') contactChanges.value++ if (type === 'contacts_changed') contactChanges.value++
if (type === 'inbox_changed') inboxChanges.value++ if (type === 'inbox_changed') inboxChanges.value++
if (type === 'group_changed' && typeof groupId === 'string') groupChange.value = { groupId } if (type === 'group_changed' && typeof groupId === 'string') groupChange.value = { groupId, notify: notify === true }
if (type === 'group_list_changed') groupListChanges.value++ if (type === 'group_list_changed') groupListChanges.value++
} }
active.onclose = (event) => { active.onclose = (event) => {
+6 -6
View File
@@ -35,7 +35,7 @@ const recent = ref<Record<string, string>>({})
const conversationQuery = ref('') const conversationQuery = ref('')
const history = ref<HTMLOListElement>() const history = ref<HTMLOListElement>()
const shareRead = ref(false) const shareRead = ref(false)
const pendingVoice = ref<File>() const pendingFile = ref<File>()
const view = ref<Awaited<ReturnType<typeof synchronize>>>() const view = ref<Awaited<ReturnType<typeof synchronize>>>()
const target = computed(() => typeof route.params.user === 'string' ? route.params.user : '') const target = computed(() => typeof route.params.user === 'string' ? route.params.user : '')
const peer = computed(() => view.value?.peers.find((item) => item.id === selected.value)) const peer = computed(() => view.value?.peers.find((item) => item.id === selected.value))
@@ -213,7 +213,7 @@ function attach(event: Event) {
const input = event.target as HTMLInputElement const input = event.target as HTMLInputElement
const file = input.files?.[0] const file = input.files?.[0]
input.value = '' input.value = ''
if (file) sendFile(file) if (file) pendingFile.value = file
} }
function sendFile(file: File) { function sendFile(file: File) {
@@ -225,12 +225,12 @@ function sendFile(file: File) {
} }
function sendVoice(file: File) { function sendVoice(file: File) {
pendingVoice.value = file pendingFile.value = file
} }
watch([pendingVoice, busy], ([file, inProgress]) => { watch([pendingFile, busy], ([file, inProgress]) => {
if (!file || inProgress) return if (!file || inProgress) return
pendingVoice.value = undefined pendingFile.value = undefined
sendFile(file) sendFile(file)
}) })
@@ -286,7 +286,7 @@ watch(selected, () => {
recalling.value = undefined recalling.value = undefined
forwarding.value = undefined forwarding.value = undefined
forwardStatus.value = '' forwardStatus.value = ''
pendingVoice.value = undefined pendingFile.value = undefined
draft.value = '' draft.value = ''
scheduleReceipt() scheduleReceipt()
}) })
+41 -5
View File
@@ -5,7 +5,7 @@ import { useSession } from '../session'
import { APIError } from '../api' import { APIError } from '../api'
import type { Contact } from '../contacts' import type { Contact } from '../contacts'
import GroupChat from '../chat/GroupChat.vue' import GroupChat from '../chat/GroupChat.vue'
import type { GroupSummary } from '../chat/group-chat' import type { GroupPreferences, GroupSummary, ListedGroup } from '../chat/group-chat'
type Group = GroupSummary type Group = GroupSummary
type Detail = Group & { members: { id: string; username: string; state: Group['state']; role: Group['role'] }[] } type Detail = Group & { members: { id: string; username: string; state: Group['state']; role: Group['role'] }[] }
@@ -13,7 +13,7 @@ type Detail = Group & { members: { id: string; username: string; state: Group['s
const session = useSession() const session = useSession()
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const groups = ref<Group[]>([]) const groups = ref<ListedGroup[]>([])
const contacts = ref<Contact[]>([]) const contacts = ref<Contact[]>([])
const detail = ref<Detail>() const detail = ref<Detail>()
const term = ref('') const term = ref('')
@@ -37,7 +37,7 @@ let revision = 0
async function refresh() { async function refresh() {
const version = ++revision const version = ++revision
const selected = id.value const selected = id.value
let list = await session.authorized<Group[]>('/groups') let list = await session.authorized<ListedGroup[]>('/groups')
let next: Detail | undefined let next: Detail | undefined
if (list.some((group) => group.id === selected)) { if (list.some((group) => group.id === selected)) {
try { try {
@@ -111,6 +111,15 @@ function change(action: string, target?: string, value?: string) {
}) })
} }
function setPreference(key: keyof GroupPreferences) {
const current = detail.value
if (current?.state !== 'active') return
void run(async () => {
await session.authorized('/groups/' + current.id + '/preferences', 'POST', { [key]: !current[key] })
await refresh()
})
}
watch(id, () => { watch(id, () => {
detail.value = undefined detail.value = undefined
confirmation.value = undefined confirmation.value = undefined
@@ -120,6 +129,7 @@ watch(id, () => {
else reload() else reload()
}) })
watch(() => session.groupListChanges, queueRefresh) watch(() => session.groupListChanges, queueRefresh)
watch(() => session.groupChange, queueRefresh)
watch(() => session.connection, (connection) => { if (connection === '实时连接已建立') queueRefresh() }) watch(() => session.connection, (connection) => { if (connection === '实时连接已建立') queueRefresh() })
onMounted(() => { onMounted(() => {
reload() reload()
@@ -144,7 +154,14 @@ onBeforeUnmount(() => {
</form> </form>
<label>查找群组<input v-model="term" type="search" maxlength="64"></label> <label>查找群组<input v-model="term" type="search" maxlength="64"></label>
<RouterLink v-for="group in visible" :key="group.id" class="contact-item" :to="'/groups/' + group.id"> <RouterLink v-for="group in visible" :key="group.id" class="contact-item" :to="'/groups/' + group.id">
<span><strong>{{ group.name }}</strong><small>{{ group.state === 'invited' ? '待接受邀请' : roles[group.role] }}</small></span> <span>
<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 aria-hidden="true">{{ group.unread >= 100 ? '99+' : group.unread }}</span>
<span class="unread-label">{{ group.unread >= 100 ? '99 条以上未读' : group.unread + ' 条未读' }}</span>
</span>
</RouterLink> </RouterLink>
</aside> </aside>
<div class="device-content chat-page"> <div class="device-content chat-page">
@@ -159,7 +176,11 @@ onBeforeUnmount(() => {
</div> </div>
</template> </template>
<template v-else> <template v-else>
<GroupChat v-if="session.identity" :key="detail.id" :group="detail" /> <div class="message-actions" aria-label="群聊设置">
<button type="button" class="plain" :aria-pressed="detail.pinned" :disabled="busy" @click="setPreference('pinned')">置顶群聊</button>
<button type="button" class="plain" :aria-pressed="detail.muted" :disabled="busy" @click="setPreference('muted')">群聊免打扰</button>
</div>
<GroupChat v-if="session.identity" :key="detail.id" :group="detail" @seen="queueRefresh" />
<form v-if="manage" class="contact-preferences" @submit.prevent="change('rename', undefined, nextName)"> <form v-if="manage" class="contact-preferences" @submit.prevent="change('rename', undefined, nextName)">
<label>修改群名称<input v-model="nextName" required maxlength="64"></label> <label>修改群名称<input v-model="nextName" required maxlength="64"></label>
<button class="plain" :disabled="busy || !nextName.trim() || nextName.trim() === detail.name">保存群名称</button> <button class="plain" :disabled="busy || !nextName.trim() || nextName.trim() === detail.name">保存群名称</button>
@@ -203,3 +224,18 @@ onBeforeUnmount(() => {
</div> </div>
</section> </section>
</template> </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>
+31 -1
View File
@@ -1,11 +1,29 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue' import { onBeforeUnmount, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useSession } from '../session' import { useSession } from '../session'
const session = useSession() const session = useSession()
const route = useRoute()
const error = ref('') const error = ref('')
const busy = ref(false) const busy = ref(false)
const browser = window.xhchat?.openBrowser const browser = window.xhchat?.openBrowser
const notice = ref<string>()
let noticeTimer: ReturnType<typeof setTimeout> | undefined
function dismissNotice() {
clearTimeout(noticeTimer)
notice.value = undefined
}
watch(() => session.groupChange, (event) => {
if (!event?.notify || 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)
async function act(action: () => Promise<void>) { async function act(action: () => Promise<void>) {
busy.value = true busy.value = true
@@ -48,5 +66,17 @@ async function act(action: () => Promise<void>) {
</div> </div>
</aside> </aside>
<RouterView /> <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>
</main> </main>
</template> </template>
<style scoped>
.group-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;
}
</style>