增加群组创建、邀请与成员权限管理

This commit is contained in:
xhgit committed 2026-11-14 08:20:47 +08:00
1 parent b1f55df263
commit 99a741e6da
13 files changed
+620 -5

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
CREATE TABLE chat_groups (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
name text NOT NULL CHECK (char_length(name) BETWEEN 1 AND 64),
owner_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
membership_version bigint NOT NULL DEFAULT 1,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE group_members (
group_id uuid NOT NULL REFERENCES chat_groups(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
state text NOT NULL CHECK (state IN ('invited', 'active')),
role text NOT NULL DEFAULT 'member' CHECK (role IN ('member', 'admin')),
PRIMARY KEY (group_id, user_id),
CHECK (state = 'active' OR role = 'member')
);
CREATE INDEX group_members_user ON group_members(user_id, group_id);
+4 -1
View File
@@ -25,6 +25,9 @@ var mlsCredentialsMigration string
//go:embed 006_attachments.sql
var attachmentsMigration string
//go:embed 007_groups.sql
var groupsMigration string
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx)
if err != nil {
@@ -37,7 +40,7 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
if _, err = tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY)"); err != nil {
return err
}
for index, migration := range []string{identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration, attachmentsMigration} {
for index, migration := range []string{identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration, attachmentsMigration, groupsMigration} {
version := index + 1
var applied bool
if err = tx.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version=$1)", version).Scan(&applied); err != nil {
+252
View File
@@ -0,0 +1,252 @@
package groups
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
var ErrUnavailable = errors.New("group unavailable")
var ErrAction = errors.New("group action unavailable")
var ErrLimit = errors.New("group member limit reached")
type Group struct {
ID string `json:"id"`
Name string `json:"name"`
State string `json:"state"`
Role string `json:"role"`
Version string `json:"membershipVersion"`
}
type Member struct {
ID string `json:"id"`
Username string `json:"username"`
State string `json:"state"`
Role string `json:"role"`
}
type Detail struct {
Group
Members []Member `json:"members"`
}
type Change struct {
Action string `json:"action"`
Target string `json:"target"`
Name string `json:"name"`
}
type Store struct{ db *pgxpool.Pool }
func New(db *pgxpool.Pool) *Store { return &Store{db: db} }
func (s *Store) Create(ctx context.Context, owner, name string) (Group, error) {
result := Group{Name: name, State: "active", Role: "owner", Version: "1"}
err := s.db.QueryRow(ctx, `
WITH created AS (INSERT INTO chat_groups(name,owner_id) VALUES($2,$1) RETURNING id)
INSERT INTO group_members(group_id,user_id,state)
SELECT id,$1,'active' FROM created RETURNING group_id
`, owner, name).Scan(&result.ID)
return result, err
}
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
`
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)
if err != nil {
return nil, err
}
defer rows.Close()
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 {
return nil, err
}
result = append(result, g)
}
return result, rows.Err()
}
func (s *Store) Detail(ctx context.Context, user, id string) (Detail, error) {
result := Detail{Members: make([]Member, 0)}
tx, err := s.db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
if err != nil {
return result, err
}
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)
if errors.Is(err, pgx.ErrNoRows) {
return result, ErrUnavailable
}
if err != nil {
return result, err
}
if result.State != "active" {
return result, tx.Commit(ctx)
}
rows, err := tx.Query(ctx, `
SELECT m.user_id,u.username,m.state,CASE WHEN m.user_id=g.owner_id THEN 'owner' ELSE m.role END
FROM group_members m JOIN users u ON u.id=m.user_id JOIN chat_groups g ON g.id=m.group_id
WHERE m.group_id=$1 AND (m.state='active' OR $2 IN ('owner','admin'))
ORDER BY u.username
`, id, result.Role)
if err != nil {
return result, err
}
defer rows.Close()
for rows.Next() {
var member Member
if err := rows.Scan(&member.ID, &member.Username, &member.State, &member.Role); err != nil {
return result, err
}
result.Members = append(result.Members, member)
}
if err = rows.Err(); err != nil {
return result, err
}
return result, tx.Commit(ctx)
}
func (s *Store) Change(ctx context.Context, user, id string, change Change) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
// Serialize membership and version changes on the group row.
var owner string
err = tx.QueryRow(ctx, "SELECT owner_id FROM chat_groups WHERE id=$1 FOR UPDATE", id).Scan(&owner)
if errors.Is(err, pgx.ErrNoRows) {
return ErrUnavailable
}
if err != nil {
return err
}
var state, role string
err = tx.QueryRow(ctx, "SELECT state,role FROM group_members WHERE group_id=$1 AND user_id=$2", id, user).Scan(&state, &role)
if errors.Is(err, pgx.ErrNoRows) {
return ErrUnavailable
}
if err != nil {
return err
}
if owner == user {
role = "owner"
}
activeChanged := false
if state == "invited" {
switch change.Action {
case "accept":
_, err = tx.Exec(ctx, "UPDATE group_members SET state='active' WHERE group_id=$1 AND user_id=$2", id, user)
activeChanged = true
case "decline":
_, err = tx.Exec(ctx, "DELETE FROM group_members WHERE group_id=$1 AND user_id=$2", id, user)
default:
return ErrAction
}
} else {
activeChanged, err = changeActive(ctx, tx, user, id, owner, role, change)
}
if err != nil {
return err
}
if activeChanged {
if _, err = tx.Exec(ctx, "UPDATE chat_groups SET membership_version=membership_version+1 WHERE id=$1", id); err != nil {
return err
}
}
return tx.Commit(ctx)
}
func changeActive(ctx context.Context, tx pgx.Tx, user, id, owner, role string, change Change) (bool, error) {
manage := role == "owner" || role == "admin"
switch change.Action {
case "leave":
if role == "owner" {
return false, ErrAction
}
_, err := tx.Exec(ctx, "DELETE FROM group_members WHERE group_id=$1 AND user_id=$2", id, user)
return true, err
case "disband":
if role != "owner" {
return false, ErrAction
}
_, err := tx.Exec(ctx, "DELETE FROM chat_groups WHERE id=$1", id)
return false, err
case "rename":
if !manage {
return false, ErrAction
}
_, err := tx.Exec(ctx, "UPDATE chat_groups SET name=$2 WHERE id=$1", id, change.Name)
return false, err
case "invite":
if !manage || change.Target == user {
return false, ErrAction
}
return false, invite(ctx, tx, user, id, change.Target)
case "remove", "promote", "demote":
if !manage || change.Target == owner || change.Target == user {
return false, ErrAction
}
return changeMember(ctx, tx, id, role, change)
default:
return false, ErrAction
}
}
func invite(ctx context.Context, tx pgx.Tx, user, id, target string) error {
var count int
if err := tx.QueryRow(ctx, "SELECT count(*) FROM group_members WHERE group_id=$1", id).Scan(&count); err != nil {
return err
}
if count >= 32 {
return ErrLimit
}
tag, err := tx.Exec(ctx, `
INSERT INTO group_members(group_id,user_id,state)
SELECT $1,$3,'invited' FROM contact_relationships
WHERE first_user=LEAST($2::uuid,$3::uuid) AND second_user=GREATEST($2::uuid,$3::uuid)
AND status='accepted'
ON CONFLICT(group_id,user_id) DO NOTHING
`, id, user, target)
if err == nil && tag.RowsAffected() == 0 {
return ErrAction
}
return err
}
func changeMember(ctx context.Context, tx pgx.Tx, id, role string, change Change) (bool, error) {
if change.Action == "remove" {
var state string
err := tx.QueryRow(ctx, `
DELETE FROM group_members WHERE group_id=$1 AND user_id=$2 AND ($3='owner' OR role='member')
RETURNING state
`, id, change.Target, role).Scan(&state)
if errors.Is(err, pgx.ErrNoRows) {
return false, ErrAction
}
return state == "active", err
}
if role != "owner" {
return false, ErrAction
}
next := "member"
if change.Action == "promote" {
next = "admin"
}
tag, err := tx.Exec(ctx, "UPDATE group_members SET role=$3 WHERE group_id=$1 AND user_id=$2 AND state='active'", id, change.Target, next)
if err == nil && tag.RowsAffected() == 0 {
return false, ErrAction
}
return false, err
}
+8 -2
View File
@@ -16,6 +16,7 @@ import (
"xhchat/server/internal/account"
"xhchat/server/internal/contacts"
"xhchat/server/internal/delivery"
"xhchat/server/internal/groups"
"github.com/jackc/pgx/v5"
"github.com/redis/go-redis/v9"
@@ -25,14 +26,15 @@ type API struct {
accounts *account.Store
contacts *contacts.Store
delivery *delivery.Store
groups *groups.Store
redis *redis.Client
origins map[string]bool
hashSlots chan struct{}
ready func(context.Context) error
}
func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *delivery.Store, cache *redis.Client, origins map[string]bool, ready func(context.Context) error) http.Handler {
a := &API{accounts: accounts, contacts: contactStore, delivery: envelopeStore, redis: cache, origins: origins, hashSlots: make(chan struct{}, 4), ready: ready}
func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *delivery.Store, groupStore *groups.Store, cache *redis.Client, origins map[string]bool, ready func(context.Context) error) http.Handler {
a := &API{accounts: accounts, contacts: contactStore, delivery: envelopeStore, groups: groupStore, redis: cache, origins: origins, hashSlots: make(chan struct{}, 4), ready: ready}
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { respond(w, 200, map[string]string{"status": "ok"}) })
mux.HandleFunc("GET /readyz", a.readiness)
@@ -58,6 +60,10 @@ func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *d
mux.HandleFunc("POST /api/v1/attachments/{id}", a.authorized(a.uploadAttachment))
mux.HandleFunc("GET /api/v1/attachments/{id}", a.authorized(a.downloadAttachment))
mux.HandleFunc("GET /api/v1/mls-local-key", a.authorized(a.localMLSKey))
mux.HandleFunc("GET /api/v1/groups", a.authorized(a.listGroups))
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))
return a.boundary(mux)
}
+113
View File
@@ -0,0 +1,113 @@
package httpapi
import (
"errors"
"net/http"
"strings"
"unicode"
"unicode/utf8"
"xhchat/server/internal/account"
"xhchat/server/internal/groups"
)
func groupName(name string) bool {
return name != "" && utf8.RuneCountInString(name) <= 64 && !strings.ContainsFunc(name, unicode.IsControl)
}
func groupError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, groups.ErrUnavailable):
problem(w, 404, "group_not_found", "群聊不可用")
case errors.Is(err, groups.ErrAction):
problem(w, 409, "group_action_unavailable", "当前无法执行此群操作")
case errors.Is(err, groups.ErrLimit):
problem(w, 409, "group_member_limit", "群成员与待处理邀请已达上限")
default:
unavailable(w, err)
}
}
func (a *API) createGroup(w http.ResponseWriter, r *http.Request, _ string, id account.Identity) {
var body struct {
Name string `json:"name"`
}
if !parse(w, r, &body) {
return
}
name := strings.TrimSpace(body.Name)
if !groupName(name) {
problem(w, 400, "invalid_group_name", "群名称须为 1 至 64 个字符")
return
}
if !a.limit(w, r, "group-create:"+id.User.ID, 10) {
return
}
group, err := a.groups.Create(r.Context(), id.User.ID, name)
if err != nil {
groupError(w, err)
return
}
respond(w, 201, group)
}
func (a *API) listGroups(w http.ResponseWriter, r *http.Request, _ string, id account.Identity) {
result, err := a.groups.List(r.Context(), id.User.ID)
if err != nil {
groupError(w, err)
return
}
respond(w, 200, result)
}
func (a *API) groupDetail(w http.ResponseWriter, r *http.Request, _ string, id account.Identity) {
group := r.PathValue("id")
if !uuidPattern.MatchString(group) {
groupError(w, groups.ErrUnavailable)
return
}
result, err := a.groups.Detail(r.Context(), id.User.ID, group)
if err != nil {
groupError(w, err)
return
}
respond(w, 200, result)
}
func (a *API) changeGroup(w http.ResponseWriter, r *http.Request, _ string, id account.Identity) {
group := r.PathValue("id")
if !uuidPattern.MatchString(group) {
groupError(w, groups.ErrUnavailable)
return
}
var change groups.Change
if !parse(w, r, &change) {
return
}
switch change.Action {
case "invite", "remove", "promote", "demote":
if !uuidPattern.MatchString(change.Target) {
problem(w, 400, "invalid_member", "群成员 ID 无效")
return
}
change.Target = strings.ToLower(change.Target)
case "rename":
change.Name = strings.TrimSpace(change.Name)
if !groupName(change.Name) {
problem(w, 400, "invalid_group_name", "群名称须为 1 至 64 个字符")
return
}
case "accept", "decline", "leave", "disband":
default:
problem(w, 400, "invalid_group_action", "群操作无效")
return
}
if !a.limit(w, r, "group-change:"+id.User.ID, 60) {
return
}
if err := a.groups.Change(r.Context(), id.User.ID, group, change); err != nil {
groupError(w, err)
return
}
w.WriteHeader(204)
}