/
helper.go
1472 lines (1350 loc) · 53.3 KB
/
helper.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
package chat
import (
"encoding/hex"
"errors"
"fmt"
"math"
"sort"
"strings"
"time"
"github.com/keybase/client/go/chat/globals"
"github.com/keybase/client/go/chat/storage"
"github.com/keybase/client/go/chat/types"
"github.com/keybase/client/go/chat/utils"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/client/go/teams"
"golang.org/x/net/context"
)
type Helper struct {
globals.Contextified
utils.DebugLabeler
ri func() chat1.RemoteInterface
}
var _ (libkb.ChatHelper) = (*Helper)(nil)
func NewHelper(g *globals.Context, ri func() chat1.RemoteInterface) *Helper {
return &Helper{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), "Helper", false),
ri: ri,
}
}
func (h *Helper) NewConversation(ctx context.Context, uid gregor1.UID, tlfName string,
topicName *string, topicType chat1.TopicType, membersType chat1.ConversationMembersType,
vis keybase1.TLFVisibility) (chat1.ConversationLocal, bool, error) {
return NewConversation(ctx, h.G(), uid, tlfName, topicName,
topicType, membersType, vis, nil, h.ri, NewConvFindExistingNormal)
}
func (h *Helper) NewConversationSkipFindExisting(ctx context.Context, uid gregor1.UID, tlfName string,
topicName *string, topicType chat1.TopicType, membersType chat1.ConversationMembersType,
vis keybase1.TLFVisibility) (chat1.ConversationLocal, bool, error) {
return NewConversation(ctx, h.G(), uid, tlfName, topicName,
topicType, membersType, vis, nil, h.ri, NewConvFindExistingSkip)
}
func (h *Helper) NewConversationWithMemberSourceConv(ctx context.Context, uid gregor1.UID, tlfName string,
topicName *string, topicType chat1.TopicType, membersType chat1.ConversationMembersType,
vis keybase1.TLFVisibility, retentionPolicy *chat1.RetentionPolicy,
memberSourceConv *chat1.ConversationID) (chat1.ConversationLocal, bool, error) {
return NewConversationWithMemberSourceConv(ctx, h.G(), uid, tlfName, topicName,
topicType, membersType, vis, nil, h.ri, NewConvFindExistingNormal, retentionPolicy, memberSourceConv)
}
func (h *Helper) SendTextByID(ctx context.Context, convID chat1.ConversationID,
tlfName string, text string, vis keybase1.TLFVisibility) error {
return h.SendMsgByID(ctx, convID, tlfName, chat1.NewMessageBodyWithText(chat1.MessageText{
Body: text,
}), chat1.MessageType_TEXT, vis)
}
func (h *Helper) SendMsgByID(ctx context.Context, convID chat1.ConversationID, tlfName string,
body chat1.MessageBody, msgType chat1.MessageType, vis keybase1.TLFVisibility) error {
boxer := NewBoxer(h.G())
sender := NewBlockingSender(h.G(), boxer, h.ri)
public := vis == keybase1.TLFVisibility_PUBLIC
msg := chat1.MessagePlaintext{
ClientHeader: chat1.MessageClientHeader{
TlfName: tlfName,
TlfPublic: public,
MessageType: msgType,
},
MessageBody: body,
}
_, _, err := sender.Send(ctx, convID, msg, 0, nil, nil, nil)
return err
}
func (h *Helper) SendTextByIDNonblock(ctx context.Context, convID chat1.ConversationID,
tlfName string, text string, outboxID *chat1.OutboxID, replyTo *chat1.MessageID) (chat1.OutboxID, error) {
return h.SendMsgByIDNonblock(ctx, convID, tlfName, chat1.NewMessageBodyWithText(chat1.MessageText{
Body: text,
}), chat1.MessageType_TEXT, outboxID, replyTo)
}
func (h *Helper) SendMsgByIDNonblock(ctx context.Context, convID chat1.ConversationID,
tlfName string, body chat1.MessageBody, msgType chat1.MessageType, inOutboxID *chat1.OutboxID,
replyTo *chat1.MessageID) (chat1.OutboxID, error) {
boxer := NewBoxer(h.G())
baseSender := NewBlockingSender(h.G(), boxer, h.ri)
sender := NewNonblockingSender(h.G(), baseSender)
msg := chat1.MessagePlaintext{
ClientHeader: chat1.MessageClientHeader{
TlfName: tlfName,
MessageType: msgType,
},
MessageBody: body,
}
prepareOpts := chat1.SenderPrepareOptions{
ReplyTo: replyTo,
}
outboxID, _, err := sender.Send(ctx, convID, msg, 0, inOutboxID, nil, &prepareOpts)
return outboxID, err
}
func (h *Helper) DeleteMsg(ctx context.Context, convID chat1.ConversationID, tlfName string,
msgID chat1.MessageID) error {
boxer := NewBoxer(h.G())
sender := NewBlockingSender(h.G(), boxer, h.ri)
msg := chat1.MessagePlaintext{
ClientHeader: chat1.MessageClientHeader{
TlfName: tlfName,
MessageType: chat1.MessageType_DELETE,
Supersedes: msgID,
},
}
_, _, err := sender.Send(ctx, convID, msg, 0, nil, nil, nil)
return err
}
func (h *Helper) DeleteMsgNonblock(ctx context.Context, convID chat1.ConversationID, tlfName string,
msgID chat1.MessageID) error {
boxer := NewBoxer(h.G())
sender := NewNonblockingSender(h.G(), NewBlockingSender(h.G(), boxer, h.ri))
msg := chat1.MessagePlaintext{
ClientHeader: chat1.MessageClientHeader{
TlfName: tlfName,
MessageType: chat1.MessageType_DELETE,
Supersedes: msgID,
},
}
_, _, err := sender.Send(ctx, convID, msg, 0, nil, nil, nil)
return err
}
func (h *Helper) SendTextByName(ctx context.Context, name string, topicName *string,
membersType chat1.ConversationMembersType, ident keybase1.TLFIdentifyBehavior, text string) error {
boxer := NewBoxer(h.G())
sender := NewBlockingSender(h.G(), boxer, h.ri)
helper := newSendHelper(h.G(), name, topicName, membersType, ident, sender, h.ri)
_, _, err := helper.SendText(ctx, text, nil)
return err
}
func (h *Helper) SendMsgByName(ctx context.Context, name string, topicName *string,
membersType chat1.ConversationMembersType, ident keybase1.TLFIdentifyBehavior, body chat1.MessageBody,
msgType chat1.MessageType) error {
boxer := NewBoxer(h.G())
sender := NewBlockingSender(h.G(), boxer, h.ri)
helper := newSendHelper(h.G(), name, topicName, membersType, ident, sender, h.ri)
_, _, err := helper.SendBody(ctx, body, msgType, nil)
return err
}
func (h *Helper) SendTextByNameNonblock(ctx context.Context, name string, topicName *string,
membersType chat1.ConversationMembersType, ident keybase1.TLFIdentifyBehavior, text string,
inOutboxID *chat1.OutboxID) (chat1.OutboxID, error) {
boxer := NewBoxer(h.G())
baseSender := NewBlockingSender(h.G(), boxer, h.ri)
sender := NewNonblockingSender(h.G(), baseSender)
helper := newSendHelper(h.G(), name, topicName, membersType, ident, sender, h.ri)
outboxID, _, err := helper.SendText(ctx, text, inOutboxID)
return outboxID, err
}
func (h *Helper) SendMsgByNameNonblock(ctx context.Context, name string, topicName *string,
membersType chat1.ConversationMembersType, ident keybase1.TLFIdentifyBehavior, body chat1.MessageBody,
msgType chat1.MessageType, inOutboxID *chat1.OutboxID) (chat1.OutboxID, error) {
boxer := NewBoxer(h.G())
baseSender := NewBlockingSender(h.G(), boxer, h.ri)
sender := NewNonblockingSender(h.G(), baseSender)
helper := newSendHelper(h.G(), name, topicName, membersType, ident, sender, h.ri)
outboxID, _, err := helper.SendBody(ctx, body, msgType, inOutboxID)
return outboxID, err
}
func (h *Helper) FindConversations(ctx context.Context,
name string, topicName *string,
topicType chat1.TopicType, membersType chat1.ConversationMembersType, vis keybase1.TLFVisibility) ([]chat1.ConversationLocal, error) {
kuid, err := CurrentUID(h.G())
if err != nil {
return nil, err
}
uid := gregor1.UID(kuid.ToBytes())
oneChat := true
var tname string
if topicName != nil {
tname = utils.SanitizeTopicName(*topicName)
}
convs, err := FindConversations(ctx, h.G(), h.DebugLabeler, types.InboxSourceDataSourceAll, h.ri, uid,
name, topicType, membersType, vis, tname, &oneChat)
return convs, err
}
func (h *Helper) FindConversationsByID(ctx context.Context, convIDs []chat1.ConversationID) ([]chat1.ConversationLocal, error) {
kuid, err := CurrentUID(h.G())
if err != nil {
return nil, err
}
uid := gregor1.UID(kuid.ToBytes())
query := &chat1.GetInboxLocalQuery{
ConvIDs: convIDs,
}
inbox, _, err := h.G().InboxSource.Read(ctx, uid, types.ConversationLocalizerBlocking,
types.InboxSourceDataSourceAll, nil, query)
if err != nil {
return nil, err
}
return inbox.Convs, nil
}
// GetChannelTopicName gets the name of a team channel even if it's not in the inbox.
func (h *Helper) GetChannelTopicName(ctx context.Context, teamID keybase1.TeamID,
topicType chat1.TopicType, convID chat1.ConversationID) (topicName string, err error) {
defer h.Trace(ctx, &err, "ChatHelper.GetChannelTopicName")()
h.Debug(ctx, "for teamID:%v convID:%v", teamID.String(), convID.String())
kuid, err := CurrentUID(h.G())
if err != nil {
return topicName, err
}
uid := gregor1.UID(kuid.ToBytes())
tlfID, err := chat1.TeamIDToTLFID(teamID)
if err != nil {
return topicName, err
}
query := &chat1.GetInboxLocalQuery{
ConvIDs: []chat1.ConversationID{convID},
}
inbox, _, err := h.G().InboxSource.Read(ctx, uid, types.ConversationLocalizerBlocking,
types.InboxSourceDataSourceAll, nil, query)
if err != nil {
return topicName, err
}
h.Debug(ctx, "found inbox convs: %v", len(inbox.Convs))
for _, conv := range inbox.Convs {
if conv.GetConvID().Eq(convID) && conv.GetMembersType() == chat1.ConversationMembersType_TEAM {
return conv.Info.TopicName, nil
}
}
// Fallback to TeamChannelSource
h.Debug(ctx, "using TeamChannelSource")
topicName, err = h.G().TeamChannelSource.GetChannelTopicName(ctx, uid, tlfID, topicType, convID)
return topicName, err
}
func (h *Helper) UpgradeKBFSToImpteam(ctx context.Context, tlfName string, tlfID chat1.TLFID, public bool) (err error) {
ctx = globals.ChatCtx(ctx, h.G(), keybase1.TLFIdentifyBehavior_CHAT_GUI, nil, NewCachingIdentifyNotifier(h.G()))
defer h.Trace(ctx, &err, "ChatHelper.UpgradeKBFSToImpteam(%s,%s,%v)",
tlfID, tlfName, public)()
var cryptKeys []keybase1.CryptKey
nis := NewKBFSNameInfoSource(h.G())
keys, err := nis.AllCryptKeys(ctx, tlfName, public)
if err != nil {
return err
}
for _, key := range keys[chat1.ConversationMembersType_KBFS] {
cryptKeys = append(cryptKeys, keybase1.CryptKey{
KeyGeneration: key.Generation(),
Key: key.Material(),
})
}
ni, err := nis.LookupID(ctx, tlfName, public)
if err != nil {
return err
}
tlfName = ni.CanonicalName
h.Debug(ctx, "UpgradeKBFSToImpteam: upgrading: TlfName: %s TLFID: %s public: %v keys: %d",
tlfName, tlfID, public, len(cryptKeys))
return teams.UpgradeTLFIDToImpteam(ctx, h.G().ExternalG(), tlfName, keybase1.TLFID(tlfID.String()),
public, keybase1.TeamApplication_CHAT, cryptKeys)
}
func (h *Helper) GetMessages(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID,
msgIDs []chat1.MessageID, resolveSupersedes bool, reason *chat1.GetThreadReason) ([]chat1.MessageUnboxed, error) {
return h.G().ConvSource.GetMessages(ctx, convID, uid, msgIDs, reason, nil, resolveSupersedes)
}
func (h *Helper) GetMessage(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID,
msgID chat1.MessageID, resolveSupersedes bool, reason *chat1.GetThreadReason) (chat1.MessageUnboxed, error) {
return h.G().ConvSource.GetMessage(ctx, convID, uid, msgID, reason, nil, resolveSupersedes)
}
func (h *Helper) UserReacjis(ctx context.Context, uid gregor1.UID) keybase1.UserReacjis {
return storage.NewReacjiStore(h.G()).UserReacjis(ctx, uid)
}
func (h *Helper) JourneycardTimeTravel(ctx context.Context, uid gregor1.UID, duration time.Duration) (int, int, error) {
j, ok := h.G().JourneyCardManager.(*JourneyCardManager)
if !ok {
return 0, 0, fmt.Errorf("could not get JourneyCardManager")
}
return j.TimeTravel(ctx, uid, duration)
}
func (h *Helper) JourneycardResetAllConvs(ctx context.Context, uid gregor1.UID) error {
j, ok := h.G().JourneyCardManager.(*JourneyCardManager)
if !ok {
return fmt.Errorf("could not get JourneyCardManager")
}
return j.ResetAllConvs(ctx, uid)
}
func (h *Helper) JourneycardDebugState(ctx context.Context, uid gregor1.UID, teamID keybase1.TeamID) (string, error) {
j, ok := h.G().JourneyCardManager.(*JourneyCardManager)
if !ok {
return "", fmt.Errorf("could not get JourneyCardManager")
}
return j.DebugState(ctx, uid, teamID)
}
// InTeam gives a best effort to answer team membership based on the current state of the inbox cache
func (h *Helper) InTeam(ctx context.Context, uid gregor1.UID, teamID keybase1.TeamID) (bool, error) {
tlfID := chat1.TLFID(teamID.ToBytes())
ibox, err := h.G().InboxSource.ReadUnverified(ctx, uid, types.InboxSourceDataSourceLocalOnly,
&chat1.GetInboxQuery{
TlfID: &tlfID,
MemberStatus: []chat1.ConversationMemberStatus{chat1.ConversationMemberStatus_ACTIVE},
AllowUnseenQuery: true,
})
if err != nil {
return false, err
}
return len(ibox.ConvsUnverified) > 0, nil
}
type sendHelper struct {
utils.DebugLabeler
name string
membersType chat1.ConversationMembersType
ident keybase1.TLFIdentifyBehavior
sender types.Sender
ri func() chat1.RemoteInterface
topicName *string
convID chat1.ConversationID
triple chat1.ConversationIDTriple
globals.Contextified
}
func newSendHelper(g *globals.Context, name string, topicName *string,
membersType chat1.ConversationMembersType, ident keybase1.TLFIdentifyBehavior, sender types.Sender,
ri func() chat1.RemoteInterface) *sendHelper {
return &sendHelper{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), "sendHelper", false),
name: name,
topicName: topicName,
membersType: membersType,
ident: ident,
sender: sender,
ri: ri,
}
}
func (s *sendHelper) SendText(ctx context.Context, text string, outboxID *chat1.OutboxID) (chat1.OutboxID, *chat1.MessageBoxed, error) {
body := chat1.NewMessageBodyWithText(chat1.MessageText{Body: text})
return s.SendBody(ctx, body, chat1.MessageType_TEXT, outboxID)
}
func (s *sendHelper) SendBody(ctx context.Context, body chat1.MessageBody, mtype chat1.MessageType,
outboxID *chat1.OutboxID) (chat1.OutboxID, *chat1.MessageBoxed, error) {
ctx = globals.ChatCtx(ctx, s.G(), s.ident, nil, NewCachingIdentifyNotifier(s.G()))
if err := s.conversation(ctx); err != nil {
return chat1.OutboxID{}, nil, err
}
return s.deliver(ctx, body, mtype, outboxID)
}
func (s *sendHelper) conversation(ctx context.Context) error {
kuid, err := CurrentUID(s.G())
if err != nil {
return err
}
uid := gregor1.UID(kuid.ToBytes())
conv, _, err := NewConversation(ctx, s.G(), uid, s.name, s.topicName,
chat1.TopicType_CHAT, s.membersType, keybase1.TLFVisibility_PRIVATE, nil, s.remoteInterface,
NewConvFindExistingNormal)
if err != nil {
return err
}
s.convID = conv.GetConvID()
s.triple = conv.Info.Triple
s.name = conv.Info.TlfName
return nil
}
func (s *sendHelper) deliver(ctx context.Context, body chat1.MessageBody, mtype chat1.MessageType,
outboxID *chat1.OutboxID) (chat1.OutboxID, *chat1.MessageBoxed, error) {
msg := chat1.MessagePlaintext{
ClientHeader: chat1.MessageClientHeader{
Conv: s.triple,
TlfName: s.name,
MessageType: mtype,
},
MessageBody: body,
}
return s.sender.Send(ctx, s.convID, msg, 0, outboxID, nil, nil)
}
func (s *sendHelper) remoteInterface() chat1.RemoteInterface {
return s.ri()
}
func CurrentUID(g *globals.Context) (keybase1.UID, error) {
uid := g.Env.GetUID()
if uid.IsNil() {
return "", libkb.LoginRequiredError{}
}
return uid, nil
}
type recentConversationParticipants struct {
globals.Contextified
utils.DebugLabeler
}
func newRecentConversationParticipants(g *globals.Context) *recentConversationParticipants {
return &recentConversationParticipants{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), "recentConversationParticipants", false),
}
}
func (r *recentConversationParticipants) getActiveScore(ctx context.Context, conv chat1.Conversation) float64 {
mtime := conv.GetMtime()
diff := time.Since(mtime.Time())
weeksAgo := diff.Seconds() / (time.Hour.Seconds() * 24 * 7)
val := 10.0 - math.Pow(1.6, weeksAgo)
if val < 1.0 {
val = 1.0
}
return val
}
func (r *recentConversationParticipants) get(ctx context.Context, myUID gregor1.UID) (res []gregor1.UID, err error) {
_, convs, err := storage.NewInbox(r.G()).ReadAll(ctx, myUID, true)
if err != nil {
if _, ok := err.(storage.MissError); ok {
r.Debug(ctx, "get: no inbox, returning blank results")
return nil, nil
}
return nil, err
}
r.Debug(ctx, "get: convs: %d", len(convs))
m := make(map[string]float64, len(convs))
for _, conv := range convs {
if conv.Conv.Metadata.Status == chat1.ConversationStatus_BLOCKED ||
conv.Conv.Metadata.Status == chat1.ConversationStatus_REPORTED {
continue
}
for _, uid := range conv.Conv.Metadata.ActiveList {
if uid.Eq(myUID) {
continue
}
m[uid.String()] += r.getActiveScore(ctx, conv.Conv)
}
}
for suid := range m {
uid, _ := hex.DecodeString(suid)
res = append(res, gregor1.UID(uid))
}
// Sort by the most appearances in the active lists
sort.Slice(res, func(i, j int) bool {
return m[res[i].String()] > m[res[j].String()]
})
return res, nil
}
func RecentConversationParticipants(ctx context.Context, g *globals.Context, myUID gregor1.UID) ([]gregor1.UID, error) {
ctx = globals.ChatCtx(ctx, g, keybase1.TLFIdentifyBehavior_CHAT_GUI, nil, NewCachingIdentifyNotifier(g))
return newRecentConversationParticipants(g).get(ctx, myUID)
}
func PresentConversationLocalWithFetchRetry(ctx context.Context, g *globals.Context,
uid gregor1.UID, conv chat1.ConversationLocal, partMode utils.PresentParticipantsMode) (pc *chat1.InboxUIItem) {
shouldPresent := true
if conv.Error != nil {
// If we get a transient failure, add this to the retrier queue
if conv.Error.Typ == chat1.ConversationErrorType_TRANSIENT {
g.FetchRetrier.Failure(ctx, uid,
NewConversationRetry(g, conv.GetConvID(), &conv.Info.Triple.Tlfid, InboxLoad))
} else {
// If this is a permanent error, then we don't send anything to the frontend yet.
shouldPresent = false
}
}
if shouldPresent {
pc = new(chat1.InboxUIItem)
*pc = utils.PresentConversationLocal(ctx, g, uid, conv, partMode)
}
return pc
}
func GetTopicNameState(ctx context.Context, g *globals.Context, debugger utils.DebugLabeler,
convs []chat1.ConversationLocal,
uid gregor1.UID, tlfID chat1.TLFID, topicType chat1.TopicType,
membersType chat1.ConversationMembersType) (res chat1.TopicNameState, err error) {
var pairs chat1.ConversationIDMessageIDPairs
sort.Sort(utils.ConvLocalByConvID(convs))
for _, conv := range convs {
msg, err := conv.GetMaxMessage(chat1.MessageType_METADATA)
if err != nil {
debugger.Debug(ctx, "GetTopicNameState: unable to get maxmessage: convID: %v, %v", conv.GetConvID(), err)
continue
}
pairs.Pairs = append(pairs.Pairs, chat1.ConversationIDMessageIDPair{
ConvID: conv.GetConvID(),
MsgID: msg.GetMessageID(),
})
}
if res, err = utils.CreateTopicNameState(pairs); err != nil {
debugger.Debug(ctx, "GetTopicNameState: failed to create topic name state: %v", err)
return res, err
}
return res, nil
}
func FindConversations(ctx context.Context, g *globals.Context, debugger utils.DebugLabeler,
dataSource types.InboxSourceDataSourceTyp, ri func() chat1.RemoteInterface, uid gregor1.UID,
tlfName string, topicType chat1.TopicType,
membersTypeIn chat1.ConversationMembersType, vis keybase1.TLFVisibility, topicName string,
oneChatPerTLF *bool) (res []chat1.ConversationLocal, err error) {
findConvosWithMembersType := func(membersType chat1.ConversationMembersType) (res []chat1.ConversationLocal, err error) {
// Don't look for KBFS conversations anymore, they have mostly been converted, and it is better
// to just not search for them than to create a double conversation. Make an exception for
// public conversations.
if g.GetEnv().GetChatMemberType() != "kbfs" && membersType == chat1.ConversationMembersType_KBFS &&
vis == keybase1.TLFVisibility_PRIVATE {
return nil, nil
}
// Make sure team topic name makes sense
if topicName == "" && membersType == chat1.ConversationMembersType_TEAM {
topicName = globals.DefaultTeamTopic
}
// Attempt to resolve any sbs convs incase the team already exists.
var nameInfo *types.NameInfo
if strings.Contains(tlfName, "@") || strings.Contains(tlfName, ":") {
// Fetch the TLF ID from specified name
if info, err := CreateNameInfoSource(ctx, g, membersType).LookupID(ctx, tlfName, vis == keybase1.TLFVisibility_PUBLIC); err == nil {
nameInfo = &info
tlfName = nameInfo.CanonicalName
}
}
query := &chat1.GetInboxLocalQuery{
Name: &chat1.NameQuery{
Name: tlfName,
MembersType: membersType,
},
TlfVisibility: &vis,
TopicName: &topicName,
TopicType: &topicType,
OneChatTypePerTLF: oneChatPerTLF,
}
inbox, _, err := g.InboxSource.Read(ctx, uid, types.ConversationLocalizerBlocking, dataSource, nil,
query)
if err != nil {
acceptableErr := false
// if we fail to load the team for some kind of rekey reason, treat as a complete miss
if _, ok := IsRekeyError(err); ok {
acceptableErr = true
}
// don't error out if the TLF name is just unknown, treat it as a complete miss
if _, ok := err.(UnknownTLFNameError); ok {
acceptableErr = true
}
if !acceptableErr {
return res, err
}
inbox.Convs = nil
}
// If we have inbox hits, return those
if len(inbox.Convs) > 0 {
debugger.Debug(ctx, "FindConversations: found conversations in inbox: tlfName: %s num: %d",
tlfName, len(inbox.Convs))
res = inbox.Convs
} else if membersType == chat1.ConversationMembersType_TEAM {
// If this is a team chat that we are looking for, then let's try searching all
// chats on the team to see if any match the arguments before giving up.
// No need to worry (yet) about conflicting with public code path, since there
// are not any public team chats.
// Fetch the TLF ID from specified name
if nameInfo == nil {
info, err := CreateNameInfoSource(ctx, g, membersType).LookupID(ctx, tlfName, false)
if err != nil {
debugger.Debug(ctx, "FindConversations: failed to get TLFID from name: %s", err.Error())
return res, err
}
nameInfo = &info
}
tlfConvs, err := g.TeamChannelSource.GetChannelsFull(ctx, uid, nameInfo.ID, topicType)
if err != nil {
debugger.Debug(ctx, "FindConversations: failed to list TLF conversations: %s", err.Error())
return res, err
}
for _, tlfConv := range tlfConvs {
if tlfConv.Info.TopicName == topicName {
res = append(res, tlfConv)
}
}
if len(res) > 0 {
debugger.Debug(ctx, "FindConversations: found team channels: num: %d", len(res))
}
} else if vis == keybase1.TLFVisibility_PUBLIC {
debugger.Debug(ctx, "FindConversations: no conversations found in inbox, trying public chats")
// Check for offline and return an error
if g.InboxSource.IsOffline(ctx) {
return res, OfflineError{}
}
// If we miss the inbox, and we are looking for a public TLF, let's try and find
// any conversation that matches
nameInfo, err := GetInboxQueryNameInfo(ctx, g, query)
if err != nil {
return res, err
}
// Call into gregor to try and find some public convs
pubConvs, err := ri().GetPublicConversations(ctx, chat1.GetPublicConversationsArg{
TlfID: nameInfo.ID,
TopicType: topicType,
SummarizeMaxMsgs: true,
})
if err != nil {
return res, err
}
// Localize the convs (if any)
if len(pubConvs.Conversations) > 0 {
convsLocal, _, err := g.InboxSource.Localize(ctx, uid,
utils.RemoteConvs(pubConvs.Conversations), types.ConversationLocalizerBlocking)
if err != nil {
return res, err
}
// Search for conversations that match the topic name
for _, convLocal := range convsLocal {
if convLocal.Error != nil {
debugger.Debug(ctx, "FindConversations: skipping convID: %s localization failure: %s",
convLocal.GetConvID(), convLocal.Error.Message)
continue
}
if convLocal.Info.TopicName == topicName &&
convLocal.Info.TLFNameExpanded() == nameInfo.CanonicalName {
debugger.Debug(ctx, "FindConversations: found matching public conv: id: %s topicName: %s",
convLocal.GetConvID(), topicName)
res = append(res, convLocal)
}
}
}
}
return res, nil
}
attempts := make(map[chat1.ConversationMembersType]bool)
mt := membersTypeIn
L:
for {
var ierr error
attempts[mt] = true
res, ierr = findConvosWithMembersType(mt)
if ierr != nil || len(res) == 0 {
if ierr != nil {
debugger.Debug(ctx, "FindConversations: fail reason: %s mt: %v", ierr, mt)
} else {
debugger.Debug(ctx, "FindConversations: fail reason: no convs mt: %v", mt)
}
var newMT chat1.ConversationMembersType
switch mt {
case chat1.ConversationMembersType_TEAM:
err = ierr
debugger.Debug(ctx, "FindConversations: failed with team, aborting")
break L
case chat1.ConversationMembersType_IMPTEAMUPGRADE:
if !attempts[chat1.ConversationMembersType_IMPTEAMNATIVE] {
newMT = chat1.ConversationMembersType_IMPTEAMNATIVE
// Only set the error if the members type is the same as what was passed in
err = ierr
} else {
newMT = chat1.ConversationMembersType_KBFS
}
case chat1.ConversationMembersType_IMPTEAMNATIVE:
if !attempts[chat1.ConversationMembersType_IMPTEAMUPGRADE] {
newMT = chat1.ConversationMembersType_IMPTEAMUPGRADE
// Only set the error if the members type is the same as what was passed in
err = ierr
} else {
newMT = chat1.ConversationMembersType_KBFS
}
case chat1.ConversationMembersType_KBFS:
debugger.Debug(ctx, "FindConversations: failed with KBFS, aborting")
// We don't want to return random errors from KBFS if we are falling back to it,
// just return no conversations and call it a day
if membersTypeIn == chat1.ConversationMembersType_KBFS {
err = ierr
}
break L
}
debugger.Debug(ctx,
"FindConversations: failing to find anything for %v, trying again for %v", mt, newMT)
mt = newMT
} else {
debugger.Debug(ctx, "FindConversations: success with mt: %v", mt)
break L
}
}
return res, err
}
// Post a join or leave message. Must be called when the user is in the conv.
// Uses a blocking sender.
func postJoinLeave(ctx context.Context, g *globals.Context, ri func() chat1.RemoteInterface, uid gregor1.UID,
convID chat1.ConversationID, body chat1.MessageBody) (err error) {
typ, err := body.MessageType()
if err != nil {
return fmt.Errorf("message type for postJoinLeave: %v", err)
}
switch typ {
case chat1.MessageType_JOIN, chat1.MessageType_LEAVE:
// good
default:
return fmt.Errorf("invalid message type for postJoinLeave: %v", typ)
}
// Get the conversation from the inbox.
query := chat1.GetInboxLocalQuery{
ConvIDs: []chat1.ConversationID{convID},
}
ib, _, err := g.InboxSource.Read(ctx, uid, types.ConversationLocalizerBlocking,
types.InboxSourceDataSourceAll, nil, &query)
if err != nil {
return fmt.Errorf("inbox read error: %s", err)
}
if len(ib.Convs) != 1 {
return fmt.Errorf("post join/leave: found %d conversations", len(ib.Convs))
}
conv := ib.Convs[0]
if conv.GetTopicType() != chat1.TopicType_CHAT {
// only post these in chat convs
return nil
}
plaintext := chat1.MessagePlaintext{
ClientHeader: chat1.MessageClientHeader{
Conv: conv.Info.Triple,
TlfName: conv.Info.TlfName,
TlfPublic: conv.Info.Visibility == keybase1.TLFVisibility_PUBLIC,
MessageType: typ,
Supersedes: chat1.MessageID(0),
Deletes: nil,
Prev: nil, // Filled by Sender
Sender: nil, // Filled by Sender
SenderDevice: nil, // Filled by Sender
MerkleRoot: nil, // Filled by Boxer
OutboxID: nil,
OutboxInfo: nil,
},
MessageBody: body,
}
// Send with a blocking sender
sender := NewBlockingSender(g, NewBoxer(g), ri)
_, _, err = sender.Send(ctx, convID, plaintext, 0, nil, nil, nil)
return err
}
func (h *Helper) JoinConversationByID(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID) (err error) {
defer h.Trace(ctx, &err, "ChatHelper.JoinConversationByID")()
return JoinConversation(ctx, h.G(), h.DebugLabeler, h.ri, uid, convID)
}
func JoinConversation(ctx context.Context, g *globals.Context, debugger utils.DebugLabeler,
ri func() chat1.RemoteInterface, uid gregor1.UID, convID chat1.ConversationID) (err error) {
if err := g.ConvSource.AcquireConversationLock(ctx, uid, convID); err != nil {
return err
}
defer g.ConvSource.ReleaseConversationLock(ctx, uid, convID)
if alreadyIn, err := g.InboxSource.IsMember(ctx, uid, convID); err != nil {
// charge forward anyway
debugger.Debug(ctx, "JoinConversation: IsMember err: %v", err)
} else if alreadyIn {
return nil
}
if _, err = ri().JoinConversation(ctx, convID); err != nil {
debugger.Debug(ctx, "JoinConversation: failed to join conversation: %v", err)
return err
}
if _, err = g.InboxSource.MembershipUpdate(ctx, uid, 0, []chat1.ConversationMember{
{
Uid: uid,
ConvID: convID,
},
}, nil, nil, nil, nil); err != nil {
debugger.Debug(ctx, "JoinConversation: failed to apply membership update: %v", err)
}
// Send a message to the channel after joining
joinMessageBody := chat1.NewMessageBodyWithJoin(chat1.MessageJoin{})
debugger.Debug(ctx, "JoinConversation: sending join message to: %s", convID)
if err := postJoinLeave(ctx, g, ri, uid, convID, joinMessageBody); err != nil {
debugger.Debug(ctx, "JoinConversation: posting join-conv message failed: %v", err)
// ignore the error
}
return nil
}
func (h *Helper) JoinConversationByName(ctx context.Context, uid gregor1.UID, tlfName, topicName string,
topicType chat1.TopicType, vis keybase1.TLFVisibility) (err error) {
defer h.Trace(ctx, &err, "ChatHelper.JoinConversationByName")()
return JoinConversationByName(ctx, h.G(), h.DebugLabeler, h.ri, uid, tlfName, topicName, topicType, vis)
}
func JoinConversationByName(ctx context.Context, g *globals.Context, debugger utils.DebugLabeler,
ri func() chat1.RemoteInterface, uid gregor1.UID, tlfName, topicName string, topicType chat1.TopicType,
vis keybase1.TLFVisibility) (err error) {
// Fetch the TLF ID from specified name
nameInfo, err := CreateNameInfoSource(ctx, g, chat1.ConversationMembersType_TEAM).LookupID(ctx,
tlfName, vis == keybase1.TLFVisibility_PUBLIC)
if err != nil {
debugger.Debug(ctx, "JoinConversationByName: failed to get TLFID from name: %s", err.Error())
return err
}
// List all the conversations on the team
convs, err := g.TeamChannelSource.GetChannelsFull(ctx, uid, nameInfo.ID, topicType)
if err != nil {
return err
}
var convID chat1.ConversationID
for _, conv := range convs {
convTopicName := conv.Info.TopicName
if convTopicName != "" && convTopicName == topicName {
convID = conv.GetConvID()
}
}
if convID.IsNil() {
return fmt.Errorf("no topic name %s exists on specified team", topicName)
}
if err = JoinConversation(ctx, g, debugger, ri, uid, convID); err != nil {
return err
}
return nil
}
func (h *Helper) LeaveConversation(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID) (err error) {
defer h.Trace(ctx, &err, "ChatHelper.LeaveConversation")()
return LeaveConversation(ctx, h.G(), h.DebugLabeler, h.ri, uid, convID)
}
func LeaveConversation(ctx context.Context, g *globals.Context, debugger utils.DebugLabeler,
ri func() chat1.RemoteInterface, uid gregor1.UID, convID chat1.ConversationID) (err error) {
alreadyIn, err := g.InboxSource.IsMember(ctx, uid, convID)
if err != nil {
debugger.Debug(ctx, "LeaveConversation: IsMember err: %s", err.Error())
// Pretend we're in.
alreadyIn = true
}
// Send a message to the channel to leave the conversation
if alreadyIn {
leaveMessageBody := chat1.NewMessageBodyWithLeave(chat1.MessageLeave{})
err := postJoinLeave(ctx, g, ri, uid, convID, leaveMessageBody)
if err != nil {
debugger.Debug(ctx, "LeaveConversation: posting leave-conv message failed: %v", err)
return err
}
} else {
_, err = ri().LeaveConversation(ctx, convID)
if err != nil {
debugger.Debug(ctx, "LeaveConversation: failed to leave conversation as a non-member: %s", err)
return err
}
}
return nil
}
func PreviewConversation(ctx context.Context, g *globals.Context, debugger utils.DebugLabeler,
ri func() chat1.RemoteInterface, uid gregor1.UID, convID chat1.ConversationID) (res chat1.ConversationLocal, err error) {
alreadyIn, err := g.InboxSource.IsMember(ctx, uid, convID)
if err != nil {
debugger.Debug(ctx, "PreviewConversation: IsMember err: %s", err.Error())
// Assume we aren't in, server will reject us otherwise.
alreadyIn = false
}
if alreadyIn {
debugger.Debug(ctx, "PreviewConversation: already in the conversation, no need to preview")
return utils.GetVerifiedConv(ctx, g, uid, convID, types.InboxSourceDataSourceAll)
}
if _, err = ri().PreviewConversation(ctx, convID); err != nil {
debugger.Debug(ctx, "PreviewConversation: failed to preview conversation: %s", err.Error())
return res, err
}
return utils.GetVerifiedConv(ctx, g, uid, convID, types.InboxSourceDataSourceRemoteOnly)
}
func RemoveFromConversation(ctx context.Context, g *globals.Context, debugger utils.DebugLabeler,
ri func() chat1.RemoteInterface, convID chat1.ConversationID, usernames []string) (err error) {
users := make([]gregor1.UID, len(usernames))
for i, username := range usernames {
uid, err := g.GetUPAKLoader().LookupUID(ctx, libkb.NewNormalizedUsername(username))
if err != nil {
return fmt.Errorf("error resolving user %s: %s", username, err)
}
users[i] = uid.ToBytes()
}
_, err = ri().RemoveFromConversation(ctx, chat1.RemoveFromConversationArg{
ConvID: convID,
Users: users,
})
return err
}
type NewConvFindExistingMode int
const (
NewConvFindExistingNormal NewConvFindExistingMode = iota
NewConvFindExistingSkip
)
func NewConversation(ctx context.Context, g *globals.Context, uid gregor1.UID, tlfName string,
topicName *string, topicType chat1.TopicType, membersType chat1.ConversationMembersType,
vis keybase1.TLFVisibility, knownTopicID *chat1.TopicID, ri func() chat1.RemoteInterface,
findExistingMode NewConvFindExistingMode) (chat1.ConversationLocal, bool, error) {
return NewConversationWithMemberSourceConv(ctx, g, uid, tlfName, topicName, topicType, membersType, vis,
knownTopicID, ri, findExistingMode, nil, nil)
}
func NewConversationWithMemberSourceConv(ctx context.Context, g *globals.Context, uid gregor1.UID,
tlfName string, topicName *string, topicType chat1.TopicType, membersType chat1.ConversationMembersType,
vis keybase1.TLFVisibility, knownTopicID *chat1.TopicID, ri func() chat1.RemoteInterface,
findExistingMode NewConvFindExistingMode, retentionPolicy *chat1.RetentionPolicy,
memberSourceConv *chat1.ConversationID) (chat1.ConversationLocal, bool, error) {
defer utils.SuspendComponent(ctx, g, g.ConvLoader)()
helper := newNewConversationHelper(g, uid, tlfName, topicName, topicType, membersType, vis,
ri, findExistingMode, retentionPolicy, memberSourceConv, knownTopicID)
return helper.create(ctx)
}
type newConversationHelper struct {
globals.Contextified
utils.DebugLabeler
uid gregor1.UID
tlfName string
topicName *string
topicType chat1.TopicType
topicID *chat1.TopicID
membersType chat1.ConversationMembersType
memberSourceConv *chat1.ConversationID
vis keybase1.TLFVisibility
ri func() chat1.RemoteInterface
findExistingMode NewConvFindExistingMode
retentionPolicy *chat1.RetentionPolicy
}
func newNewConversationHelper(g *globals.Context, uid gregor1.UID, tlfName string, topicName *string,
topicType chat1.TopicType, membersType chat1.ConversationMembersType, vis keybase1.TLFVisibility,
ri func() chat1.RemoteInterface, findExistingMode NewConvFindExistingMode,
retentionPolicy *chat1.RetentionPolicy, memberSourceConv *chat1.ConversationID,
knownTopicID *chat1.TopicID) *newConversationHelper {
return &newConversationHelper{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), "newConversationHelper", false),
uid: uid,
tlfName: utils.AddUserToTLFName(g, tlfName, vis, membersType),
topicName: topicName,
topicType: topicType,
membersType: membersType,
memberSourceConv: memberSourceConv,
vis: vis,