forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore_group.go
2155 lines (1917 loc) · 77.8 KB
/
core_group.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"context"
"database/sql"
"encoding/base64"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"github.com/heroiclabs/nakama-common/runtime"
"math"
"strconv"
"strings"
"time"
"github.com/gofrs/uuid"
"github.com/heroiclabs/nakama-common/api"
"github.com/heroiclabs/nakama-common/rtapi"
"github.com/jackc/pgconn"
"github.com/jackc/pgtype"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
"google.golang.org/protobuf/types/known/wrapperspb"
)
var ErrEmptyMemberDemote = errors.New("could not demote member")
var ErrEmptyMemberPromote = errors.New("could not promote member")
var ErrEmptyMemberKick = errors.New("could not kick member")
type groupListCursor struct {
Lang string
EdgeCount int32
ID uuid.UUID
Open bool
Name string
UpdateTime int64
}
func (c *groupListCursor) GetState() int {
if c.Open {
return 1
}
return 0
}
func (c *groupListCursor) GetUpdateTime() time.Time {
return time.Unix(c.UpdateTime, 0)
}
func CreateGroup(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, creatorID uuid.UUID, name, lang, desc, avatarURL, metadata string, open bool, maxCount int) (*api.Group, error) {
if userID == uuid.Nil {
return nil, runtime.ErrGroupCreatorInvalid
}
state := 1
if open {
state = 0
}
params := []interface{}{uuid.Must(uuid.NewV4()), creatorID, name, desc, avatarURL, state}
statements := []string{"$1", "$2", "$3", "$4", "$5", "$6"}
query := "INSERT INTO groups(id, creator_id, name, description, avatar_url, state"
// Add lang tag if any.
if lang != "" {
query += ", lang_tag"
params = append(params, lang)
statements = append(statements, "$"+strconv.Itoa(len(params)))
}
// Add max count if any.
if maxCount > 0 {
query += ", max_count"
params = append(params, maxCount)
statements = append(statements, "$"+strconv.Itoa(len(params)))
}
// Add metadata if any.
if metadata != "" {
query += ", metadata"
params = append(params, metadata)
statements = append(statements, "$"+strconv.Itoa(len(params)))
}
// Add the trailing edge count value.
query += `, edge_count) VALUES (` + strings.Join(statements, ",") + `,1)
RETURNING id, creator_id, name, description, avatar_url, state, edge_count, lang_tag, max_count, metadata, create_time, update_time`
var group *api.Group
tx, err := db.BeginTx(ctx, nil)
if err != nil {
logger.Error("Could not begin database transaction.", zap.Error(err))
return nil, err
}
if err = ExecuteInTx(ctx, tx, func() error {
rows, err := tx.QueryContext(ctx, query, params...)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == dbErrorUniqueViolation {
logger.Info("Could not create group as it already exists.", zap.String("name", name))
return runtime.ErrGroupNameInUse
}
logger.Debug("Could not create group.", zap.Error(err))
return err
}
// Rows closed in groupConvertRows()
groups, err := groupConvertRows(rows, 1)
if err != nil {
logger.Debug("Could not parse rows.", zap.Error(err))
return err
}
group = groups[0]
_, err = groupAddUser(ctx, db, tx, uuid.Must(uuid.FromString(group.Id)), userID, 0)
if err != nil {
logger.Debug("Could not add user to group.", zap.Error(err))
return err
}
return nil
}); err != nil {
if err == runtime.ErrGroupNameInUse {
return nil, runtime.ErrGroupNameInUse
}
logger.Error("Error creating group.", zap.Error(err))
return nil, err
}
logger.Info("Group created.", zap.String("group_id", group.Id), zap.String("user_id", userID.String()))
return group, nil
}
func UpdateGroup(ctx context.Context, logger *zap.Logger, db *sql.DB, groupID uuid.UUID, userID uuid.UUID, creatorID uuid.UUID, name, lang, desc, avatar, metadata *wrapperspb.StringValue, open *wrapperspb.BoolValue, maxCount int) error {
if userID != uuid.Nil {
allowedUser, err := groupCheckUserPermission(ctx, logger, db, groupID, userID, 1)
if err != nil {
return err
}
if !allowedUser {
logger.Info("User does not have permission to update group.", zap.String("group", groupID.String()), zap.String("user", userID.String()))
return runtime.ErrGroupPermissionDenied
}
}
statements := make([]string, 0)
params := []interface{}{groupID}
index := 2
if name != nil {
statements = append(statements, "name = $"+strconv.Itoa(index))
params = append(params, name.GetValue())
index++
}
if lang != nil {
statements = append(statements, "lang_tag = $"+strconv.Itoa(index))
params = append(params, lang.GetValue())
index++
}
if desc != nil {
if u := desc.GetValue(); u == "" {
statements = append(statements, "description = NULL")
} else {
statements = append(statements, "description = $"+strconv.Itoa(index))
params = append(params, u)
index++
}
}
if avatar != nil {
if u := avatar.GetValue(); u == "" {
statements = append(statements, "avatar_url = NULL")
} else {
statements = append(statements, "avatar_url = $"+strconv.Itoa(index))
params = append(params, u)
index++
}
}
if open != nil {
state := 0
if !open.GetValue() {
state = 1
}
statements = append(statements, "state = $"+strconv.Itoa(index))
params = append(params, state)
index++
}
if metadata != nil {
statements = append(statements, "metadata = $"+strconv.Itoa(index))
params = append(params, metadata.GetValue())
index++
}
if maxCount >= 1 {
statements = append(statements, "max_count = $"+strconv.Itoa(index))
params = append(params, maxCount)
index++
}
if creatorID != uuid.Nil {
statements = append(statements, "creator_id = $"+strconv.Itoa(index))
params = append(params, creatorID)
}
if len(statements) == 0 {
logger.Info("Did not update group as no fields were changed.")
return runtime.ErrGroupNoUpdateOps
}
query := "UPDATE groups SET update_time = now(), " + strings.Join(statements, ", ") + " WHERE (id = $1) AND (disable_time = '1970-01-01 00:00:00 UTC')"
res, err := db.ExecContext(ctx, query, params...)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == dbErrorUniqueViolation {
logger.Info("Could not update group as it already exists.", zap.String("group_id", groupID.String()))
return runtime.ErrGroupNameInUse
}
logger.Error("Could not update group.", zap.Error(err))
return err
}
rowsAffected, err := res.RowsAffected()
if err != nil {
logger.Error("Could not get rows affected after group update query.", zap.Error(err))
return err
}
if rowsAffected == 0 {
return runtime.ErrGroupNotUpdated
}
logger.Info("Group updated.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return nil
}
func DeleteGroup(ctx context.Context, logger *zap.Logger, db *sql.DB, groupID uuid.UUID, userID uuid.UUID) error {
if userID != uuid.Nil {
// only super-admins can delete group.
allowedUser, err := groupCheckUserPermission(ctx, logger, db, groupID, userID, 0)
if err != nil {
return err
}
if !allowedUser {
logger.Info("User does not have permission to delete group.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return runtime.ErrGroupPermissionDenied
}
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
logger.Error("Could not begin database transaction.", zap.Error(err))
return err
}
if err = ExecuteInTx(ctx, tx, func() error {
return deleteGroup(ctx, logger, tx, groupID)
}); err != nil {
logger.Error("Error deleting group.", zap.Error(err))
return err
}
logger.Info("Group deleted.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return nil
}
func JoinGroup(ctx context.Context, logger *zap.Logger, db *sql.DB, router MessageRouter, groupID uuid.UUID, userID uuid.UUID, username string) error {
query := `
SELECT id, creator_id, name, description, avatar_url, state, edge_count, lang_tag, max_count, metadata, create_time, update_time
FROM groups
WHERE (id = $1) AND (disable_time = '1970-01-01 00:00:00 UTC')`
rows, err := db.QueryContext(ctx, query, groupID)
if err != nil {
logger.Error("Could not look up group while trying to join it.", zap.Error(err))
return err
}
// Rows closed in groupConvertRows()
groups, err := groupConvertRows(rows, 1)
if err != nil {
logger.Error("Could not parse groups.", zap.Error(err))
return err
}
if len(groups) == 0 {
logger.Info("Group does not exist.", zap.Error(err), zap.String("group_id", groupID.String()))
return runtime.ErrGroupNotFound
}
group := groups[0]
if group.EdgeCount >= group.MaxCount {
logger.Info("Group maximum count has reached.", zap.Error(err), zap.String("group_id", groupID.String()))
return runtime.ErrGroupFull
}
state := 2
if !group.Open.Value {
state = 3
_, err = groupAddUser(ctx, db, nil, uuid.Must(uuid.FromString(group.Id)), userID, state)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == dbErrorUniqueViolation {
logger.Info("Could not add user to group as relationship already exists.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return nil // completed successfully
}
logger.Error("Could not add user to group.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return err
}
// If it's a private group notify superadmins/admins that someone has requested to join.
// Prepare notification data.
notificationContentBytes, err := json.Marshal(map[string]string{"group_id": groupID.String(), "username": username})
if err != nil {
logger.Error("Could not encode notification content.", zap.Error(err))
} else {
notificationContent := string(notificationContentBytes)
notificationSubject := fmt.Sprintf("User %v wants to join your group", username)
notifications := make(map[uuid.UUID][]*api.Notification)
query = "SELECT destination_id FROM group_edge WHERE source_id = $1::UUID AND (state = 0 OR state = 1)"
rows, err := db.QueryContext(ctx, query, groupID)
if err != nil {
// Errors here will not cause the join operation to fail.
logger.Error("Error looking up group admins to notify of join request.", zap.Error(err))
} else {
for rows.Next() {
var id string
if err = rows.Scan(&id); err != nil {
// Errors here will not cause the join operation to fail.
logger.Error("Error reading up group admins to notify of join request.", zap.Error(err))
break
}
adminID := uuid.FromStringOrNil(id)
notifications[adminID] = []*api.Notification{
{
Id: uuid.Must(uuid.NewV4()).String(),
Subject: notificationSubject,
Content: notificationContent,
SenderId: userID.String(),
Code: NotificationCodeGroupJoinRequest,
Persistent: true,
CreateTime: ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()},
},
}
}
_ = rows.Close()
}
if len(notifications) > 0 {
// Any error is already logged before it's returned here.
_ = NotificationSend(ctx, logger, db, router, notifications)
}
}
logger.Info("Added join request to group.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return nil
}
// Prepare the message we'll need to send to the group channel.
stream := PresenceStream{
Mode: StreamModeGroup,
Subject: groupID,
}
channelID, err := StreamToChannelId(stream)
if err != nil {
logger.Error("Could not create channel ID.", zap.Error(err))
return err
}
ts := time.Now().Unix()
message := &api.ChannelMessage{
ChannelId: channelID,
MessageId: uuid.Must(uuid.NewV4()).String(),
Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeGroupJoin},
SenderId: userID.String(),
Username: username,
Content: "{}",
CreateTime: ×tamppb.Timestamp{Seconds: ts},
UpdateTime: ×tamppb.Timestamp{Seconds: ts},
Persistent: &wrapperspb.BoolValue{Value: true},
GroupId: group.Id,
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
logger.Error("Could not begin database transaction.", zap.Error(err))
return err
}
if err = ExecuteInTx(ctx, tx, func() error {
if _, err = groupAddUser(ctx, db, tx, uuid.Must(uuid.FromString(group.Id)), userID, state); err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == dbErrorUniqueViolation {
logger.Info("Could not add user to group as relationship already exists.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return pgErr
}
logger.Debug("Could not add user to group.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return err
}
query = "UPDATE groups SET edge_count = edge_count + 1, update_time = now() WHERE id = $1::UUID AND edge_count+1 <= max_count"
if _, err = tx.ExecContext(ctx, query, groupID); err != nil {
logger.Debug("Could not update group edge_count.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return err
}
query = `INSERT INTO message (id, code, sender_id, username, stream_mode, stream_subject, stream_descriptor, stream_label, content, create_time, update_time)
VALUES ($1, $2, $3, $4, $5, $6::UUID, $7::UUID, $8, $9, $10, $10)`
if _, err = tx.ExecContext(ctx, query, message.MessageId, message.Code.Value, message.SenderId, message.Username, stream.Mode, stream.Subject, stream.Subcontext, stream.Label, message.Content, time.Unix(message.CreateTime.Seconds, 0).UTC()); err != nil {
logger.Debug("Could insert group join channel message.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return err
}
return nil
}); err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == dbErrorUniqueViolation {
// No-op, user was already in group.
return nil
}
logger.Error("Error joining group.", zap.Error(err))
return err
}
router.SendToStream(logger, stream, &rtapi.Envelope{Message: &rtapi.Envelope_ChannelMessage{ChannelMessage: message}}, true)
logger.Info("Successfully joined group.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return nil
}
func LeaveGroup(ctx context.Context, logger *zap.Logger, db *sql.DB, router MessageRouter, groupID uuid.UUID, userID uuid.UUID, username string) error {
var myState sql.NullInt64
query := "SELECT state FROM group_edge WHERE source_id = $1::UUID AND destination_id = $2::UUID"
if err := db.QueryRowContext(ctx, query, groupID, userID).Scan(&myState); err != nil {
if err == sql.ErrNoRows {
logger.Info("Could not retrieve state as no group relationship exists.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return nil // Completed successfully.
}
logger.Error("Could not retrieve state from group_edge.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return err
}
if myState.Int64 == 0 {
// check for other superadmins
var otherSuperadminCount sql.NullInt64
query := "SELECT COUNT(destination_id) FROM group_edge WHERE source_id = $1::UUID AND destination_id != $2::UUID AND state = 0"
if err := db.QueryRowContext(ctx, query, groupID, userID).Scan(&otherSuperadminCount); err != nil {
logger.Error("Could not look up superadmin count group_edge.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return err
}
if otherSuperadminCount.Int64 == 0 {
logger.Info("Cannot leave group as user is last superadmin.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return runtime.ErrGroupLastSuperadmin
}
}
// Prepare the message we'll need to send to the group channel.
stream := PresenceStream{
Mode: StreamModeGroup,
Subject: groupID,
}
channelID, err := StreamToChannelId(stream)
if err != nil {
logger.Error("Could not create channel ID.", zap.Error(err))
return err
}
ts := time.Now().Unix()
message := &api.ChannelMessage{
ChannelId: channelID,
MessageId: uuid.Must(uuid.NewV4()).String(),
Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeGroupLeave},
SenderId: userID.String(),
Username: username,
Content: "{}",
CreateTime: ×tamppb.Timestamp{Seconds: ts},
UpdateTime: ×tamppb.Timestamp{Seconds: ts},
Persistent: &wrapperspb.BoolValue{Value: true},
GroupId: groupID.String(),
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
logger.Error("Could not begin database transaction.", zap.Error(err))
return err
}
if err := ExecuteInTx(ctx, tx, func() error {
query = "DELETE FROM group_edge WHERE (source_id = $1::UUID AND destination_id = $2::UUID) OR (source_id = $2::UUID AND destination_id = $1::UUID)"
// don't need to check affectedRows as we've confirmed the existence of the relationship above
if _, err = tx.ExecContext(ctx, query, groupID, userID); err != nil {
logger.Debug("Could not delete group_edge relationships.", zap.Error(err))
return err
}
// check to ensure we are not decrementing the count when the relationship was an invite.
if myState.Int64 < 3 {
query = "UPDATE groups SET edge_count = edge_count - 1, update_time = now() WHERE (id = $1::UUID) AND (disable_time = '1970-01-01 00:00:00 UTC')"
res, err := tx.ExecContext(ctx, query, groupID)
if err != nil {
logger.Debug("Could not update group edge_count.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return err
}
rowsAffected, err := res.RowsAffected()
if err != nil {
logger.Debug("Could not fetch affected rows.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return err
}
if rowsAffected == 0 {
logger.Debug("Did not update group edge_count as group is disabled.")
return runtime.ErrGroupNotFound
}
}
query = `INSERT INTO message (id, code, sender_id, username, stream_mode, stream_subject, stream_descriptor, stream_label, content, create_time, update_time)
VALUES ($1, $2, $3, $4, $5, $6::UUID, $7::UUID, $8, $9, $10, $10)`
if _, err = tx.ExecContext(ctx, query, message.MessageId, message.Code.Value, message.SenderId, message.Username, stream.Mode, stream.Subject, stream.Subcontext, stream.Label, message.Content, time.Unix(message.CreateTime.Seconds, 0).UTC()); err != nil {
logger.Debug("Could insert group leave channel message.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return err
}
return nil
}); err != nil {
logger.Error("Error leaving group.", zap.Error(err))
return err
}
router.SendToStream(logger, stream, &rtapi.Envelope{Message: &rtapi.Envelope_ChannelMessage{ChannelMessage: message}}, true)
logger.Info("Successfully left group.", zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
return nil
}
func AddGroupUsers(ctx context.Context, logger *zap.Logger, db *sql.DB, router MessageRouter, caller uuid.UUID, groupID uuid.UUID, userIDs []uuid.UUID) error {
if caller != uuid.Nil {
var dbState sql.NullInt64
query := "SELECT state FROM group_edge WHERE source_id = $1::UUID AND destination_id = $2::UUID"
if err := db.QueryRowContext(ctx, query, groupID, caller).Scan(&dbState); err != nil {
if err == sql.ErrNoRows {
logger.Info("Could not retrieve state as no group relationship exists.", zap.String("group_id", groupID.String()), zap.String("user_id", caller.String()))
return runtime.ErrGroupPermissionDenied
}
logger.Error("Could not retrieve state from group_edge.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", caller.String()))
return err
}
if dbState.Int64 > 1 {
logger.Info("Cannot add users as user does not have correct permissions.", zap.String("group_id", groupID.String()), zap.String("user_id", caller.String()), zap.Int64("state", dbState.Int64))
return runtime.ErrGroupPermissionDenied
}
}
var groupName sql.NullString
query := "SELECT name FROM groups WHERE id = $1 AND disable_time = '1970-01-01 00:00:00 UTC'"
if err := db.QueryRowContext(ctx, query, groupID).Scan(&groupName); err != nil {
if err == sql.ErrNoRows {
logger.Info("Cannot add users to disabled group.", zap.String("group_id", groupID.String()))
return runtime.ErrGroupNotFound
}
logger.Error("Could not look up group when adding users.", zap.Error(err), zap.String("group_id", groupID.String()))
return err
}
// Prepare notification data.
notificationContentBytes, err := json.Marshal(map[string]string{"group_id": groupID.String(), "name": groupName.String})
if err != nil {
logger.Error("Could not encode notification content.", zap.Error(err))
return err
}
notificationContent := string(notificationContentBytes)
notificationSubject := fmt.Sprintf("You've been added to group %v", groupName.String)
var notifications map[uuid.UUID][]*api.Notification
// Prepare the messages we'll need to send to the group channel.
stream := PresenceStream{
Mode: StreamModeGroup,
Subject: groupID,
}
channelID, err := StreamToChannelId(stream)
if err != nil {
logger.Error("Could not create channel ID.", zap.Error(err))
return err
}
ts := time.Now().Unix()
var messages []*api.ChannelMessage
tx, err := db.BeginTx(ctx, nil)
if err != nil {
logger.Error("Could not begin database transaction.", zap.Error(err))
return err
}
if err := ExecuteInTx(ctx, tx, func() error {
// If the transaction is retried ensure we wipe any notifications/messages that may have been prepared by previous attempts.
notifications = make(map[uuid.UUID][]*api.Notification, len(userIDs))
messages = make([]*api.ChannelMessage, 0, len(userIDs))
for _, uid := range userIDs {
if uid == caller {
continue
}
// Look up the username, and implicitly if this user exists.
var username sql.NullString
query := "SELECT username FROM users WHERE id = $1::UUID"
if err := tx.QueryRowContext(ctx, query, uid).Scan(&username); err != nil {
if err == sql.ErrNoRows {
return runtime.ErrGroupUserNotFound
}
logger.Debug("Could not retrieve username to add user to group.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
}
// Check if this is a join request being accepted.
incrementEdgeCount := true
var userExists sql.NullBool
query = "SELECT EXISTS(SELECT 1 FROM group_edge WHERE source_id = $1::UUID AND destination_id = $2::UUID)"
if err := tx.QueryRowContext(ctx, query, groupID, uid).Scan(&userExists); err != nil {
logger.Debug("Could not retrieve user state from group_edge.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
}
if !userExists.Bool {
if _, err = groupAddUser(ctx, db, tx, groupID, uid, 2); err != nil {
logger.Debug("Could not add user to group.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
}
} else {
res, err := groupUpdateUserState(ctx, db, tx, groupID, uid, 3, 2)
if err != nil {
logger.Debug("Could not update user state in group_edge.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
}
if res != 2 {
incrementEdgeCount = false
}
}
if incrementEdgeCount {
query = "UPDATE groups SET edge_count = edge_count + 1, update_time = now() WHERE id = $1::UUID AND edge_count+1 <= max_count"
res, err := tx.ExecContext(ctx, query, groupID)
if err != nil {
logger.Debug("Could not update group edge_count.", zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
}
if rowsAffected, err := res.RowsAffected(); err != nil {
logger.Debug("Could not update group edge_count.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
} else if rowsAffected == 0 {
logger.Info("Could not add users as group maximum count was reached.", zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return runtime.ErrGroupFull
}
} else {
// If we reach here then this was a repeated (or failed, if the user was banned) operation.
// No need to send a message to the channel.
continue
}
message := &api.ChannelMessage{
ChannelId: channelID,
MessageId: uuid.Must(uuid.NewV4()).String(),
Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeGroupAdd},
SenderId: uid.String(),
Username: username.String,
Content: "{}",
CreateTime: ×tamppb.Timestamp{Seconds: ts},
UpdateTime: ×tamppb.Timestamp{Seconds: ts},
Persistent: &wrapperspb.BoolValue{Value: true},
GroupId: groupID.String(),
}
query = `INSERT INTO message (id, code, sender_id, username, stream_mode, stream_subject, stream_descriptor, stream_label, content, create_time, update_time)
VALUES ($1, $2, $3, $4, $5, $6::UUID, $7::UUID, $8, $9, $10, $10)`
if _, err = tx.ExecContext(ctx, query, message.MessageId, message.Code.Value, message.SenderId, message.Username, stream.Mode, stream.Subject, stream.Subcontext, stream.Label, message.Content, time.Unix(message.CreateTime.Seconds, 0).UTC()); err != nil {
logger.Debug("Could insert group add channel message.", zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
}
messages = append(messages, message)
notifications[uid] = []*api.Notification{
{
Id: uuid.Must(uuid.NewV4()).String(),
Subject: notificationSubject,
Content: notificationContent,
SenderId: caller.String(),
Code: NotificationCodeGroupAdd,
Persistent: true,
CreateTime: ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()},
},
}
}
return nil
}); err != nil {
return err
}
for _, message := range messages {
router.SendToStream(logger, stream, &rtapi.Envelope{Message: &rtapi.Envelope_ChannelMessage{ChannelMessage: message}}, true)
}
if len(notifications) > 0 {
// Any error is already logged before it's returned here.
_ = NotificationSend(ctx, logger, db, router, notifications)
}
return nil
}
func BanGroupUsers(ctx context.Context, logger *zap.Logger, db *sql.DB, router MessageRouter, caller uuid.UUID, groupID uuid.UUID, userIDs []uuid.UUID) error {
myState := 0
if caller != uuid.Nil {
var dbState sql.NullInt64
query := "SELECT state FROM group_edge WHERE source_id = $1::UUID AND destination_id = $2::UUID"
if err := db.QueryRowContext(ctx, query, groupID, caller).Scan(&dbState); err != nil {
if err == sql.ErrNoRows {
logger.Info("Could not retrieve state as no group relationship exists.", zap.String("group_id", groupID.String()), zap.String("user_id", caller.String()))
return runtime.ErrGroupPermissionDenied
}
logger.Error("Could not retrieve state from group_edge.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", caller.String()))
return err
}
myState = int(dbState.Int64)
if myState > 1 {
logger.Info("Cannot ban users as user does not have correct permissions.", zap.String("group_id", groupID.String()), zap.String("user_id", caller.String()), zap.Int("state", myState))
return runtime.ErrGroupPermissionDenied
}
}
// Prepare the messages we'll need to send to the group channel.
stream := PresenceStream{
Mode: StreamModeGroup,
Subject: groupID,
}
channelID, err := StreamToChannelId(stream)
if err != nil {
logger.Error("Could not create channel ID.", zap.Error(err))
return err
}
ts := time.Now().Unix()
var messages []*api.ChannelMessage
tx, err := db.BeginTx(ctx, nil)
if err != nil {
logger.Error("Could not begin database transaction.", zap.Error(err))
return err
}
if err := ExecuteInTx(ctx, tx, func() error {
// If the transaction is retried ensure we wipe any messages that may have been prepared by previous attempts.
messages = make([]*api.ChannelMessage, 0, len(userIDs))
// Position to use for new banned edges.
position := time.Now().UTC().UnixNano()
for _, uid := range userIDs {
// Shouldn't ban self.
if uid == caller {
continue
}
params := []interface{}{groupID, uid}
query := ""
if myState == 0 {
// Ensure we aren't banning the last superadmin when deleting authoritatively.
// Query is for superadmin or if done authoritatively.
query = `
DELETE FROM group_edge
WHERE
(
(source_id = $1::UUID AND destination_id = $2::UUID)
OR
(source_id = $2::UUID AND destination_id = $1::UUID)
)
AND
EXISTS (SELECT id FROM groups WHERE id = $1::UUID AND disable_time = '1970-01-01 00:00:00 UTC')
AND
NOT (
(EXISTS (SELECT 1 FROM group_edge WHERE source_id = $1::UUID AND destination_id = $2::UUID AND state = 0))
AND
((SELECT COUNT(destination_id) FROM group_edge WHERE (source_id = $1::UUID AND destination_id != $2::UUID AND state = 0)) = 0)
)
RETURNING state`
} else {
// Query is just for admins.
query = `
DELETE FROM group_edge
WHERE
(
(source_id = $1::UUID AND destination_id = $2::UUID AND state > 1)
OR
(source_id = $2::UUID AND destination_id = $1::UUID AND state > 1)
)
AND
EXISTS (SELECT id FROM groups WHERE id = $1::UUID AND disable_time = '1970-01-01 00:00:00 UTC')
RETURNING state`
}
var deletedState sql.NullInt64
logger.Debug("Ban user from group query.", zap.String("query", query), zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()), zap.String("caller", caller.String()), zap.Int("caller_state", myState))
if err := tx.QueryRowContext(ctx, query, params...).Scan(&deletedState); err != nil {
if err == sql.ErrNoRows {
// Ignore - move to the next user ID.
continue
}
logger.Debug("Could not delete relationship from group_edge.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
}
query = `
INSERT INTO group_edge (position, state, source_id, destination_id) VALUES ($1, $2, $3, $4)
ON CONFLICT (source_id, state, position) DO
UPDATE SET state = $2, update_time = now()`
_, err := tx.ExecContext(ctx, query, position, 4, groupID, uid)
if err != nil {
logger.Debug("Could not add banned relationship in group_edge.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
}
// Only update group edge count and send messages when we kicked valid members, not invites.
if deletedState.Int64 < 3 {
query = "UPDATE groups SET edge_count = edge_count - 1, update_time = now() WHERE id = $1::UUID"
_, err = tx.ExecContext(ctx, query, groupID)
if err != nil {
logger.Debug("Could not update group edge_count.", zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
}
// Look up the username.
var username sql.NullString
query = "SELECT username FROM users WHERE id = $1::UUID"
if err := tx.QueryRowContext(ctx, query, uid).Scan(&username); err != nil {
if err == sql.ErrNoRows {
return runtime.ErrGroupUserNotFound
}
logger.Debug("Could not retrieve username to ban user from group.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
}
message := &api.ChannelMessage{
ChannelId: channelID,
MessageId: uuid.Must(uuid.NewV4()).String(),
Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeGroupBan},
SenderId: uid.String(),
Username: username.String,
Content: "{}",
CreateTime: ×tamppb.Timestamp{Seconds: ts},
UpdateTime: ×tamppb.Timestamp{Seconds: ts},
Persistent: &wrapperspb.BoolValue{Value: true},
GroupId: groupID.String(),
}
query = `INSERT INTO message (id, code, sender_id, username, stream_mode, stream_subject, stream_descriptor, stream_label, content, create_time, update_time)
VALUES ($1, $2, $3, $4, $5, $6::UUID, $7::UUID, $8, $9, $10, $10)`
if _, err = tx.ExecContext(ctx, query, message.MessageId, message.Code.Value, message.SenderId, message.Username, stream.Mode, stream.Subject, stream.Subcontext, stream.Label, message.Content, time.Unix(message.CreateTime.Seconds, 0).UTC()); err != nil {
logger.Debug("Could insert group ban channel message.", zap.String("group_id", groupID.String()), zap.String("user_id", uid.String()))
return err
}
messages = append(messages, message)
}
}
return nil
}); err != nil {
logger.Error("Error banning users from group.", zap.Error(err))
return err
}
for _, message := range messages {
router.SendToStream(logger, stream, &rtapi.Envelope{Message: &rtapi.Envelope_ChannelMessage{ChannelMessage: message}}, true)
}
return nil
}
func KickGroupUsers(ctx context.Context, logger *zap.Logger, db *sql.DB, router MessageRouter, caller uuid.UUID, groupID uuid.UUID, userIDs []uuid.UUID) error {
myState := 0
if caller != uuid.Nil {
var dbState sql.NullInt64
query := "SELECT state FROM group_edge WHERE source_id = $1::UUID AND destination_id = $2::UUID"
if err := db.QueryRowContext(ctx, query, groupID, caller).Scan(&dbState); err != nil {
if err == sql.ErrNoRows {
logger.Info("Could not retrieve state as no group relationship exists.", zap.String("group_id", groupID.String()), zap.String("user_id", caller.String()))
return runtime.ErrGroupPermissionDenied
}
logger.Error("Could not retrieve state from group_edge.", zap.Error(err), zap.String("group_id", groupID.String()), zap.String("user_id", caller.String()))
return err
}
myState = int(dbState.Int64)
if myState > 1 {
logger.Info("Cannot kick users as user does not have correct permissions.", zap.String("group_id", groupID.String()), zap.String("user_id", caller.String()), zap.Int("state", myState))
return runtime.ErrGroupPermissionDenied
}
}
var groupExists sql.NullBool
query := "SELECT EXISTS (SELECT id FROM groups WHERE id = $1 AND disable_time = '1970-01-01 00:00:00 UTC')"
err := db.QueryRowContext(ctx, query, groupID).Scan(&groupExists)
if err != nil {
logger.Error("Could not look up group when kicking users.", zap.Error(err), zap.String("group_id", groupID.String()))
return err
}
if !groupExists.Bool {
logger.Info("Cannot kick users in a disabled group.", zap.String("group_id", groupID.String()))
return runtime.ErrGroupNotFound
}
// Prepare the messages we'll need to send to the group channel.
stream := PresenceStream{
Mode: StreamModeGroup,
Subject: groupID,
}
channelID, err := StreamToChannelId(stream)
if err != nil {
logger.Error("Could not create channel ID.", zap.Error(err))
return err
}
ts := time.Now().Unix()
var messages []*api.ChannelMessage
tx, err := db.BeginTx(ctx, nil)
if err != nil {
logger.Error("Could not begin database transaction.", zap.Error(err))
return err
}
if err := ExecuteInTx(ctx, tx, func() error {
// If the transaction is retried ensure we wipe any messages that may have been prepared by previous attempts.
messages = make([]*api.ChannelMessage, 0, len(userIDs))
for _, uid := range userIDs {
// Shouldn't kick self.
if uid == caller {
continue
}
params := []interface{}{groupID, uid}
query := ""
if myState == 0 {
// Ensure we aren't removing the last superadmin when deleting authoritatively.
// Query is for superadmin or if done authoritatively.
query = `
DELETE FROM group_edge
WHERE
(
(source_id = $1::UUID AND destination_id = $2::UUID)
OR
(source_id = $2::UUID AND destination_id = $1::UUID)
)
AND
EXISTS (SELECT id FROM groups WHERE id = $1::UUID AND disable_time = '1970-01-01 00:00:00 UTC')
AND
NOT (
(EXISTS (SELECT 1 FROM group_edge WHERE source_id = $1::UUID AND destination_id = $2::UUID AND state = 0))
AND
((SELECT COUNT(destination_id) FROM group_edge WHERE (source_id = $1::UUID AND destination_id != $2::UUID AND state = 0)) = 0)
)
RETURNING state`
} else {
// Query is just for admins.
query = `
DELETE FROM group_edge
WHERE
(
(source_id = $1::UUID AND destination_id = $2::UUID AND state > 1)
OR
(source_id = $2::UUID AND destination_id = $1::UUID AND state > 1)