diff --git a/database.go b/database.go index 8ee2984..4f7829b 100644 --- a/database.go +++ b/database.go @@ -2,7 +2,9 @@ package main import ( "context" + "time" + "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) @@ -121,3 +123,23 @@ func DbSetGroupById(ctx context.Context, group *Group) error { } return rows.Err() } + +func DbAddClientsToGroup(ctx context.Context, groupId uint32, clientIds []uint32) error { + batch := &pgx.Batch{} + now := time.Now() + for _, cid := range clientIds { + batch.Queue(` + INSERT INTO chat_group_members (group_id, user_id, joined_at) + VALUES ($1, $2, $3) + ON CONFLICT DO NOTHING + `, groupId, cid, now) + } + br := dbConn.SendBatch(ctx, batch) + defer br.Close() + for range clientIds { + if _, err := br.Exec(); err != nil { + return err + } + } + return nil +} diff --git a/go-socket b/go-socket index 2704ae6..7af15e3 100755 Binary files a/go-socket and b/go-socket differ diff --git a/go.mod b/go.mod index 2902dbf..e6bf2fb 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,11 @@ require ( golang.org/x/crypto v0.49.0 ) +require ( + github.com/jackc/puddle/v2 v2.2.2 // indirect + golang.org/x/sync v0.20.0 // indirect +) + require ( github.com/golang-jwt/jwt/v5 v5.3.1 github.com/jackc/pgpassfile v1.0.0 // indirect diff --git a/http.go b/http.go index af3ae43..e44f503 100644 --- a/http.go +++ b/http.go @@ -202,6 +202,7 @@ func HttpHandleGroupAddClient(response http.ResponseWriter, request *http.Reques ctx := request.Context() var group Group + group.Id = affectedGroupId groupPtr, err := CacheGetGroup(affectedGroupId) if err == nil { group = *groupPtr @@ -225,10 +226,28 @@ func HttpHandleGroupAddClient(response http.ResponseWriter, request *http.Reques return } - usersToAdd := strings.SplitN(usersToAddString, ",", remainingUsersCount+1) - if len(usersToAdd) == 0 { + userIdStrings := strings.SplitN(usersToAddString, ",", remainingUsersCount+1) + if len(userIdStrings) == 0 { http.Error(response, "no users to add", http.StatusBadRequest) return } + clientIds := make([]uint32, 0, len(userIdStrings)) + for _, s := range userIdStrings { + id, err := ConvertStringUint32(strings.TrimSpace(s)) + if err != nil { + continue + } + clientIds = append(clientIds, id) + } + if len(clientIds) == 0 { + http.Error(response, "no valid users", http.StatusBadRequest) + return + } + + err = DbAddClientsToGroup(ctx, group.Id, clientIds) + if err != nil { + http.Error(response, "internal server error", http.StatusInternalServerError) + return + } }