/
inboxsource.go
1718 lines (1545 loc) · 58.1 KB
/
inboxsource.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 (
"errors"
"fmt"
"sort"
"strings"
"sync"
"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"
context "golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
func filterConvLocals(convLocals []chat1.ConversationLocal, rquery *chat1.GetInboxQuery,
query *chat1.GetInboxLocalQuery, nameInfo types.NameInfo) (res []chat1.ConversationLocal, err error) {
for _, convLocal := range convLocals {
if rquery != nil && rquery.TlfID != nil {
// inbox query contained a TLF name, so check to make sure that
// the conversation from the server matches tlfInfo from kbfs
if convLocal.Info.TLFNameExpanded() != nameInfo.CanonicalName {
if convLocal.Error == nil {
return nil, fmt.Errorf("server conversation TLF name mismatch: %s, expected %s",
convLocal.Info.TLFNameExpanded(), nameInfo.CanonicalName)
}
}
if convLocal.Info.Visibility != rquery.Visibility() {
return nil, fmt.Errorf("server conversation TLF visibility mismatch: %s, expected %s",
convLocal.Info.Visibility, rquery.Visibility())
}
if !nameInfo.ID.Eq(convLocal.Info.Triple.Tlfid) {
return nil, fmt.Errorf("server conversation TLF ID mismatch: %s, expected %s",
convLocal.Info.Triple.Tlfid, nameInfo.ID)
}
// tlfInfo.ID and rquery.TlfID should always match, but just in case:
if !rquery.TlfID.Eq(convLocal.Info.Triple.Tlfid) {
return nil, fmt.Errorf("server conversation TLF ID mismatch: %s, expected %s",
convLocal.Info.Triple.Tlfid, rquery.TlfID)
}
// Note that previously, we made a call to KBFS to lookup the TLF in
// convLocal.Info.TlfName and verify that, but the above checks accomplish
// the same thing without an RPC call.
}
// server can't query on topic name, so we have to do it ourselves in the loop
if query != nil && query.TopicName != nil && *query.TopicName != convLocal.Info.TopicName {
continue
}
res = append(res, convLocal)
}
return res, nil
}
type baseInboxSource struct {
globals.Contextified
utils.DebugLabeler
so *sourceOfflinable
sub types.InboxSource
getChatInterface func() chat1.RemoteInterface
localizer *localizerPipeline
}
func newBaseInboxSource(g *globals.Context, ibs types.InboxSource,
getChatInterface func() chat1.RemoteInterface) *baseInboxSource {
labeler := utils.NewDebugLabeler(g.GetLog(), "baseInboxSource", false)
return &baseInboxSource{
Contextified: globals.NewContextified(g),
sub: ibs,
DebugLabeler: labeler,
getChatInterface: getChatInterface,
so: newSourceOfflinable(g, labeler),
localizer: newLocalizerPipeline(g),
}
}
func (b *baseInboxSource) notifyTlfFinalize(ctx context.Context, username string) {
// Let the rest of the system know this user has changed
arg := libkb.NewLoadUserArg(b.G().ExternalG()).WithName(username).WithPublicKeyOptional()
finalizeUser, err := libkb.LoadUser(arg)
if err != nil {
b.Debug(ctx, "notifyTlfFinalize: failed to load finalize user, skipping user changed notification: err: %s", err.Error())
} else {
b.G().UserChanged(ctx, finalizeUser.GetUID())
}
}
func (b *baseInboxSource) SetRemoteInterface(ri func() chat1.RemoteInterface) {
b.getChatInterface = ri
}
func (b *baseInboxSource) GetInboxQueryLocalToRemote(ctx context.Context,
lquery *chat1.GetInboxLocalQuery) (rquery *chat1.GetInboxQuery, info types.NameInfo, err error) {
if lquery == nil {
return nil, info, nil
}
rquery = &chat1.GetInboxQuery{}
if lquery.Name != nil && lquery.Name.TlfID != nil {
rquery.TlfID = lquery.Name.TlfID
rquery.MembersTypes = []chat1.ConversationMembersType{lquery.Name.MembersType}
info = types.NameInfo{
CanonicalName: lquery.Name.Name,
ID: *lquery.Name.TlfID,
}
b.Debug(ctx, "GetInboxQueryLocalToRemote: using TLFID: %v", *lquery.Name.TlfID)
} else if lquery.Name != nil && len(lquery.Name.Name) > 0 {
var err error
tlfName := utils.AddUserToTLFName(b.G(), lquery.Name.Name, lquery.Visibility(),
lquery.Name.MembersType)
info, err = CreateNameInfoSource(ctx, b.G(), lquery.Name.MembersType).LookupID(ctx, tlfName,
lquery.Visibility() == keybase1.TLFVisibility_PUBLIC)
if err != nil {
b.Debug(ctx, "GetInboxQueryLocalToRemote: failed: %s", err)
return nil, info, err
}
rquery.TlfID = &info.ID
rquery.MembersTypes = []chat1.ConversationMembersType{lquery.Name.MembersType}
b.Debug(ctx, "GetInboxQueryLocalToRemote: mapped name %q to TLFID %v", tlfName, info.ID)
}
rquery.TopicName = lquery.TopicName
rquery.After = lquery.After
rquery.Before = lquery.Before
rquery.TlfVisibility = lquery.TlfVisibility
rquery.TopicType = lquery.TopicType
rquery.UnreadOnly = lquery.UnreadOnly
rquery.ReadOnly = lquery.ReadOnly
rquery.ComputeActiveList = lquery.ComputeActiveList
rquery.ConvIDs = lquery.ConvIDs
rquery.OneChatTypePerTLF = lquery.OneChatTypePerTLF
rquery.Status = lquery.Status
rquery.MemberStatus = lquery.MemberStatus
rquery.SummarizeMaxMsgs = false
return rquery, info, nil
}
func (b *baseInboxSource) IsMember(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID) (bool, error) {
ib, err := b.sub.ReadUnverified(ctx, uid, types.InboxSourceDataSourceAll, &chat1.GetInboxQuery{
ConvID: &convID,
})
if err != nil {
return false, err
}
if len(ib.ConvsUnverified) == 0 {
return false, fmt.Errorf("conversation not found: %s", convID)
}
conv := ib.ConvsUnverified[0]
switch conv.Conv.ReaderInfo.Status {
case chat1.ConversationMemberStatus_ACTIVE, chat1.ConversationMemberStatus_RESET:
return true, nil
default:
return false, nil
}
}
func (b *baseInboxSource) Localize(ctx context.Context, uid gregor1.UID, convs []types.RemoteConversation,
localizerTyp types.ConversationLocalizerTyp) ([]chat1.ConversationLocal, chan types.AsyncInboxResult, error) {
localizeCb := make(chan types.AsyncInboxResult, len(convs))
localizer := b.createConversationLocalizer(ctx, localizerTyp, localizeCb)
b.Debug(ctx, "Localize: using localizer: %s, convs: %d", localizer.Name(), len(convs))
res, err := localizer.Localize(ctx, uid, types.Inbox{
ConvsUnverified: convs,
}, nil)
return res, localizeCb, err
}
func (b *baseInboxSource) notifyServerAboutReportedConv(mctx libkb.MetaContext, uid gregor1.UID, convID chat1.ConversationID) (err error) {
ctx := mctx.Ctx()
// Send word to API server about the report
defer b.Trace(ctx, func() error { return err }, "notifyServerAboutReportedConv")()
// Get TLF name to post
tlfname := "<error fetching TLF name>"
ib, _, err := b.sub.Read(ctx, uid, types.ConversationLocalizerBlocking, types.InboxSourceDataSourceAll,
nil, &chat1.GetInboxLocalQuery{
ConvIDs: []chat1.ConversationID{convID},
})
if err != nil {
b.Debug(ctx, "notifyServerAboutReportedConv: failed to fetch conversation: %s", err)
} else {
if len(ib.Convs) > 0 {
tlfname = ib.Convs[0].Info.TLFNameExpanded()
}
}
args := libkb.NewHTTPArgs()
args.Add("tlfname", libkb.S{Val: tlfname})
_, err = b.G().API.Post(mctx, libkb.APIArg{
Endpoint: "report/conversation",
SessionType: libkb.APISessionTypeREQUIRED,
Args: args,
})
if err != nil {
b.Debug(ctx, "notifyServerAboutReportedConv: failed to post report: %s", err.Error())
}
return nil
}
// blockOtherUser attempts to do a user-block based on a convID if the conversation is
// impteam and has exactly two members: the active user and the user about to get blocked.
func (b *baseInboxSource) blockOtherUser(mctx libkb.MetaContext, convID chat1.ConversationID) (err error) {
defer b.Trace(mctx.Ctx(), func() error { return err }, "blockOtherUser")()
conversations, err := mctx.G().ChatHelper.FindConversationsByID(mctx.Ctx(), []chat1.ConversationID{convID})
if err != nil {
mctx.Debug("blockOtherUser: error loading conversation by ID", convID, err)
return err
}
if len(conversations) != 1 {
mctx.Debug("blockOtherUser: did not find exactly 1 conversation, so don't user-block")
return nil
}
conv := conversations[0]
if conv.GetMembersType() != chat1.ConversationMembersType_IMPTEAMNATIVE {
mctx.Debug("blockOtherUser: conversation is not an implicit team, so don't user-block")
return nil
}
participants := conv.Info.Participants
if len(participants) != 2 {
mctx.Debug("blockOtherUser: conversation does not have exactly 2 users, so don't user-block")
return nil
}
myName := mctx.G().Env.GetUsername().String()
var otherUser string
var foundMyself bool
for _, participant := range participants {
if myName == participant.Username {
foundMyself = true
} else {
otherUser = participant.Username
}
}
if !foundMyself || otherUser == "" {
mctx.Debug("blockOtherUser: did not find myself and another user, so don't user-block")
return nil
}
otherUserUID, err := mctx.G().GetUPAKLoader().LookupUID(mctx.Ctx(), libkb.NewNormalizedUsername(otherUser))
if err != nil || otherUserUID.String() == "" {
mctx.Debug("blockOtherUser: could not load user and lookup UID, so don't user-block", err)
return nil
}
apiArg := libkb.APIArg{
Endpoint: "user/block",
SessionType: libkb.APISessionTypeREQUIRED,
Args: libkb.HTTPArgs{
"block_uid": libkb.S{Val: otherUserUID.String()},
"unblock": libkb.B{Val: false},
},
}
_, err = mctx.G().API.Post(mctx, apiArg)
_ = mctx.G().CardCache().Delete(keybase1.UID(otherUserUID.String()))
return err
}
func (b *baseInboxSource) RemoteSetConversationStatus(ctx context.Context, uid gregor1.UID,
convID chat1.ConversationID, status chat1.ConversationStatus) (err error) {
mctx := libkb.NewMetaContext(ctx, b.G().ExternalG())
defer b.Trace(ctx, func() error { return err }, "RemoteSetConversationStatus")()
if _, err = b.getChatInterface().SetConversationStatus(ctx, chat1.SetConversationStatusArg{
ConversationID: convID,
Status: status,
}); err != nil {
return err
}
switch status {
case chat1.ConversationStatus_REPORTED:
_ = b.notifyServerAboutReportedConv(mctx, uid, convID)
fallthrough
case chat1.ConversationStatus_BLOCKED:
return b.blockOtherUser(mctx, convID)
}
return nil
}
func (b *baseInboxSource) createConversationLocalizer(ctx context.Context, typ types.ConversationLocalizerTyp,
localizeCb chan types.AsyncInboxResult) conversationLocalizer {
switch typ {
case types.ConversationLocalizerBlocking:
return newBlockingLocalizer(b.G(), b.localizer, localizeCb)
case types.ConversationLocalizerNonblocking:
return newNonblockingLocalizer(b.G(), b.localizer, localizeCb)
default:
b.Debug(ctx, "createConversationLocalizer: warning unknown typ %v, using blockingLocalizer as default", typ)
return newBlockingLocalizer(b.G(), b.localizer, localizeCb)
}
}
func (b *baseInboxSource) Start(ctx context.Context, uid gregor1.UID) {
b.localizer.start(ctx)
}
func (b *baseInboxSource) Stop(ctx context.Context) chan struct{} {
return b.localizer.stop(ctx)
}
func (b *baseInboxSource) Suspend(ctx context.Context) bool {
return b.localizer.suspend(ctx)
}
func (b *baseInboxSource) Resume(ctx context.Context) bool {
return b.localizer.resume(ctx)
}
func (b *baseInboxSource) IsOffline(ctx context.Context) bool {
return b.so.IsOffline(ctx)
}
func (b *baseInboxSource) Connected(ctx context.Context) {
b.so.Connected(ctx)
b.localizer.Connected()
}
func (b *baseInboxSource) Disconnected(ctx context.Context) {
b.so.Disconnected(ctx)
b.localizer.Disconnected()
}
func (b *baseInboxSource) ApplyLocalChatState(ctx context.Context, i []keybase1.BadgeConversationInfo) []keybase1.BadgeConversationInfo {
return i
}
func GetInboxQueryNameInfo(ctx context.Context, g *globals.Context,
lquery *chat1.GetInboxLocalQuery) (res types.NameInfo, err error) {
if lquery.Name == nil {
return res, errors.New("invalid name query")
} else if lquery.Name != nil && len(lquery.Name.Name) > 0 {
if lquery.Name.TlfID != nil {
return CreateNameInfoSource(ctx, g, lquery.Name.MembersType).LookupName(ctx, *lquery.Name.TlfID,
lquery.Visibility() == keybase1.TLFVisibility_PUBLIC, lquery.Name.Name)
}
return CreateNameInfoSource(ctx, g, lquery.Name.MembersType).LookupID(ctx, lquery.Name.Name,
lquery.Visibility() == keybase1.TLFVisibility_PUBLIC)
} else {
return res, errors.New("invalid name query")
}
}
type RemoteInboxSource struct {
globals.Contextified
utils.DebugLabeler
*baseInboxSource
}
var _ types.InboxSource = (*RemoteInboxSource)(nil)
func NewRemoteInboxSource(g *globals.Context, ri func() chat1.RemoteInterface) *RemoteInboxSource {
labeler := utils.NewDebugLabeler(g.GetLog(), "RemoteInboxSource", false)
s := &RemoteInboxSource{
Contextified: globals.NewContextified(g),
DebugLabeler: labeler,
}
s.baseInboxSource = newBaseInboxSource(g, s, ri)
return s
}
func (s *RemoteInboxSource) Clear(ctx context.Context, uid gregor1.UID) error {
return nil
}
func (s *RemoteInboxSource) Read(ctx context.Context, uid gregor1.UID,
localizerTyp types.ConversationLocalizerTyp, dataSource types.InboxSourceDataSourceTyp, maxLocalize *int,
query *chat1.GetInboxLocalQuery) (types.Inbox, chan types.AsyncInboxResult, error) {
rquery, tlfInfo, err := s.GetInboxQueryLocalToRemote(ctx, query)
if err != nil {
return types.Inbox{}, nil, err
}
inbox, err := s.ReadUnverified(ctx, uid, dataSource, rquery)
if err != nil {
return types.Inbox{}, nil, err
}
localizeCb := make(chan types.AsyncInboxResult, len(inbox.ConvsUnverified))
localizer := s.createConversationLocalizer(ctx, localizerTyp, localizeCb)
s.Debug(ctx, "Read: using localizer: %s", localizer.Name())
res, err := localizer.Localize(ctx, uid, inbox, maxLocalize)
if err != nil {
return types.Inbox{}, localizeCb, err
}
res, err = filterConvLocals(res, rquery, query, tlfInfo)
if err != nil {
return types.Inbox{}, localizeCb, err
}
return types.Inbox{
Version: inbox.Version,
Convs: res,
ConvsUnverified: inbox.ConvsUnverified,
}, localizeCb, nil
}
func (s *RemoteInboxSource) ReadUnverified(ctx context.Context, uid gregor1.UID,
dataSource types.InboxSourceDataSourceTyp, rquery *chat1.GetInboxQuery) (types.Inbox, error) {
if s.IsOffline(ctx) {
return types.Inbox{}, OfflineError{}
}
ib, err := s.getChatInterface().GetInboxRemote(ctx, chat1.GetInboxRemoteArg{
Query: rquery,
})
if err != nil {
return types.Inbox{}, err
}
return types.Inbox{
Version: ib.Inbox.Full().Vers,
ConvsUnverified: utils.RemoteConvs(ib.Inbox.Full().Conversations),
}, nil
}
func (s *RemoteInboxSource) MarkAsRead(ctx context.Context, convID chat1.ConversationID,
uid gregor1.UID, msgID *chat1.MessageID) (err error) {
defer s.Trace(ctx, func() error { return err }, "MarkAsRead(%s,%d)", convID, msgID)()
if msgID == nil {
conv, err := utils.GetUnverifiedConv(ctx, s.G(), uid, convID, types.InboxSourceDataSourceAll)
if err != nil {
return err
}
msgID = new(chat1.MessageID)
*msgID = conv.Conv.ReaderInfo.MaxMsgid
}
if _, err = s.getChatInterface().MarkAsRead(ctx, chat1.MarkAsReadArg{
ConversationID: convID,
MsgID: *msgID,
}); err != nil {
return err
}
return nil
}
func (s *RemoteInboxSource) Search(ctx context.Context, uid gregor1.UID, query string, limit int) (res []types.RemoteConversation, err error) {
return nil, errors.New("not implemented")
}
func (s *RemoteInboxSource) IsTeam(ctx context.Context, uid gregor1.UID, item string) (bool, error) {
return false, errors.New("not implemented")
}
func (s *RemoteInboxSource) NewConversation(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
conv chat1.Conversation) error {
return nil
}
func (s *RemoteInboxSource) Sync(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers, convs []chat1.Conversation) (res types.InboxSyncRes, err error) {
return res, nil
}
func (s *RemoteInboxSource) NewMessage(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, msg chat1.MessageBoxed, maxMsgs []chat1.MessageSummary) (*chat1.ConversationLocal, error) {
return nil, nil
}
func (s *RemoteInboxSource) ReadMessage(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, msgID chat1.MessageID) (*chat1.ConversationLocal, error) {
return nil, nil
}
func (s *RemoteInboxSource) SetStatus(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, status chat1.ConversationStatus) (*chat1.ConversationLocal, error) {
return nil, nil
}
func (s *RemoteInboxSource) SetAppNotificationSettings(ctx context.Context, uid gregor1.UID,
vers chat1.InboxVers, convID chat1.ConversationID, settings chat1.ConversationNotificationInfo) (*chat1.ConversationLocal, error) {
return nil, nil
}
func (s *RemoteInboxSource) TlfFinalize(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convIDs []chat1.ConversationID, finalizeInfo chat1.ConversationFinalizeInfo) ([]chat1.ConversationLocal, error) {
// Notify rest of system about reset
s.notifyTlfFinalize(ctx, finalizeInfo.ResetUser)
return nil, nil
}
func (s *RemoteInboxSource) MembershipUpdate(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
joined []chat1.ConversationMember, removed []chat1.ConversationMember, resets []chat1.ConversationMember,
previews []chat1.ConversationID, teamMemberRoleUpdate *chat1.TeamMemberRoleUpdate) (res types.MembershipUpdateRes, err error) {
return res, err
}
func (s *RemoteInboxSource) ConversationsUpdate(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convUpdates []chat1.ConversationUpdate) error {
return nil
}
func (s *RemoteInboxSource) Expunge(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers, convID chat1.ConversationID,
expunge chat1.Expunge, maxMsgs []chat1.MessageSummary) (res *chat1.ConversationLocal, err error) {
return res, err
}
func (s *RemoteInboxSource) SetConvRetention(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, policy chat1.RetentionPolicy) (res *chat1.ConversationLocal, err error) {
return res, err
}
func (s *RemoteInboxSource) SetTeamRetention(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
teamID keybase1.TeamID, policy chat1.RetentionPolicy) (res []chat1.ConversationLocal, err error) {
return res, err
}
func (s *RemoteInboxSource) SetConvSettings(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convID chat1.ConversationID, convSettings *chat1.ConversationSettings) (res *chat1.ConversationLocal, err error) {
return res, err
}
func (s *RemoteInboxSource) SubteamRename(ctx context.Context, uid gregor1.UID, vers chat1.InboxVers,
convIDs []chat1.ConversationID) (convs []chat1.ConversationLocal, err error) {
return convs, err
}
func (s *RemoteInboxSource) TeamTypeChanged(ctx context.Context, uid gregor1.UID,
vers chat1.InboxVers, convID chat1.ConversationID, teamType chat1.TeamType) (conv *chat1.ConversationLocal, err error) {
return conv, err
}
func (s *RemoteInboxSource) UpgradeKBFSToImpteam(ctx context.Context, uid gregor1.UID,
vers chat1.InboxVers, convID chat1.ConversationID) (conv *chat1.ConversationLocal, err error) {
return conv, err
}
func (s *RemoteInboxSource) UpdateInboxVersion(ctx context.Context, uid gregor1.UID,
vers chat1.InboxVers) error {
return nil
}
func (s *RemoteInboxSource) Draft(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID,
text *string) error {
return nil
}
func (s *RemoteInboxSource) MergeLocalMetadata(ctx context.Context, uid gregor1.UID,
convs []chat1.ConversationLocal) error {
return nil
}
func (s *RemoteInboxSource) NotifyUpdate(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID) {
}
func (s *RemoteInboxSource) UpdateLocalMtime(ctx context.Context, uid gregor1.UID, updates []chat1.LocalMtimeUpdate) error {
return nil
}
func (s *RemoteInboxSource) TeamBotSettingsForConv(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID) (
map[keybase1.UID]keybase1.TeamBotSettings, error) {
return nil, nil
}
type HybridInboxSource struct {
sync.Mutex
globals.Contextified
utils.DebugLabeler
*baseInboxSource
uid gregor1.UID
started bool
stopCh chan struct{}
eg errgroup.Group
flushDelay time.Duration
readOutbox *storage.ReadOutbox
readFlushDelay time.Duration
readFlushCh chan struct{}
searchStatusMap map[chat1.ConversationStatus]bool
searchMemberStatusMap map[chat1.ConversationMemberStatus]bool
testFlushCh chan struct{} // testing only
}
var _ types.InboxSource = (*HybridInboxSource)(nil)
func NewHybridInboxSource(g *globals.Context,
getChatInterface func() chat1.RemoteInterface) *HybridInboxSource {
labeler := utils.NewDebugLabeler(g.GetLog(), "HybridInboxSource", false)
s := &HybridInboxSource{
Contextified: globals.NewContextified(g),
DebugLabeler: labeler,
flushDelay: time.Minute,
readFlushDelay: 5 * time.Second,
readFlushCh: make(chan struct{}, 10),
}
s.searchStatusMap = map[chat1.ConversationStatus]bool{
chat1.ConversationStatus_UNFILED: true,
chat1.ConversationStatus_FAVORITE: true,
chat1.ConversationStatus_MUTED: true,
chat1.ConversationStatus_IGNORED: true,
}
s.searchMemberStatusMap = map[chat1.ConversationMemberStatus]bool{
chat1.ConversationMemberStatus_ACTIVE: true,
chat1.ConversationMemberStatus_PREVIEW: true,
chat1.ConversationMemberStatus_RESET: true,
}
s.baseInboxSource = newBaseInboxSource(g, s, getChatInterface)
return s
}
func (s *HybridInboxSource) createInbox() *storage.Inbox {
return storage.NewInbox(s.G(),
storage.FlushMode(storage.InboxFlushModeDelegate),
storage.LayoutChangedNotifier(s.G().UIInboxLoader))
}
func (s *HybridInboxSource) Clear(ctx context.Context, uid gregor1.UID) error {
return s.createInbox().Clear(ctx, uid)
}
func (s *HybridInboxSource) Connected(ctx context.Context) {
defer s.Trace(ctx, func() error { return nil }, "Connected")()
s.baseInboxSource.Connected(ctx)
s.flushMarkAsRead(ctx)
}
func (s *HybridInboxSource) Start(ctx context.Context, uid gregor1.UID) {
defer s.Trace(ctx, func() error { return nil }, "Start")()
s.baseInboxSource.Start(ctx, uid)
s.Lock()
defer s.Unlock()
if s.started {
return
}
s.stopCh = make(chan struct{})
s.started = true
s.uid = uid
s.readOutbox = storage.NewReadOutbox(s.G(), uid)
s.eg.Go(func() error { return s.inboxFlushLoop(uid, s.stopCh) })
s.eg.Go(func() error { return s.markAsReadDeliverLoop(uid, s.stopCh) })
}
func (s *HybridInboxSource) Stop(ctx context.Context) chan struct{} {
defer s.Trace(ctx, func() error { return nil }, "Stop")()
<-s.baseInboxSource.Stop(ctx)
s.Lock()
defer s.Unlock()
ch := make(chan struct{})
if s.started {
close(s.stopCh)
s.started = false
go func() {
_ = s.eg.Wait()
close(ch)
}()
} else {
close(ch)
}
return ch
}
func (s *HybridInboxSource) flushMarkAsRead(ctx context.Context) {
select {
case s.readFlushCh <- struct{}{}:
default:
s.Debug(ctx, "flushMarkAsRead: channel full, dropping")
}
}
func (s *HybridInboxSource) markAsReadDeliver(ctx context.Context) (err error) {
defer func() {
if err != nil {
s.Debug(ctx, "markAsReadDeliver: failed to mark as read: %s", err)
}
}()
recs, err := s.readOutbox.GetRecords(ctx)
if err != nil {
return err
}
for _, rec := range recs {
shouldRemove := false
if _, err := s.getChatInterface().MarkAsRead(ctx, chat1.MarkAsReadArg{
ConversationID: rec.ConvID,
MsgID: rec.MsgID,
}); err != nil {
s.Debug(ctx, "markAsReadDeliver: failed to mark as read: convID: %s msgID: %s err: %s",
rec.ConvID, rec.MsgID, err)
// check for an immediate failure from the server, and get the attempt out if it fails
if berr, ok := err.(DelivererInfoError); ok {
if _, ok := berr.IsImmediateFail(); ok {
s.Debug(ctx, "markAsReadDeliver: error is an immediate failure, not retrying")
shouldRemove = true
}
}
} else {
shouldRemove = true
}
if shouldRemove {
if err := s.readOutbox.RemoveRecord(ctx, rec.ID); err != nil {
s.Debug(ctx, "markAsReadDeliver: failed to remove record: %s", err)
}
}
}
return nil
}
func (s *HybridInboxSource) markAsReadDeliverLoop(uid gregor1.UID, stopCh chan struct{}) error {
ctx := context.Background()
for {
select {
case <-s.readFlushCh:
err := s.markAsReadDeliver(ctx)
if err != nil {
return err
}
case <-s.G().Clock().After(s.readFlushDelay):
err := s.markAsReadDeliver(ctx)
if err != nil {
return err
}
case <-stopCh:
return nil
}
}
}
func makeBadgeConversationInfo(convID keybase1.ChatConversationID, count int) keybase1.BadgeConversationInfo {
return keybase1.BadgeConversationInfo{
ConvID: convID,
BadgeCounts: map[keybase1.DeviceType]int{
keybase1.DeviceType_DESKTOP: count,
keybase1.DeviceType_MOBILE: count,
},
UnreadMessages: count,
}
}
// ApplyLocalChatState marks items locally as read and badges conversations
// that have failed outbox items.
func (s *HybridInboxSource) ApplyLocalChatState(ctx context.Context, infos []keybase1.BadgeConversationInfo) (res []keybase1.BadgeConversationInfo) {
var convIDs []chat1.ConversationID
for _, info := range infos {
if !info.IsEmpty() {
convIDs = append(convIDs, chat1.ConversationID(info.ConvID.Bytes()))
}
}
_, convs, err := s.createInbox().Read(ctx, s.uid, &chat1.GetInboxQuery{
ConvIDs: convIDs,
})
if err != nil {
s.Debug(ctx, "ApplyLocalChatState: failed to get convs: %v", err)
}
// convID -> isRead
readConvMap := make(map[string]bool)
for _, conv := range convs {
if conv.IsLocallyRead() {
readConvMap[conv.GetConvID().String()] = true
}
}
outbox := storage.NewOutbox(s.G(), s.uid)
obrs, oerr := outbox.PullAllConversations(ctx, true /*includeErrors */, false /*remove*/)
if oerr != nil {
s.Debug(ctx, "ApplyLocalChatState: failed to get outbox: %v", oerr)
}
// convID -> unreadCount
failedOutboxMap := make(map[string]int)
// convID -> mtime
localUpdates := make(map[string]chat1.LocalMtimeUpdate)
s.Debug(ctx, "ApplyLocalChatState: looking through %d outbox items for badgable errors", len(obrs))
for _, obr := range obrs {
if topicType := obr.Msg.ClientHeader.Conv.TopicType; !(obr.Msg.IsBadgableType() && topicType == chat1.TopicType_CHAT) {
s.Debug(ctx, "ApplyLocalChatState: skipping msgTyp: %v, topicType: %v", obr.Msg.MessageType(), topicType)
continue
}
state, err := obr.State.State()
if err != nil {
s.Debug(ctx, "ApplyLocalChatState: unknown state item: skipping: err: %v", err)
continue
}
if state == chat1.OutboxStateType_ERROR {
ctime := obr.Ctime
isBadgableError := obr.State.Error().Typ.IsBadgableError()
s.Debug(ctx, "ApplyLocalChatState: found errored outbox item ctime: %v, error: %v, messageType: %v, IsBadgableError: %v",
ctime.Time(), obr.State.Error(), obr.Msg.MessageType(), isBadgableError)
if !isBadgableError {
continue
}
if update, ok := localUpdates[obr.ConvID.String()]; ok {
if ctime.After(update.Mtime) {
localUpdates[obr.ConvID.String()] = update
}
} else {
localUpdates[obr.ConvID.String()] = chat1.LocalMtimeUpdate{
ConvID: obr.ConvID,
Mtime: ctime,
}
}
failedOutboxMap[obr.ConvID.String()]++
}
}
updates := []chat1.LocalMtimeUpdate{}
for _, update := range localUpdates {
updates = append(updates, update)
}
if err := s.createInbox().UpdateLocalMtime(ctx, s.uid, updates); err != nil {
s.Debug(ctx, "ApplyLocalChatState: unable to apply UpdateLocalMtime: %v", err)
}
for _, info := range infos {
// mark this conv as read
if readConvMap[info.ConvID.String()] {
info = makeBadgeConversationInfo(info.ConvID, 0)
s.Debug(ctx, "ApplyLocalChatState, marking as read %+v", info)
}
// badge qualifying failed outbox items
if failedCount, ok := failedOutboxMap[info.ConvID.String()]; ok {
newInfo := makeBadgeConversationInfo(info.ConvID, failedCount)
newInfo.BadgeCounts[keybase1.DeviceType_DESKTOP] += info.BadgeCounts[keybase1.DeviceType_DESKTOP]
newInfo.BadgeCounts[keybase1.DeviceType_MOBILE] += info.BadgeCounts[keybase1.DeviceType_MOBILE]
newInfo.UnreadMessages += info.UnreadMessages
info = newInfo
delete(failedOutboxMap, info.ConvID.String())
s.Debug(ctx, "ApplyLocalChatState, applying failed to existing info %+v", info)
}
res = append(res, info)
}
// apply any new failed outbox items
for convIDStr, failedCount := range failedOutboxMap {
convID, err := chat1.MakeConvID(convIDStr)
if err != nil {
s.Debug(ctx, "ApplyLocalChatState: Unable to make convID: %v", err)
continue
}
newInfo := makeBadgeConversationInfo(keybase1.ChatConversationID(convID), failedCount)
s.Debug(ctx, "ApplyLocalChatState, applying failed to new info %+v", newInfo)
res = append(res, newInfo)
}
return res
}
func (s *HybridInboxSource) Draft(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID,
text *string) error {
if err := s.createInbox().Draft(ctx, uid, convID, text); err != nil {
return err
}
return nil
}
func (s *HybridInboxSource) UpdateLocalMtime(ctx context.Context, uid gregor1.UID, updates []chat1.LocalMtimeUpdate) error {
if err := s.createInbox().UpdateLocalMtime(ctx, uid, updates); err != nil {
return err
}
return nil
}
func (s *HybridInboxSource) MergeLocalMetadata(ctx context.Context, uid gregor1.UID, convs []chat1.ConversationLocal) (err error) {
defer s.Trace(ctx, func() error { return err }, "MergeLocalMetadata")()
return s.createInbox().MergeLocalMetadata(ctx, uid, convs)
}
func (s *HybridInboxSource) NotifyUpdate(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID) {
if err := s.createInbox().IncrementLocalConvVersion(ctx, uid, convID); err != nil {
s.Debug(ctx, "NotifyUpdate: unable to IncrementLocalConvVersion, err", err)
}
conv, err := s.getConvLocal(ctx, uid, convID)
if err != nil {
s.Debug(ctx, "NotifyUpdate: unable to getConvLocal, err", err)
}
var inboxUIItem *chat1.InboxUIItem
topicType := chat1.TopicType_NONE
if conv != nil {
inboxUIItem = PresentConversationLocalWithFetchRetry(ctx, s.G(), uid, *conv)
topicType = conv.GetTopicType()
}
s.G().ActivityNotifier.ConvUpdate(ctx, uid, convID,
topicType, inboxUIItem)
}
func (s *HybridInboxSource) MarkAsRead(ctx context.Context, convID chat1.ConversationID,
uid gregor1.UID, msgID *chat1.MessageID) (err error) {
defer s.Trace(ctx, func() error { return err }, "MarkAsRead(%s,%d)", convID, msgID)()
// Check local copy to see if we have this convo, and have fully read it. If so, we skip the remote call
readRes, err := s.createInbox().GetConversation(ctx, uid, convID)
if err == nil && readRes.GetConvID().Eq(convID) &&
readRes.Conv.ReaderInfo.ReadMsgid == readRes.Conv.ReaderInfo.MaxMsgid {
s.Debug(ctx, "MarkAsRead: conversation fully read: %s, not sending remote call", convID)
return nil
}
if msgID == nil {
conv, err := utils.GetUnverifiedConv(ctx, s.G(), uid, convID, types.InboxSourceDataSourceAll)
if err != nil {
return err
}
msgID = new(chat1.MessageID)
*msgID = conv.Conv.ReaderInfo.MaxMsgid
}
if err := s.createInbox().MarkLocalRead(ctx, uid, convID, *msgID); err != nil {
s.Debug(ctx, "MarkAsRead: failed to mark local read: %s", err)
} else {
if err := s.G().Badger.Send(ctx); err != nil {
return err
}
}
if err := s.readOutbox.PushRead(ctx, convID, *msgID); err != nil {
return err
}
s.flushMarkAsRead(ctx)
return nil
}
func (s *HybridInboxSource) inboxFlushLoop(uid gregor1.UID, stopCh chan struct{}) error {
ctx := globals.ChatCtx(context.Background(), s.G(),
keybase1.TLFIdentifyBehavior_CHAT_SKIP, nil, nil)
appState := s.G().MobileAppState.State()
doFlush := func() {
s.createInbox().Flush(ctx, uid)
if s.testFlushCh != nil {
s.testFlushCh <- struct{}{}
}
}
for {
select {
case <-s.G().Clock().After(s.flushDelay):
doFlush()
case appState = <-s.G().MobileAppState.NextUpdate(&appState):
switch appState {
case keybase1.MobileAppState_BACKGROUND:
doFlush()
default:
// Nothing to do for other app states.
}
case <-stopCh:
doFlush()
return nil
}
}
}
func (s *HybridInboxSource) fetchRemoteInbox(ctx context.Context, uid gregor1.UID,
query *chat1.GetInboxQuery) (res types.Inbox, err error) {
defer s.Trace(ctx, func() error { return err }, "fetchRemoteInbox")()
// Insta fail if we are offline
if s.IsOffline(ctx) {
return types.Inbox{}, OfflineError{}
}
// We always want this on for fetches to fill the local inbox, otherwise we never get the
// full list for the conversations that come back
var rquery chat1.GetInboxQuery
if query == nil {
rquery = chat1.GetInboxQuery{
ComputeActiveList: true,
}
} else {
rquery = *query
rquery.ComputeActiveList = true
}
rquery.SummarizeMaxMsgs = true // always summarize max msgs
ib, err := s.getChatInterface().GetInboxRemote(ctx, chat1.GetInboxRemoteArg{
Query: &rquery,
})
if err != nil {
return types.Inbox{}, err
}
var bgEnqueued int
// Limit the number of jobs we enqueue when on a limited data connection in
// mobile.
maxBgEnqueued := 10
if s.G().MobileNetState.State().IsLimited() {
maxBgEnqueued = 3
}
for _, conv := range ib.Inbox.Full().Conversations {
// Retention policy expunge
expunge := conv.GetExpunge()
if expunge != nil {
err := s.G().ConvSource.Expunge(ctx, conv.GetConvID(), uid, *expunge)
if err != nil {
return types.Inbox{}, err
}
}
if query != nil && query.SkipBgLoads {
continue
}
// Queue all these convs up to be loaded by the background loader. Only
// load first maxBgEnqueued non KBFS convs, ACTIVE convs so we don't
// get the conv loader too backed up.
if conv.Metadata.MembersType != chat1.ConversationMembersType_KBFS &&
(conv.HasMemberStatus(chat1.ConversationMemberStatus_ACTIVE) ||
conv.HasMemberStatus(chat1.ConversationMemberStatus_PREVIEW)) &&
bgEnqueued < maxBgEnqueued {
job := types.NewConvLoaderJob(conv.GetConvID(), &chat1.Pagination{Num: 50},
types.ConvLoaderPriorityMedium, types.ConvLoaderGeneric, nil)