forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipeline_group.go
1055 lines (906 loc) · 31.3 KB
/
pipeline_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 2017 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"
"database/sql"
"encoding/gob"
"encoding/json"
"errors"
"strconv"
"strings"
"github.com/lib/pq"
"github.com/satori/go.uuid"
"github.com/uber-go/zap"
)
type scanner interface {
Scan(dest ...interface{}) error
}
type groupCursor struct {
Primary interface{}
Secondary int64
GroupID []byte
}
func (p *pipeline) extractGroup(r scanner) (*Group, error) {
var id []byte
var creatorID []byte
var name sql.NullString
var description sql.NullString
var avatarURL sql.NullString
var lang sql.NullString
var utcOffsetMs sql.NullInt64
var metadata []byte
var state sql.NullInt64
var count sql.NullInt64
var createdAt sql.NullInt64
var updatedAt sql.NullInt64
err := r.Scan(&id, &creatorID, &name,
&description, &avatarURL, &lang,
&utcOffsetMs, &metadata, &state,
&count, &createdAt, &updatedAt)
if err != nil {
return &Group{}, err
}
desc := ""
if description.Valid {
desc = description.String
}
avatar := ""
if avatarURL.Valid {
avatar = avatarURL.String
}
private := state.Int64 == 1
return &Group{
Id: id,
CreatorId: creatorID,
Name: name.String,
Description: desc,
AvatarUrl: avatar,
Lang: lang.String,
UtcOffsetMs: utcOffsetMs.Int64,
Metadata: metadata,
Private: private,
Count: count.Int64,
CreatedAt: createdAt.Int64,
UpdatedAt: updatedAt.Int64,
}, nil
}
func (p *pipeline) groupCreate(logger zap.Logger, session *session, envelope *Envelope) {
g := envelope.GetGroupCreate()
if g.Name == "" {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Group name is mandatory."))
return
}
var group *Group
tx, err := p.db.Begin()
if err != nil {
logger.Error("Could not create group", zap.Error(err))
session.Send(ErrorMessageBadInput(envelope.CollationId, "Could not create group"))
return
}
defer func() {
if err != nil {
logger.Error("Could not create group", zap.Error(err))
if tx != nil {
txErr := tx.Rollback()
if txErr != nil {
logger.Error("Could not rollback transaction", zap.Error(txErr))
}
}
if strings.HasSuffix(err.Error(), "violates unique constraint \"groups_name_key\"") {
session.Send(ErrorMessage(envelope.CollationId, GROUP_NAME_INUSE, "Name is in use"))
} else {
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not create group"))
}
} else {
err = tx.Commit()
if err != nil {
logger.Error("Could not commit transaction", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not create group"))
} else {
logger.Info("Created new group", zap.String("name", group.Name))
session.Send(&Envelope{CollationId: envelope.CollationId, Payload: &Envelope_Group{Group: &TGroup{Group: group}}})
}
}
}()
state := 0
if g.Private {
state = 1
}
columns := make([]string, 0)
params := make([]string, 0)
values := make([]interface{}, 5)
updatedAt := nowMs()
values[0] = uuid.NewV4().Bytes()
values[1] = session.userID.Bytes()
values[2] = g.Name
values[3] = state
values[4] = updatedAt
if g.Description != "" {
columns = append(columns, "description")
params = append(params, "$"+strconv.Itoa(len(values)+1))
values = append(values, g.Description)
}
if g.AvatarUrl != "" {
columns = append(columns, "avatar_url")
params = append(params, "$"+strconv.Itoa(len(values)+1))
values = append(values, g.AvatarUrl)
}
if g.Lang != "" {
columns = append(columns, "lang")
params = append(params, "$"+strconv.Itoa(len(values)+1))
values = append(values, g.Lang)
}
if g.Metadata != nil {
// Make this `var js interface{}` if we want to allow top-level JSON arrays.
var maybeJSON map[string]interface{}
if json.Unmarshal(g.Metadata, &maybeJSON) != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Metadata must be a valid JSON object"))
return
}
columns = append(columns, "metadata")
params = append(params, "$"+strconv.Itoa(len(values)))
values = append(values, g.Metadata)
}
r := tx.QueryRow(`
INSERT INTO groups (id, creator_id, name, state, created_at, updated_at, `+strings.Join(columns, ", ")+")"+`
VALUES ($1, $2, $3, $4, $5, $5, `+strings.Join(params, ",")+")"+`
RETURNING id, creator_id, name, description, avatar_url, lang, utc_offset_ms, metadata, state, count, created_at, updated_at
`, values...)
group, err = p.extractGroup(r)
if err != nil {
return
}
res, err := tx.Exec(`
INSERT INTO group_edge (source_id, position, updated_at, destination_id, state)
VALUES ($1, $2, $2, $3, 0), ($3, $2, $2, $1, 0)`,
group.Id, updatedAt, session.userID.Bytes())
if err != nil {
return
}
rowAffected, err := res.RowsAffected()
if err != nil {
return
}
if rowAffected == 0 {
err = errors.New("Could not insert into group_edge table")
return
}
}
func (p *pipeline) groupUpdate(l zap.Logger, session *session, envelope *Envelope) {
//TODO notify members that group has been updated.
g := envelope.GetGroupUpdate()
groupID, err := uuid.FromBytes(g.GroupId)
if err != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Group ID is not valid."))
return
}
// Make this `var js interface{}` if we want to allow top-level JSON arrays.
var maybeJSON map[string]interface{}
if len(g.Metadata) != 0 && json.Unmarshal(g.Metadata, &maybeJSON) != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Metadata must be a valid JSON object"))
return
}
logger := l.With(zap.String("group_id", groupID.String()))
statements := make([]string, 6)
params := make([]interface{}, 8)
params[0] = groupID.Bytes()
params[1] = session.userID.Bytes()
statements[0] = "updated_at = $3"
params[2] = nowMs()
statements[1] = "description = $4"
params[3] = g.Description
statements[2] = "avatar_url = $5"
params[4] = g.AvatarUrl
statements[3] = "lang = $6"
params[5] = g.Lang
statements[4] = "metadata = $7"
params[6] = g.Metadata
statements[5] = "state = $8"
params[7] = 0
if g.Private {
params[7] = 1
}
if g.Name != "" {
statements = append(statements, "name = $"+strconv.Itoa(len(statements)))
params = append(params, g.Name)
}
_, err = p.db.Exec(`
UPDATE groups SET `+strings.Join(statements, ", ")+`
WHERE id = $1 AND
EXISTS (SELECT source_id FROM group_edge WHERE source_id = $1 AND destination_id = $2 AND state = 0)`,
params...)
if err != nil {
if strings.HasSuffix(err.Error(), "violates unique constraint \"groups_name_key\"") {
session.Send(ErrorMessage(envelope.CollationId, GROUP_NAME_INUSE, "Name is in use"))
} else {
logger.Error("Could not update group", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not update group"))
}
return
}
logger.Info("Updated group")
session.Send(&Envelope{CollationId: envelope.CollationId})
}
func (p *pipeline) groupRemove(l zap.Logger, session *session, envelope *Envelope) {
//TODO kick all users out
g := envelope.GetGroupRemove()
groupID, err := uuid.FromBytes(g.GroupId)
if err != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Group ID is not valid."))
return
}
logger := l.With(zap.String("group_id", groupID.String()))
failureReason := "Failed to remove group"
tx, err := p.db.Begin()
if err != nil {
logger.Error("Could not remove group", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, failureReason))
return
}
defer func() {
if err != nil {
logger.Error("Could not remove group", zap.Error(err))
err = tx.Rollback()
if err != nil {
logger.Error("Could not rollback transaction", zap.Error(err))
}
session.Send(ErrorMessageRuntimeException(envelope.CollationId, failureReason))
} else {
err = tx.Commit()
if err != nil {
logger.Error("Could not commit transaction", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, failureReason))
} else {
logger.Info("Removed group")
session.Send(&Envelope{CollationId: envelope.CollationId})
}
}
}()
res, err := tx.Exec(`
DELETE FROM groups
WHERE
id = $1
AND
EXISTS (SELECT source_id FROM group_edge WHERE source_id = $1 AND destination_id = $2 AND state = 0)
`, groupID.Bytes(), session.userID.Bytes())
if err != nil {
return
}
rowAffected, err := res.RowsAffected()
if err != nil {
return
}
if rowAffected == 0 {
err = errors.New("Could not remove group. User may not be group admin or group may not exist")
failureReason = "Could not remove group. Make sure you are a group admin and group exists"
return
}
_, err = tx.Exec("DELETE FROM group_edge WHERE source_id = $1 OR destination_id = $1", groupID.Bytes())
}
func (p *pipeline) groupsFetch(logger zap.Logger, session *session, envelope *Envelope) {
g := envelope.GetGroupsFetch()
statements := []string{}
params := []interface{}{}
switch g.Set.(type) {
case *TGroupsFetch_GroupIds_:
for _, gid := range g.GetGroupIds().GroupIds {
groupID, err := uuid.FromBytes(gid)
if err == nil {
params = append(params, groupID.Bytes())
statements = append(statements, "id = $"+strconv.Itoa(len(params)))
}
}
case *TGroupsFetch_Names_:
for _, name := range g.GetNames().Names {
params = append(params, name)
statements = append(statements, "name = $"+strconv.Itoa(len(params)))
}
case nil:
session.Send(ErrorMessageBadInput(envelope.CollationId, "A fetch set is required"))
return
default:
session.Send(ErrorMessageBadInput(envelope.CollationId, "Unknown fetch set"))
return
}
if len(statements) == 0 {
session.Send(ErrorMessageBadInput(envelope.CollationId, "One or more fetch set values are required"))
return
}
rows, err := p.db.Query(
`SELECT id, creator_id, name, description, avatar_url, lang, utc_offset_ms, metadata, state, count, created_at, updated_at
FROM groups WHERE disabled_at = 0 AND ( `+strings.Join(statements, " OR ")+" )",
params...)
if err != nil {
logger.Error("Could not get groups", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not get groups"))
return
}
defer rows.Close()
groups := make([]*Group, 0)
for rows.Next() {
group, err := p.extractGroup(rows)
if err != nil {
logger.Error("Could not get groups", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not get groups"))
return
}
groups = append(groups, group)
}
session.Send(&Envelope{CollationId: envelope.CollationId, Payload: &Envelope_Groups{Groups: &TGroups{Groups: groups}}})
}
func (p *pipeline) groupsList(logger zap.Logger, session *session, envelope *Envelope) {
incoming := envelope.GetGroupsList()
params := make([]interface{}, 0)
limit := incoming.PageLimit
if limit == 0 {
limit = 10
} else if limit < 10 || limit > 100 {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Page limit must be between 10 and 100"))
return
}
foundCursor := false
paramNumber := 1
if incoming.Cursor != nil {
var c groupCursor
if err := gob.NewDecoder(bytes.NewReader(incoming.Cursor)).Decode(&c); err != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Invalid cursor data"))
return
}
foundCursor = true
params = append(params, c.Primary)
params = append(params, c.Secondary)
params = append(params, c.GroupID)
paramNumber = len(params)
}
orderBy := "DESC"
comparison := "<"
if incoming.OrderByAsc {
orderBy = "ASC"
comparison = ">"
}
cursorQuery := ""
filterQuery := ""
if incoming.GetLang() != "" {
if foundCursor {
cursorQuery = "(lang, count, id) " + comparison + " ($1, $2, $3) AND"
}
filterQuery = "lang >= $" + strconv.Itoa(paramNumber) + " AND"
params = append(params, incoming.GetLang())
} else if incoming.GetCreatedAt() != 0 {
if foundCursor {
cursorQuery = "(created_at, count, id) " + comparison + " ($1, $2, $3) AND"
}
filterQuery = "created_at >= $" + strconv.Itoa(paramNumber) + " AND"
params = append(params, incoming.GetCreatedAt())
} else if incoming.GetCount() != 0 {
if foundCursor {
cursorQuery = "(count, updated_at, id) " + comparison + " ($1, $2, $3) AND"
}
filterQuery = "count <= $" + strconv.Itoa(paramNumber) + " AND"
params = append(params, incoming.GetCount())
}
params = append(params, limit+1)
query := `
SELECT id, creator_id, name, description, avatar_url, lang, utc_offset_ms, metadata, state, count, created_at, updated_at
FROM groups WHERE ` + cursorQuery + " " + filterQuery + " disabled_at = 0" + `
ORDER BY count ` + orderBy + " " + `
LIMIT $` + strconv.Itoa(len(params))
rows, err := p.db.Query(query, params...)
if err != nil {
logger.Error("Could not list groups", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not list groups"))
return
}
defer rows.Close()
groups := make([]*Group, 0)
var cursor []byte
var lastGroup *Group
for rows.Next() {
if int64(len(groups)) >= limit {
cursorBuf := new(bytes.Buffer)
newCursor := &groupCursor{GroupID: lastGroup.Id}
if incoming.GetLang() != "" {
newCursor.Primary = lastGroup.Lang
newCursor.Secondary = lastGroup.Count
} else if incoming.GetCreatedAt() != 0 {
newCursor.Primary = lastGroup.CreatedAt
newCursor.Secondary = lastGroup.Count
} else {
newCursor.Primary = lastGroup.Count
newCursor.Secondary = lastGroup.UpdatedAt
}
if gob.NewEncoder(cursorBuf).Encode(newCursor); err != nil {
logger.Error("Could not create group list cursor", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not list groups"))
return
}
cursor = cursorBuf.Bytes()
break
}
lastGroup, err = p.extractGroup(rows)
if err != nil {
logger.Error("Could not list groups", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not list groups"))
return
}
groups = append(groups, lastGroup)
}
session.Send(&Envelope{CollationId: envelope.CollationId, Payload: &Envelope_Groups{Groups: &TGroups{
Groups: groups,
Cursor: cursor,
}}})
}
func (p *pipeline) groupsSelfList(logger zap.Logger, session *session, envelope *Envelope) {
envelope.GetGroupsSelfList()
rows, err := p.db.Query(`
SELECT id, creator_id, name, description, avatar_url, lang, utc_offset_ms, metadata, groups.state, count, created_at, groups.updated_at
FROM groups
JOIN group_edge ON (group_edge.source_id = id)
WHERE group_edge.destination_id = $1 AND disabled_at = 0 AND (group_edge.state = 1 OR group_edge.state = 0)
`, session.userID.Bytes())
if err != nil {
logger.Error("Could not list joined groups", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not list joined groups"))
return
}
defer rows.Close()
groups := make([]*Group, 0)
var lastGroup *Group
for rows.Next() {
lastGroup, err = p.extractGroup(rows)
if err != nil {
logger.Error("Could not list joined groups", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not list joined groups"))
return
}
groups = append(groups, lastGroup)
}
session.Send(&Envelope{CollationId: envelope.CollationId, Payload: &Envelope_Groups{Groups: &TGroups{Groups: groups}}})
}
func (p *pipeline) groupUsersList(l zap.Logger, session *session, envelope *Envelope) {
g := envelope.GetGroupUsersList()
groupID, err := uuid.FromBytes(g.GroupId)
if err != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Group ID is not valid"))
return
}
logger := l.With(zap.String("group_id", groupID.String()))
query := `
SELECT u.id, u.handle, u.fullname, u.avatar_url,
u.lang, u.location, u.timezone, u.metadata,
u.created_at, u.updated_at, u.last_online_at, ge.state
FROM users u, group_edge ge
WHERE u.id = ge.source_id AND ge.destination_id = $1`
rows, err := p.db.Query(query, groupID.Bytes())
if err != nil {
logger.Error("Could not get group users", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not get group users"))
return
}
defer rows.Close()
users := make([]*GroupUser, 0)
for rows.Next() {
var id []byte
var handle sql.NullString
var fullname sql.NullString
var avatarURL sql.NullString
var lang sql.NullString
var location sql.NullString
var timezone sql.NullString
var metadata []byte
var createdAt sql.NullInt64
var updatedAt sql.NullInt64
var lastOnlineAt sql.NullInt64
var state sql.NullInt64
err = rows.Scan(&id, &handle, &fullname, &avatarURL, &lang, &location, &timezone, &metadata, &createdAt, &updatedAt, &lastOnlineAt, &state)
if err != nil {
logger.Error("Could not get group users", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not get group users"))
return
}
users = append(users, &GroupUser{
User: &User{
Id: id,
Handle: handle.String,
Fullname: fullname.String,
AvatarUrl: avatarURL.String,
Lang: lang.String,
Location: location.String,
Timezone: timezone.String,
Metadata: metadata,
CreatedAt: createdAt.Int64,
UpdatedAt: updatedAt.Int64,
LastOnlineAt: lastOnlineAt.Int64,
},
Type: state.Int64,
})
}
session.Send(&Envelope{CollationId: envelope.CollationId, Payload: &Envelope_GroupUsers{GroupUsers: &TGroupUsers{Users: users}}})
}
func (p *pipeline) groupJoin(l zap.Logger, session *session, envelope *Envelope) {
g := envelope.GetGroupJoin()
groupID, err := uuid.FromBytes(g.GroupId)
if err != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Group ID is not valid."))
return
}
logger := l.With(zap.String("group_id", groupID.String()))
tx, err := p.db.Begin()
if err != nil {
logger.Error("Could not add user to group", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not add user to group"))
return
}
defer func() {
if err != nil {
logger.Error("Could not join group", zap.Error(err))
err = tx.Rollback()
if err != nil {
logger.Error("Could not rollback transaction", zap.Error(err))
}
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not join group"))
} else {
err = tx.Commit()
if err != nil {
logger.Error("Could not commit transaction", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not join group"))
} else {
logger.Info("User joined group")
session.Send(&Envelope{CollationId: envelope.CollationId})
err = p.storeAndDeliverMessage(logger, session, &TopicId{Id: &TopicId_GroupId{GroupId: groupID.Bytes()}}, 1, []byte("{}"))
if err != nil {
logger.Error("Error handling group user join notification topic message", zap.Error(err))
}
}
}
}()
var groupState sql.NullInt64
err = tx.QueryRow("SELECT state FROM groups WHERE id = $1 AND disabled_at = 0", groupID.Bytes()).Scan(&groupState)
if err != nil {
return
}
userState := 1
if groupState.Int64 == 1 {
userState = 2
}
updatedAt := nowMs()
res, err := tx.Exec(`
INSERT INTO group_edge (source_id, position, updated_at, destination_id, state)
VALUES ($1, $2, $2, $3, $4), ($3, $2, $2, $1, $4)`,
groupID.Bytes(), updatedAt, session.userID.Bytes(), userState)
if err != nil {
return
}
if affectedRows, _ := res.RowsAffected(); affectedRows == 0 {
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not accept group join envelope. Group may not exists with the given ID"))
return
}
if groupState.Int64 == 0 {
_, err = tx.Exec("UPDATE groups SET count = count + 1, updated_at = $2 WHERE id = $1", groupID.Bytes(), updatedAt)
}
if err != nil {
return
}
}
func (p *pipeline) groupLeave(l zap.Logger, session *session, envelope *Envelope) {
g := envelope.GetGroupLeave()
groupID, err := uuid.FromBytes(g.GroupId)
if err != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Group ID is not valid"))
return
}
logger := l.With(zap.String("group_id", groupID.String()))
failureReason := "Could not leave group"
tx, err := p.db.Begin()
if err != nil {
logger.Error("Could not leave group", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, failureReason))
return
}
defer func() {
if err != nil {
logger.Error("Could not leave group", zap.Error(err))
err = tx.Rollback()
if err != nil {
logger.Error("Could not rollback transaction", zap.Error(err))
}
session.Send(ErrorMessageRuntimeException(envelope.CollationId, failureReason))
} else {
err = tx.Commit()
if err != nil {
logger.Error("Could not commit transaction", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, failureReason))
} else {
logger.Info("User left group")
session.Send(&Envelope{CollationId: envelope.CollationId})
err = p.storeAndDeliverMessage(logger, session, &TopicId{Id: &TopicId_GroupId{GroupId: groupID.Bytes()}}, 3, []byte("{}"))
if err != nil {
logger.Error("Error handling group user leave notification topic message", zap.Error(err))
}
}
}
}()
// first remove any invitation from user
// and if this wasn't an invitation then
// look to see if the user is an admin
// and remove the user from group and update group count
res, err := tx.Exec(`
DELETE FROM group_edge
WHERE
(source_id = $1 AND destination_id = $2 AND state = 2)
OR
(source_id = $2 AND destination_id = $1 AND state = 2)`,
groupID.Bytes(), session.userID.Bytes())
if err != nil {
return
}
if count, _ := res.RowsAffected(); count > 0 {
logger.Info("Group invitation removed.")
return
}
var adminCount sql.NullInt64
err = tx.QueryRow(`
SELECT COUNT(source_id) FROM group_edge
WHERE
source_id = $1 AND state = 0
AND
EXISTS (SELECT id FROM groups WHERE id = $1 AND disabled_at = 0)
AND
EXISTS (SELECT source_id FROM group_edge WHERE source_id = $1 AND destination_id = $2 AND state = 0)`,
groupID.Bytes(), session.userID.Bytes()).Scan(&adminCount)
if err != nil {
return
}
if adminCount.Int64 == 1 {
failureReason = "Cannot leave group when you are the last group admin"
err = errors.New("Cannot leave group when you are the last group admin")
return
}
res, err = tx.Exec(`
DELETE FROM group_edge
WHERE
(source_id = $1 AND destination_id = $2)
OR
(source_id = $2 AND destination_id = $1)`,
groupID.Bytes(), session.userID.Bytes())
if err != nil {
return
}
if count, _ := res.RowsAffected(); count == 0 {
failureReason = "Cannot leave group - Make sure you are part of the group or group exists"
err = errors.New("Cannot leave group - Make sure you are part of the group or group exists")
return
}
_, err = tx.Exec(`UPDATE groups SET count = count - 1, updated_at = $1 WHERE id = $2`, nowMs(), groupID.Bytes())
if err != nil {
return
}
}
func (p *pipeline) groupUserAdd(l zap.Logger, session *session, envelope *Envelope) {
g := envelope.GetGroupUserAdd()
groupID, err := uuid.FromBytes(g.GroupId)
if err != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Group ID is not valid"))
return
}
userID, err := uuid.FromBytes(g.UserId)
if err != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "User ID is not valid"))
return
}
logger := l.With(zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
var handle string
tx, err := p.db.Begin()
if err != nil {
logger.Error("Could not add user to group", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not add user to group"))
return
}
defer func() {
if err != nil {
if _, ok := err.(*pq.Error); ok {
logger.Error("Could not add user to group", zap.Error(err))
} else {
logger.Warn("Could not add user to group", zap.Error(err))
}
err = tx.Rollback()
if err != nil {
logger.Error("Could not rollback transaction", zap.Error(err))
}
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not add user to group"))
} else {
err = tx.Commit()
if err != nil {
logger.Error("Could not commit transaction", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, "Could not add user to group"))
} else {
logger.Info("Added user to the group")
session.Send(&Envelope{CollationId: envelope.CollationId})
data, _ := json.Marshal(map[string]string{"user_id": userID.String(), "handle": handle})
err = p.storeAndDeliverMessage(logger, session, &TopicId{Id: &TopicId_GroupId{GroupId: groupID.Bytes()}}, 2, data)
if err != nil {
logger.Error("Error handling group user added notification topic message", zap.Error(err))
}
}
}
}()
// Look up the user being added.
err = tx.QueryRow("SELECT handle FROM users WHERE id = $1 AND disabled_at = 0", userID.Bytes()).Scan(&handle)
if err != nil {
return
}
res, err := tx.Exec(`
INSERT INTO group_edge (source_id, position, updated_at, destination_id, state)
SELECT data.id, data.position, data.updated_at, data.destination, data.state
FROM (
SELECT $1::BYTEA AS id, $2::INT AS position, $2::INT AS updated_at, $3::BYTEA AS destination, 1 AS state
UNION ALL
SELECT $3::BYTEA AS id, $2::INT AS position, $2::INT AS updated_at, $1::BYTEA AS destination, 1 AS state
) AS data
WHERE
EXISTS (SELECT source_id FROM group_edge WHERE source_id = $1::BYTEA AND destination_id = $4::BYTEA AND state = 0)
AND
EXISTS (SELECT id FROM groups WHERE id = $1::BYTEA AND disabled_at = 0)
ON CONFLICT (source_id, destination_id)
DO UPDATE SET state = 1, updated_at = $2::INT`,
groupID.Bytes(), nowMs(), userID.Bytes(), session.userID.Bytes())
if err != nil {
return
}
if affectedRows, _ := res.RowsAffected(); affectedRows == 0 {
err = errors.New("Could not add user to group. Group may not exists or you may not be group admin")
return
}
_, err = tx.Exec(`UPDATE groups SET count = count + 1, updated_at = $1 WHERE id = $2`, nowMs(), groupID.Bytes())
if err != nil {
return
}
}
func (p *pipeline) groupUserKick(l zap.Logger, session *session, envelope *Envelope) {
// TODO Force kick the user out.
g := envelope.GetGroupUserKick()
groupID, err := uuid.FromBytes(g.GroupId)
if err != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Group ID is not valid"))
return
}
userID, err := uuid.FromBytes(g.UserId)
if err != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "User ID is not valid"))
return
}
if userID == session.userID {
session.Send(ErrorMessageBadInput(envelope.CollationId, "You can't kick yourself from the group"))
return
}
logger := l.With(zap.String("group_id", groupID.String()), zap.String("user_id", userID.String()))
var handle string
failureReason := "Could not kick user from group"
tx, err := p.db.Begin()
if err != nil {
logger.Error("Could not kick user from group", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, failureReason))
return
}
defer func() {
if err != nil {
if _, ok := err.(*pq.Error); ok {
logger.Error("Could not kick user from group", zap.Error(err))
} else {
logger.Warn("Could not kick user from group", zap.Error(err))
}
err = tx.Rollback()
if err != nil {
logger.Error("Could not rollback transaction", zap.Error(err))
}
session.Send(ErrorMessageRuntimeException(envelope.CollationId, failureReason))
} else {
err = tx.Commit()
if err != nil {
logger.Error("Could not commit transaction", zap.Error(err))
session.Send(ErrorMessageRuntimeException(envelope.CollationId, failureReason))
} else {
logger.Info("Kicked user from group")
session.Send(&Envelope{CollationId: envelope.CollationId})
data, _ := json.Marshal(map[string]string{"user_id": userID.String(), "handle": handle})
err = p.storeAndDeliverMessage(logger, session, &TopicId{Id: &TopicId_GroupId{GroupId: groupID.Bytes()}}, 4, data)
if err != nil {
logger.Error("Error handling group user kicked notification topic message", zap.Error(err))
}
}
}
}()
res, err := tx.Exec(`
DELETE FROM group_edge
WHERE
EXISTS (SELECT source_id FROM group_edge WHERE source_id = $1 AND destination_id = $3 AND state = 0)
AND
EXISTS (SELECT id FROM groups WHERE id = $1 AND disabled_at = 0)
AND
(
(source_id = $1 AND destination_id = $2)
OR
(source_id = $2 AND destination_id = $1)
)`, groupID.Bytes(), userID.Bytes(), session.userID.Bytes())
if err != nil {
return
}
if count, _ := res.RowsAffected(); count == 0 {
failureReason = "Cannot kick from group - Make sure user is part of the group and is admin or group exists"
err = errors.New("Cannot kick from group - Make sure user is part of the group and is admin or group exists")
return
}
_, err = tx.Exec(`UPDATE groups SET count = count - 1, updated_at = $1 WHERE id = $2`, nowMs(), groupID.Bytes())
if err != nil {
return
}
// Look up the user being kicked. Allow kicking disabled users.
err = tx.QueryRow("SELECT handle FROM users WHERE id = $1", userID.Bytes()).Scan(&handle)
if err != nil {
return
}
}
func (p *pipeline) groupUserPromote(l zap.Logger, session *session, envelope *Envelope) {
g := envelope.GetGroupUserPromote()
groupID, err := uuid.FromBytes(g.GroupId)
if err != nil {
session.Send(ErrorMessageBadInput(envelope.CollationId, "Group ID is not valid"))
return