From f54077ce46aa899b791e033308aad3a44422cb50 Mon Sep 17 00:00:00 2001 From: xhgit Date: Sat, 14 Nov 2026 16:00:46 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=BE=A4=E8=81=8A=E7=BD=AE?= =?UTF-8?q?=E9=A1=B6=E3=80=81=E5=85=8D=E6=89=93=E6=89=B0=E5=92=8C=E5=BA=94?= =?UTF-8?q?=E7=94=A8=E5=86=85=E6=8F=90=E9=86=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/api.md | 5 ++- docs/progress.md | 6 ++++ .../database/010_group_preferences.sql | 4 +++ server/internal/database/database.go | 5 ++- server/internal/groups/store.go | 34 +++++++++++++++--- server/internal/groups/transport.go | 35 +++++++++++-------- server/internal/httpapi/api.go | 1 + server/internal/httpapi/group_transport.go | 19 ++++++---- server/internal/httpapi/groups.go | 29 +++++++++++++++ server/internal/httpapi/realtime.go | 8 +++-- tests/delivery.test.mjs | 26 +++++++++++++- tests/group-chat.test.mjs | 35 ++++++++++++++++--- web/src/chat/group-chat.ts | 3 +- web/src/session.ts | 6 ++-- web/src/views/GroupView.vue | 20 +++++++++-- web/src/views/Workspace.vue | 32 ++++++++++++++++- 17 files changed, 228 insertions(+), 42 deletions(-) create mode 100644 server/internal/database/010_group_preferences.sql diff --git a/README.md b/README.md index 406c610..11c79f5 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ | 账号与设备 | Windows 和 Web 共用账号,支持用户名注册、登录、查看设备和远程撤销。 | | 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 | | 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 | -| 加密群聊 | 创建群组、邀请联系人和管理成员。每个账号选一台已核验设备参与 MLS 加密文字聊天。 | +| 加密群聊 | 创建群组、邀请联系人、管理成员,并按账号同步置顶和免打扰。每个账号选一台已核验设备参与 MLS 加密文字聊天。 | | 加密附件 | 两端可在私聊和群聊发送、下载最多 8 MiB 的文件,并在本机预览图片和视频。 | | 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 | | 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索和收藏。消息可转发到已建立加密会话的群或已核验的联系人设备。私聊支持可选加密已读回执。 | diff --git a/docs/api.md b/docs/api.md index 27c517c..2d598c5 100644 --- a/docs/api.md +++ b/docs/api.md @@ -28,6 +28,7 @@ | GET | /api/v1/attachments/{id} | 原发送或接收设备获取附件密文 | | GET / POST | /api/v1/groups | 列出当前账号所属群组与邀请,或创建群组 | | GET / POST | /api/v1/groups/{id} | 查看群组详情或执行邀请、接受、拒绝、改名、升降管理员、移除、退出或解散 | +| POST | /api/v1/groups/{id}/preferences | 更新当前账号的 `pinned` 和 `muted`,可只传其中一项 | | GET | /api/v1/groups/{id}/devices | 获取群成员的有效设备与 MLS 公钥 | | POST | /api/v1/groups/{id}/devices/{device}/claim | 群主一次性领取群成员设备的 KeyPackage | | GET / POST | /api/v1/groups/{id}/epochs | 读取当前设备可访问的会话信息或由群主发布新世代 | @@ -54,7 +55,9 @@ 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 游标返回本设备有权读取的密文。 -群世代和密文提交后,WebSocket 向该世代的设备发送 `group_changed`,事件只包含 `type` 和 `groupId`。客户端收到提示、重连或到达兜底轮询周期时,按持久化的游标向授权接口补拉。提示由 Redis 尽力送达,数据库保存投递记录。 +群世代和密文提交后,WebSocket 向该世代的设备发送 `group_changed`,包含 `type` 和 `groupId`。新投递给其他设备的密文在该账号未开启免打扰时附带 `notify: true`。客户端收到提示、重连或到达兜底轮询周期时,按持久化的游标向授权接口补拉。提示由 Redis 尽力送达,数据库保存投递记录。 + +群列表和详情返回当前账号的 `pinned` 和 `muted`。群列表先排序置顶群,随后按创建时间排序。设置修改后,同一账号的在线设备收到刷新提示。离开群组或被移除后,当前成员资格的设置随之清除。 有效成员可通过 `GET /groups/{id}/devices` 获取群内有效设备凭据。群主通过 `POST /groups/{id}/devices/{device}/claim` 一次性领取其他有效成员的设备密钥包。邀请待接受的账号、已离群的账号和撤销设备无法访问群设备目录。 diff --git a/docs/progress.md b/docs/progress.md index a4273f4..0d488f8 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -156,3 +156,9 @@ Windows 和 Web 的私聊与群聊共用转发目标选择。私聊支持把文 群成员、邀请与群资料更新事务提交后,受影响账号的在线设备收到刷新提示。提示只含事件类型。群组页合并提示,通过现有授权接口刷新列表和当前群详情,重连时也会刷新,并保留 15 秒兜底轮询。群成员权限仍取决于服务端的实时授权结果。 Windows Electron 和 Edge 验证了群组页在兜底轮询前显示邀请、成员接受和成员移除。服务端测试验证普通成员收不到其他人的待处理邀请提示,未加入账号收不到群事件,解散会通知仍待接受邀请的账号。 + +## 群置顶和免打扰 + +两端可按账号设置群置顶和免打扰,置顶群排在群列表前面。离开群页面时,未静音的新群投递可显示通用的应用内提醒,点击返回群组。免打扰保留 WebSocket 补拉提示,省略应用内提醒标记。原生系统通知和 Web Push 仍待实现。 + +测试覆盖迁移 010、邀请者和外部账号不可修改群设置、不同账号的设置隔离、双端静音收取和提醒入口,以及同一账号的两台设备实时同步偏好。 diff --git a/server/internal/database/010_group_preferences.sql b/server/internal/database/010_group_preferences.sql new file mode 100644 index 0000000..bcbff2e --- /dev/null +++ b/server/internal/database/010_group_preferences.sql @@ -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)); diff --git a/server/internal/database/database.go b/server/internal/database/database.go index 63d6829..05ac3eb 100644 --- a/server/internal/database/database.go +++ b/server/internal/database/database.go @@ -34,6 +34,9 @@ var groupTransportMigration string //go:embed 009_group_attachments.sql var groupAttachmentsMigration string +//go:embed 010_group_preferences.sql +var groupPreferencesMigration string + func Migrate(ctx context.Context, pool *pgxpool.Pool) error { tx, err := pool.Begin(ctx) if err != nil { @@ -48,7 +51,7 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool) error { } for index, migration := range []string{ identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration, - attachmentsMigration, groupsMigration, groupTransportMigration, groupAttachmentsMigration, + attachmentsMigration, groupsMigration, groupTransportMigration, groupAttachmentsMigration, groupPreferencesMigration, } { version := index + 1 var applied bool diff --git a/server/internal/groups/store.go b/server/internal/groups/store.go index a80a467..7075f69 100644 --- a/server/internal/groups/store.go +++ b/server/internal/groups/store.go @@ -18,6 +18,12 @@ type Group struct { State string `json:"state"` Role string `json:"role"` Version string `json:"membershipVersion"` + Preferences +} + +type Preferences struct { + Pinned bool `json:"pinned"` + Muted bool `json:"muted"` } type Member struct { @@ -53,12 +59,12 @@ func (s *Store) Create(ctx context.Context, owner, name string) (Group, error) { } 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 + 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,m.pinned,m.muted 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) { - rows, err := s.db.Query(ctx, groupRows+" ORDER BY g.created_at DESC, g.id LIMIT 200", user) + rows, err := s.db.Query(ctx, groupRows+" ORDER BY m.pinned DESC, g.created_at DESC, g.id LIMIT 200", user) if err != nil { return nil, err } @@ -66,7 +72,7 @@ func (s *Store) List(ctx context.Context, user string) ([]Group, error) { result := make([]Group, 0) for rows.Next() { var g Group - 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); err != nil { return nil, err } result = append(result, g) @@ -82,7 +88,7 @@ func (s *Store) Detail(ctx context.Context, user, id string) (Detail, error) { } defer tx.Rollback(ctx) err = tx.QueryRow(ctx, 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) { return result, ErrUnavailable } @@ -115,6 +121,26 @@ func (s *Store) Detail(ctx context.Context, user, id string) (Detail, error) { 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) { tx, err := s.db.Begin(ctx) if err != nil { diff --git a/server/internal/groups/transport.go b/server/internal/groups/transport.go index 57bf11c..791e55e 100644 --- a/server/internal/groups/transport.go +++ b/server/internal/groups/transport.go @@ -150,7 +150,12 @@ func retryEpoch(ctx context.Context, tx pgx.Tx, group, sender string, input Epoc 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) if err != nil { 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 // revoked the generation cannot accept any further application ciphertext. 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 `, group, epoch) if err != nil { return nil, err } defer rows.Close() - devices := make([]string, 0, 32) + devices := make([]EpochDevice, 0, 32) for rows.Next() { - var id string + var member EpochDevice 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 } if !active { return nil, ErrVersion } - devices = append(devices, id) + devices = append(devices, member) } 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) if err != nil { - return "", nil, err + return "", nil, false, err } defer tx.Rollback(ctx) devices, err := lockSendingEpoch(ctx, tx, group, user, device, message.Epoch) if err != nil { - return "", nil, err + return "", nil, false, err } if message.AttachmentID != nil { 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 `, group, message.Epoch, device, message.AttachmentID).Scan(&found) if errors.Is(err, pgx.ErrNoRows) { - return "", nil, ErrAttachment + return "", nil, false, ErrAttachment } 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) 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) + created := err == nil if errors.Is(err, pgx.ErrNoRows) { var same bool 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 `, group, message.Epoch, device, message.ID, message.Wire, message.AttachmentID).Scan(&sequence, &same) if errors.Is(err, pgx.ErrNoRows) || err == nil && !same { - return "", nil, ErrVersion + return "", nil, false, ErrVersion } } 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) { diff --git a/server/internal/httpapi/api.go b/server/internal/httpapi/api.go index b97dfcf..9549c8e 100644 --- a/server/internal/httpapi/api.go +++ b/server/internal/httpapi/api.go @@ -64,6 +64,7 @@ func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *d mux.HandleFunc("POST /api/v1/groups", a.authorized(a.createGroup)) 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}/preferences", a.authorized(a.setGroupPreferences)) 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("GET /api/v1/groups/{id}/messages", a.authorized(a.groupInbox)) diff --git a/server/internal/httpapi/group_transport.go b/server/internal/httpapi/group_transport.go index 49f6ca9..9f7c6e3 100644 --- a/server/internal/httpapi/group_transport.go +++ b/server/internal/httpapi/group_transport.go @@ -97,11 +97,11 @@ func (a *API) publishGroupEpoch(w http.ResponseWriter, r *http.Request, _ string groupError(w, err) return } - devices := make([]string, 0, len(input.Devices)) + devices := make([]groups.EpochDevice, 0, len(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) } @@ -129,21 +129,26 @@ func (a *API) sendGroupMessage(w http.ResponseWriter, r *http.Request, _ string, return } 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 { groupError(w, err) 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}) } -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) defer cancel() pipe := a.redis.Pipeline() + group = strings.ToLower(group) 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. _, _ = pipe.Exec(ctx) diff --git a/server/internal/httpapi/groups.go b/server/internal/httpapi/groups.go index 57f49f5..681f90e 100644 --- a/server/internal/httpapi/groups.go +++ b/server/internal/httpapi/groups.go @@ -134,3 +134,32 @@ func (a *API) hintGroupList(ctx context.Context, users []string) { } _, _ = 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) +} diff --git a/server/internal/httpapi/realtime.go b/server/internal/httpapi/realtime.go index 77d40ce..0b05229 100644 --- a/server/internal/httpapi/realtime.go +++ b/server/internal/httpapi/realtime.go @@ -103,15 +103,19 @@ func (a *API) realtime(w http.ResponseWriter, r *http.Request) { return } 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 { case groupsChannel: event["type"] = "group_list_changed" case inboxChannel: 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["groupId"] = group + if kind == "group-notify" { + event["notify"] = true + } } } err := wsjson.Write(writeCtx, conn, event) diff --git a/tests/delivery.test.mjs b/tests/delivery.test.mjs index 7b31754..65afd68 100644 --- a/tests/delivery.test.mjs +++ b/tests/delivery.test.mjs @@ -62,6 +62,7 @@ test('群组邀请、授权、成员移除、版本变更与实时提示', { tim const other = await register() const group = await json('/groups', 'POST', owner.token, { name: '发布验收群' }, 201) const path = '/groups/' + group.id + const preferences = path + '/preferences' const act = async (actor, action, target, expected = 204, name) => { const reply = await call(path, 'POST', actor.token, { action, target, name }) assert.equal(reply.status, expected, await reply.text()) @@ -81,6 +82,8 @@ test('群组邀请、授权、成员移除、版本变更与实时提示', { tim await expectHint([ownerSocket, memberSocket], () => act(owner, 'invite', member.user.id)) const invitation = await json(path, 'GET', member.token) 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.equal(invitation.membershipVersion, '1') 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(member, 'accept')) 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.deepEqual(active.members.map((item) => item.role).sort(), ['member', 'owner']) 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) const [ownerSocket, memberSocket, outsiderSocket] = await Promise.all([owner, member, outsider].map((actor) => watchRealtime(actor, t))) const outsiderEvents = [] + const memberEvents = [] 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 epochHint = once(memberSocket, 'message', { signal: AbortSignal.timeout(4000) }) await publish(owner, second) @@ -196,11 +216,13 @@ test('群密文和实时提示只投递到名单设备,移除或撤销阻断 const message = { id: randomUUID(), epoch: second.id, wire: frame() } const messageHint = once(ownerSocket, 'message', { signal: AbortSignal.timeout(4000) }) 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) const received = await json(path + '/messages', 'GET', member.token) assert.deepEqual(received.map((item) => item.wire), [message.wire]) + await json(path + '/preferences', 'POST', member.token, { muted: true }) + const attachmentId = randomUUID() const attachment = path + '/attachments/' + attachmentId const bytes = randomBytes(16_384) @@ -246,6 +268,8 @@ test('群密文和实时提示只投递到名单设备,移除或撤销阻断 assert.equal((await json(path + '/epochs', 'GET', owner.token)).every((epoch) => !epoch.current), true) await change(owner, 'disband') 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, []) }) diff --git a/tests/group-chat.test.mjs b/tests/group-chat.test.mjs index 2d641dd..8f02674 100644 --- a/tests/group-chat.test.mjs +++ b/tests/group-chat.test.mjs @@ -155,6 +155,25 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员 await owner.getByRole('heading', { name: group }).waitFor() await invite(owner, windows, names[1], group) await invite(owner, removed, names[2], group) + const 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) => { await chat(page).getByRole('button', { name: '启用本机群聊' }).click() const code = page.locator('.group-security-code') @@ -180,6 +199,7 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员 holdConnection = false await owner.getByText('实时连接已建立', { exact: true }).waitFor() await Promise.all([owner, windows].map((page) => chat(page).getByText(first, { exact: true }).waitFor({ timeout: 3500 }))) + assert.equal(await removed.getByRole('link', { name: '有新的群消息' }).count(), 0) await work(removed).getByRole('link', { name: '群组' }).click() await removed.getByRole('link', { name: new RegExp(group) }).click() await chat(removed).getByRole('button', { name: '启用本机群聊' }).click() @@ -193,15 +213,18 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员 assert.equal(await send(owner, reply), epoch) const receivedReply = chat(windows).getByRole('listitem').filter({ hasText: reply }) 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() const own = chat(windows).getByRole('listitem').filter({ has: windows.getByText(first, { exact: true }) }).first() await own.getByRole('button', { name: '编辑', exact: true }).click() const edited = '已修改群消息 ' + id() 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 }) }) await incomingEdit.getByText('已编辑', { exact: true }).waitFor() - await work(removed).getByRole('link', { name: '群组' }).click() - await removed.getByRole('link', { name: new RegExp(group) }).click() + await notice.click() await chat(removed).getByRole('button', { name: '启用本机群聊' }).click() await chat(removed).getByText(edited, { exact: true }).waitFor() @@ -343,6 +366,7 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员 await owner.getByLabel('群名称', { exact: true }).fill(targetGroup) await owner.getByRole('button', { name: '创建群组' }).click() 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.getByRole('button', { name: '发送邀请' }).click() await windows.getByRole('link', { name: new RegExp(targetGroup) }).click() @@ -407,8 +431,11 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员 await windows.getByRole('button', { name: '启用本机加密聊天' }).click() const privateFile = '私聊文件-' + id() + '.txt' 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 originalFile = await originalUpload + const attachmentInput = windows.locator('input[type=file]:enabled') + const [originalFile] = await Promise.all([ + originalUpload, + attachmentInput.setInputFiles({ name: privateFile, mimeType: 'text/plain', buffer: contents }), + ]) assert.equal(originalFile.status(), 204) const originalBytes = originalFile.request().postDataBuffer() assert.ok(originalBytes && originalBytes.length === contents.length + 16) diff --git a/web/src/chat/group-chat.ts b/web/src/chat/group-chat.ts index 36b9a7d..5e69275 100644 --- a/web/src/chat/group-chat.ts +++ b/web/src/chat/group-chat.ts @@ -7,7 +7,8 @@ import type { Attachment, Mutation } from './attachments' 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 GroupSummary = Omit & { name: string; state: GroupMember['state'] } +export type GroupPreferences = { pinned: boolean; muted: boolean } +export type GroupSummary = Omit & GroupPreferences & { name: string; state: GroupMember['state'] } export type GroupDevice = Peer & { user: 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 }[] } diff --git a/web/src/session.ts b/web/src/session.ts index 532c926..52d2b14 100644 --- a/web/src/session.ts +++ b/web/src/session.ts @@ -26,7 +26,7 @@ export const useSession = defineStore('session', () => { const connection = ref('离线') const contactChanges = ref(0) const inboxChanges = ref(0) - const groupChange = shallowRef<{ groupId: string }>() + const groupChange = shallowRef<{ groupId: string; notify: boolean }>() const groupListChanges = ref(0) let token = '' let socket: WebSocket | undefined @@ -54,14 +54,14 @@ export const useSession = defineStore('session', () => { socket = active active.onmessage = (event) => { if (socket !== active) return - const { type, groupId } = JSON.parse(event.data) + const { type, groupId, notify } = JSON.parse(event.data) if (type === 'ready') { connection.value = '实时连接已建立' attempts = 0 } if (type === 'contacts_changed') contactChanges.value++ if (type === 'inbox_changed') inboxChanges.value++ - if (type === '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++ } active.onclose = (event) => { diff --git a/web/src/views/GroupView.vue b/web/src/views/GroupView.vue index efbebfa..0f5fe16 100644 --- a/web/src/views/GroupView.vue +++ b/web/src/views/GroupView.vue @@ -5,7 +5,7 @@ import { useSession } from '../session' import { APIError } from '../api' import type { Contact } from '../contacts' import GroupChat from '../chat/GroupChat.vue' -import type { GroupSummary } from '../chat/group-chat' +import type { GroupPreferences, GroupSummary } from '../chat/group-chat' type Group = GroupSummary type Detail = Group & { members: { id: string; username: string; state: Group['state']; role: Group['role'] }[] } @@ -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, () => { detail.value = undefined confirmation.value = undefined @@ -144,7 +153,10 @@ onBeforeUnmount(() => { - {{ group.name }}{{ group.state === 'invited' ? '待接受邀请' : roles[group.role] }} + + {{ group.name }} + {{ group.state === 'invited' ? '待接受邀请' : roles[group.role] }} +
@@ -159,6 +171,10 @@ onBeforeUnmount(() => {