forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sender.go
1417 lines (1312 loc) · 51.9 KB
/
sender.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"
"time"
"github.com/keybase/client/go/chat/attachments"
"github.com/keybase/client/go/chat/bots"
"github.com/keybase/client/go/chat/globals"
"github.com/keybase/client/go/chat/msgchecker"
"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/engine"
"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"
"github.com/keybase/clockwork"
context "golang.org/x/net/context"
)
type BlockingSender struct {
globals.Contextified
utils.DebugLabeler
boxer *Boxer
store attachments.Store
getRi func() chat1.RemoteInterface
prevPtrPagination *chat1.Pagination
clock clockwork.Clock
}
var _ types.Sender = (*BlockingSender)(nil)
func NewBlockingSender(g *globals.Context, boxer *Boxer, getRi func() chat1.RemoteInterface) *BlockingSender {
return &BlockingSender{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), "BlockingSender", false),
getRi: getRi,
boxer: boxer,
store: attachments.NewS3Store(g, g.GetRuntimeDir()),
clock: clockwork.NewRealClock(),
prevPtrPagination: &chat1.Pagination{Num: 50},
}
}
func (s *BlockingSender) setPrevPagination(p *chat1.Pagination) {
s.prevPtrPagination = p
}
func (s *BlockingSender) SetClock(clock clockwork.Clock) {
s.clock = clock
}
func (s *BlockingSender) addSenderToMessage(msg chat1.MessagePlaintext) (chat1.MessagePlaintext, gregor1.UID, error) {
uid := s.G().Env.GetUID()
if uid.IsNil() {
return chat1.MessagePlaintext{}, nil, libkb.LoginRequiredError{}
}
did := s.G().Env.GetDeviceID()
if did.IsNil() {
return chat1.MessagePlaintext{}, nil, libkb.DeviceRequiredError{}
}
huid := uid.ToBytes()
if huid == nil {
return chat1.MessagePlaintext{}, nil, errors.New("invalid UID")
}
hdid := make([]byte, libkb.DeviceIDLen)
if err := did.ToBytes(hdid); err != nil {
return chat1.MessagePlaintext{}, nil, err
}
header := msg.ClientHeader
header.Sender = gregor1.UID(huid)
header.SenderDevice = gregor1.DeviceID(hdid)
updated := chat1.MessagePlaintext{
ClientHeader: header,
MessageBody: msg.MessageBody,
SupersedesOutboxID: msg.SupersedesOutboxID,
}
return updated, gregor1.UID(huid), nil
}
func (s *BlockingSender) addPrevPointersAndCheckConvID(ctx context.Context, msg chat1.MessagePlaintext,
conv chat1.ConversationLocal) (resMsg chat1.MessagePlaintext, err error) {
// Make sure the caller hasn't already assembled this list. For now, this
// should never happen, and we'll return an error just in case we make a
// mistake in the future. But if there's some use case in the future where
// a caller wants to specify custom prevs, we can relax this.
if len(msg.ClientHeader.Prev) != 0 {
return resMsg, fmt.Errorf("addPrevPointersToMessage expects an empty prev list")
}
var thread chat1.ThreadView
var prevs []chat1.MessagePreviousPointer
pagination := &chat1.Pagination{
Num: s.prevPtrPagination.Num,
}
// If we fail to find anything to prev against after maxAttempts, we allow
// the message to be send with an empty prev list.
maxAttempts := 5
attempt := 0
reachedLast := false
for {
thread, err = s.G().ConvSource.Pull(ctx, conv.GetConvID(), msg.ClientHeader.Sender,
chat1.GetThreadReason_PREPARE, nil,
&chat1.GetThreadQuery{
DisableResolveSupersedes: true,
},
pagination)
if err != nil {
return resMsg, err
} else if thread.Pagination == nil {
break
}
pagination.Next = thread.Pagination.Next
if len(thread.Messages) == 0 {
s.Debug(ctx, "no local messages found for prev pointers")
}
newPrevsForRegular, newPrevsForExploding, err := CheckPrevPointersAndGetUnpreved(&thread)
if err != nil {
return resMsg, err
}
var hasPrev bool
if msg.IsEphemeral() {
prevs = newPrevsForExploding
hasPrev = len(newPrevsForExploding) > 0
} else {
prevs = newPrevsForRegular
// If we have only sent ephemeralMessages and are now sending a regular
// message, we may have an empty list for newPrevsForRegular. In this
// case we allow the `Prev` to be empty, so we don't want to abort in
// the check on numPrev below.
hasPrev = len(newPrevsForRegular) > 0 || len(newPrevsForExploding) > 0
}
if hasPrev {
break
} else if thread.Pagination.Last && !reachedLast {
s.Debug(ctx, "Could not find previous messages for prev pointers (of %v). Nuking local storage and retrying.", len(thread.Messages))
if err := s.G().ConvSource.Clear(ctx, conv.GetConvID(), msg.ClientHeader.Sender, &types.ClearOpts{
SendLocalAdminNotification: true,
Reason: "missing prev pointer",
}); err != nil {
s.Debug(ctx, "Unable to clear conversation: %v, %v", conv.GetConvID(), err)
break
}
attempt = 0
pagination.Next = nil
// Make sure we only reset `attempt` once
reachedLast = true
continue
} else if attempt >= maxAttempts || reachedLast {
s.Debug(ctx, "Could not find previous messages for prev pointers (of %v), after %v attempts. Giving up.", len(thread.Messages), attempt)
break
} else {
s.Debug(ctx, "Could not find previous messages for prev pointers (of %v), attempt: %v of %v, retrying", len(thread.Messages), attempt, maxAttempts)
}
attempt++
}
for _, msg2 := range thread.Messages {
if msg2.IsValid() {
if err = s.checkConvID(ctx, conv, msg, msg2); err != nil {
s.Debug(ctx, "Unable to checkConvID: %s", msg2.DebugString())
return resMsg, err
}
break
}
}
// Make an attempt to avoid changing anything in the input message. There
// are a lot of shared pointers though, so this is
header := msg.ClientHeader
header.Prev = prevs
updated := chat1.MessagePlaintext{
ClientHeader: header,
MessageBody: msg.MessageBody,
}
return updated, nil
}
// Check that the {ConvID,ConvTriple,TlfName} of msgToSend matches both the ConvID and an existing message from the questionable ConvID.
// `convID` is the convID that `msgToSend` will be posted to.
// `msgReference` is a validated message from `convID`.
// The misstep that this method checks for is thus: The frontend may post a message while viewing an "untrusted inbox view".
// That message (msgToSend) will have the header.{TlfName,TlfPublic} set to the user's intention.
// But the header.Conv.{Tlfid,TopicType,TopicID} and the convID to post to may be erroneously set to a different conversation's values.
// This method checks that all of those fields match. Using `msgReference` as the validated link from {TlfName,TlfPublic} <-> ConvTriple.
func (s *BlockingSender) checkConvID(ctx context.Context, conv chat1.ConversationLocal,
msgToSend chat1.MessagePlaintext, msgReference chat1.MessageUnboxed) error {
headerQ := msgToSend.ClientHeader
headerRef := msgReference.Valid().ClientHeader
fmtConv := func(conv chat1.ConversationIDTriple) string { return hex.EncodeToString(conv.Hash()) }
if !headerQ.Conv.Derivable(conv.GetConvID()) {
s.Debug(ctx, "checkConvID: ConvID %s </- %s", fmtConv(headerQ.Conv), conv.GetConvID())
return fmt.Errorf("ConversationID does not match reference message")
}
if !headerQ.Conv.Eq(headerRef.Conv) {
s.Debug(ctx, "checkConvID: Conv %s != %s", fmtConv(headerQ.Conv), fmtConv(headerRef.Conv))
return fmt.Errorf("ConversationID does not match reference message")
}
if headerQ.TlfPublic != headerRef.TlfPublic {
s.Debug(ctx, "checkConvID: TlfPublic %s != %s", headerQ.TlfPublic, headerRef.TlfPublic)
return fmt.Errorf("Chat public-ness does not match reference message")
}
if headerQ.TlfName != headerRef.TlfName {
// If we're of type TEAM, we lookup the name info for the team and
// verify it matches what is on the message itself. If we rename a
// subteam the names between the current and reference message will
// differ so we cannot rely on that.
switch conv.GetMembersType() {
case chat1.ConversationMembersType_TEAM:
// Cannonicalize the given TlfName
teamNameParsed, err := keybase1.TeamNameFromString(headerQ.TlfName)
if err != nil {
return fmt.Errorf("invalid team name: %v", err)
}
if info, err := CreateNameInfoSource(ctx, s.G(), conv.GetMembersType()).LookupName(ctx,
conv.Info.Triple.Tlfid,
conv.Info.Visibility == keybase1.TLFVisibility_PUBLIC,
headerQ.TlfName); err != nil {
return err
} else if info.CanonicalName != teamNameParsed.String() {
return fmt.Errorf("TlfName does not match conversation tlf [%q vs ref %q]", teamNameParsed.String(), info.CanonicalName)
}
default:
// Try normalizing both tlfnames if simple comparison fails because they may have resolved.
if namesEq, err := s.boxer.CompareTlfNames(ctx, headerQ.TlfName, headerRef.TlfName,
conv.GetMembersType(), headerQ.TlfPublic); err != nil {
return err
} else if !namesEq {
s.Debug(ctx, "checkConvID: TlfName %s != %s", headerQ.TlfName, headerRef.TlfName)
return fmt.Errorf("TlfName does not match reference message [%q vs ref %q]", headerQ.TlfName, headerRef.TlfName)
}
}
}
return nil
}
// Get all messages to be deleted, and attachments to delete.
// Returns (message, assetsToDelete, flipConvToDelete, error)
// If the entire conversation is cached locally, this will find all messages that should be deleted.
// If the conversation is not cached, this relies on the server to get old messages, so the server
// could omit messages. Those messages would then not be signed into the `Deletes` list. And their
// associated attachment assets would be left undeleted.
func (s *BlockingSender) getAllDeletedEdits(ctx context.Context, uid gregor1.UID,
convID chat1.ConversationID, msg chat1.MessagePlaintext) (chat1.MessagePlaintext, []chat1.Asset, *chat1.ConversationID, error) {
var pendingAssetDeletes []chat1.Asset
var deleteFlipConvID *chat1.ConversationID
// Make sure this is a valid delete message
if msg.ClientHeader.MessageType != chat1.MessageType_DELETE {
return msg, nil, nil, nil
}
deleteTargetID := msg.ClientHeader.Supersedes
if deleteTargetID == 0 {
return msg, nil, nil, fmt.Errorf("getAllDeletedEdits: no supersedes specified")
}
// Get the one message to be deleted by ID.
deleteTarget, err := s.getMessage(ctx, uid, convID, deleteTargetID, false /* resolveSupersedes */)
if err != nil {
return msg, nil, nil, err
}
bodyTyp, err := deleteTarget.MessageBody.MessageType()
if err != nil {
return msg, nil, nil, err
}
switch bodyTyp {
case chat1.MessageType_REACTION:
// Don't do anything here for reactions/unfurls, they can't be edited
return msg, nil, nil, nil
case chat1.MessageType_SYSTEM:
msgSys := deleteTarget.MessageBody.System()
typ, err := msgSys.SystemType()
if err != nil {
return msg, nil, nil, err
}
if !chat1.IsSystemMsgDeletableByDelete(typ) {
return msg, nil, nil, fmt.Errorf("%v is not deletable", typ)
}
case chat1.MessageType_FLIP:
flipConvID := deleteTarget.MessageBody.Flip().FlipConvID
deleteFlipConvID = &flipConvID
}
// Delete all assets on the deleted message.
// assetsForMessage logs instead of failing.
pads2 := utils.AssetsForMessage(s.G(), deleteTarget.MessageBody)
pendingAssetDeletes = append(pendingAssetDeletes, pads2...)
// Time of the first message to be deleted.
timeOfFirst := gregor1.FromTime(deleteTarget.ServerHeader.Ctime)
// Time a couple seconds before that, because After querying is exclusive.
timeBeforeFirst := gregor1.ToTime(timeOfFirst.Add(-2 * time.Second))
// Get all the affected edits/AUs since just before the delete target.
// Use ConvSource with an `After` which query. Fetches from a combination of local cache
// and the server. This is an opportunity for the server to retain messages that should
// have been deleted without getting caught.
var tv chat1.ThreadView
switch deleteTarget.ClientHeader.MessageType {
case chat1.MessageType_UNFURL:
// no edits/deletes possible here
default:
tv, err = s.G().ConvSource.Pull(ctx, convID, msg.ClientHeader.Sender,
chat1.GetThreadReason_PREPARE, nil,
&chat1.GetThreadQuery{
MarkAsRead: false,
MessageTypes: []chat1.MessageType{chat1.MessageType_EDIT, chat1.MessageType_ATTACHMENTUPLOADED},
After: &timeBeforeFirst,
}, nil)
if err != nil {
return msg, nil, nil, err
}
}
// Get all affected messages to be deleted
deletes := []chat1.MessageID{deleteTargetID}
// Add in any reaction/unfurl messages the deleteTargetID may have
deletes = append(deletes,
append(deleteTarget.ServerHeader.ReactionIDs, deleteTarget.ServerHeader.UnfurlIDs...)...)
for _, m := range tv.Messages {
if !m.IsValid() {
continue
}
body := m.Valid().MessageBody
typ, err := body.MessageType()
if err != nil {
s.Debug(ctx, "getAllDeletedEdits: error getting message type: convID: %s msgID: %d err: %s",
convID, m.GetMessageID(), err.Error())
continue
}
switch typ {
case chat1.MessageType_EDIT:
if body.Edit().MessageID == deleteTargetID {
deletes = append(deletes, m.GetMessageID())
}
case chat1.MessageType_ATTACHMENTUPLOADED:
if body.Attachmentuploaded().MessageID == deleteTargetID {
deletes = append(deletes, m.GetMessageID())
// Delete all assets on AttachmentUploaded's for the deleted message.
// assetsForMessage logs instead of failing.
pads2 = utils.AssetsForMessage(s.G(), body)
pendingAssetDeletes = append(pendingAssetDeletes, pads2...)
}
default:
s.Debug(ctx, "getAllDeletedEdits: unexpected message type: convID: %s msgID: %d typ: %v",
convID, m.GetMessageID(), typ)
continue
}
}
// Modify original delete message
msg.ClientHeader.Deletes = deletes
// NOTE: If we ever add more fields to MessageDelete, we'll need to be
// careful to preserve them here.
msg.MessageBody = chat1.NewMessageBodyWithDelete(chat1.MessageDelete{MessageIDs: deletes})
return msg, pendingAssetDeletes, deleteFlipConvID, nil
}
func (s *BlockingSender) getMessage(ctx context.Context, uid gregor1.UID,
convID chat1.ConversationID, msgID chat1.MessageID, resolveSupersedes bool) (mvalid chat1.MessageUnboxedValid, err error) {
reason := chat1.GetThreadReason_PREPARE
messages, err := s.G().ConvSource.GetMessages(ctx, convID, uid, []chat1.MessageID{msgID},
&reason, nil, resolveSupersedes)
if err != nil {
return mvalid, err
}
if len(messages) == 0 {
return mvalid, fmt.Errorf("getMessage: message not found")
}
if !messages[0].IsValid() {
st, err := messages[0].State()
return mvalid, fmt.Errorf("getMessage returned invalid message: msgID: %v st: %v: err %v",
msgID, st, err)
}
return messages[0].Valid(), nil
}
// If we are superseding an ephemeral message, we have to set the
// ephemeralMetadata on this superseder message.
func (s *BlockingSender) getSupersederEphemeralMetadata(ctx context.Context, uid gregor1.UID,
convID chat1.ConversationID, msg chat1.MessagePlaintext) (metadata *chat1.MsgEphemeralMetadata, err error) {
if chat1.IsEphemeralNonSupersederType(msg.ClientHeader.MessageType) {
// Leave whatever was previously set
return msg.ClientHeader.EphemeralMetadata, nil
} else if !chat1.IsEphemeralSupersederType(msg.ClientHeader.MessageType) {
// clear out any defaults, this msg is a non-ephemeral type
return nil, nil
}
supersededMsg, err := s.getMessage(ctx, uid, convID, msg.ClientHeader.Supersedes, false /* resolveSupersedes */)
if err != nil {
return nil, err
}
if supersededMsg.IsEphemeral() {
metadata = supersededMsg.EphemeralMetadata()
metadata.Lifetime = gregor1.ToDurationSec(supersededMsg.RemainingEphemeralLifetime(s.clock.Now()))
}
return metadata, nil
}
// processReactionMessage determines if we are trying to post a duplicate
// chat1.MessageType_REACTION, which is considered a chat1.MessageType_DELETE
// and updates the send appropriately.
func (s *BlockingSender) processReactionMessage(ctx context.Context, uid gregor1.UID,
convID chat1.ConversationID, msg chat1.MessagePlaintext) (clientHeader chat1.MessageClientHeader, body chat1.MessageBody, err error) {
if msg.ClientHeader.MessageType != chat1.MessageType_REACTION {
// nothing to do here
return msg.ClientHeader, msg.MessageBody, nil
}
// We could either be posting a reaction or removing one that we already posted.
supersededMsg, err := s.getMessage(ctx, uid, convID, msg.ClientHeader.Supersedes,
true /* resolveSupersedes */)
if err != nil {
return clientHeader, body, err
}
found, reactionMsgID := supersededMsg.Reactions.HasReactionFromUser(msg.MessageBody.Reaction().Body,
s.G().Env.GetUsername().String())
if found {
msg.ClientHeader.Supersedes = reactionMsgID
msg.ClientHeader.MessageType = chat1.MessageType_DELETE
msg.ClientHeader.Deletes = []chat1.MessageID{reactionMsgID}
msg.MessageBody = chat1.NewMessageBodyWithDelete(chat1.MessageDelete{
MessageIDs: []chat1.MessageID{reactionMsgID},
})
} else {
// bookkeep the reaction used so we can keep track of the user's
// popular reactions in the UI
if err := storage.NewReacjiStore(s.G()).PutReacji(ctx, uid, msg.MessageBody.Reaction().Body); err != nil {
s.Debug(ctx, "unable to put in ReacjiStore: %v", err)
}
// set an @ mention on the message body for the author of the message we are reacting to
s.Debug(ctx, "processReactionMessage: adding target: %s", supersededMsg.ClientHeader.Sender)
body := msg.MessageBody.Reaction().DeepCopy()
body.TargetUID = &supersededMsg.ClientHeader.Sender
msg.MessageBody = chat1.NewMessageBodyWithReaction(body)
}
return msg.ClientHeader, msg.MessageBody, nil
}
func (s *BlockingSender) checkTopicNameAndGetState(ctx context.Context, msg chat1.MessagePlaintext,
membersType chat1.ConversationMembersType) (topicNameState *chat1.TopicNameState, convIDs []chat1.ConversationID, err error) {
if msg.ClientHeader.MessageType != chat1.MessageType_METADATA {
return topicNameState, convIDs, nil
}
tlfID := msg.ClientHeader.Conv.Tlfid
topicType := msg.ClientHeader.Conv.TopicType
switch topicType {
case chat1.TopicType_EMOJICROSS:
// skip this for this topic type
return topicNameState, convIDs, nil
default:
}
newTopicName := msg.MessageBody.Metadata().ConversationTitle
convs, err := s.G().TeamChannelSource.GetChannelsFull(ctx, msg.ClientHeader.Sender, tlfID, topicType)
if err != nil {
return nil, nil, err
}
var validConvs []chat1.ConversationLocal
for _, conv := range convs {
// If we have a conv error consider the conv invalid. Exclude
// the conv from out TopicNameState forcing the client to retry.
if conv.Error == nil {
if conv.GetTopicName() == "" {
s.Debug(ctx, "checkTopicNameAndGetState: unnamed channel in play: %s", conv.GetConvID())
}
validConvs = append(validConvs, conv)
convIDs = append(convIDs, conv.GetConvID())
} else {
s.Debug(ctx, "checkTopicNameAndGetState: skipping conv: %s, will cause an error from server",
conv.GetConvID())
}
if conv.GetTopicName() == newTopicName {
return nil, nil, DuplicateTopicNameError{Conv: conv}
}
}
ts, err := GetTopicNameState(ctx, s.G(), s.DebugLabeler, validConvs,
msg.ClientHeader.Sender, tlfID, topicType, membersType)
if err != nil {
return nil, nil, err
}
topicNameState = &ts
return topicNameState, convIDs, nil
}
func (s *BlockingSender) resolveOutboxIDEdit(ctx context.Context, uid gregor1.UID,
convID chat1.ConversationID, msg *chat1.MessagePlaintext) error {
if msg.SupersedesOutboxID == nil {
return nil
}
s.Debug(ctx, "resolveOutboxIDEdit: resolving edit: outboxID: %s", msg.SupersedesOutboxID)
typ, err := msg.MessageBody.MessageType()
if err != nil {
return err
}
if typ != chat1.MessageType_EDIT {
return errors.New("supersedes outboxID only valid for edit messages")
}
body := msg.MessageBody.Edit()
// try to find the message with the given outbox ID in the first 50 messages.
tv, err := s.G().ConvSource.Pull(ctx, convID, uid, chat1.GetThreadReason_PREPARE, nil,
&chat1.GetThreadQuery{
MessageTypes: []chat1.MessageType{chat1.MessageType_TEXT},
DisableResolveSupersedes: true,
}, &chat1.Pagination{Num: 50})
if err != nil {
return err
}
for _, m := range tv.Messages {
if msg.SupersedesOutboxID.Eq(m.GetOutboxID()) {
s.Debug(ctx, "resolveOutboxIDEdit: resolved edit: outboxID: %s messageID: %v",
msg.SupersedesOutboxID, m.GetMessageID())
msg.ClientHeader.Supersedes = m.GetMessageID()
msg.MessageBody = chat1.NewMessageBodyWithEdit(chat1.MessageEdit{
MessageID: m.GetMessageID(),
Body: body.Body,
})
return nil
}
}
return errors.New("failed to find message to edit")
}
func (s *BlockingSender) handleReplyTo(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID,
msg chat1.MessagePlaintext, replyTo *chat1.MessageID) (chat1.MessagePlaintext, error) {
if replyTo == nil {
return msg, nil
}
typ, err := msg.MessageBody.MessageType()
if err != nil {
s.Debug(ctx, "handleReplyTo: failed to get body type: %s", err)
return msg, nil
}
switch typ {
case chat1.MessageType_TEXT:
s.Debug(ctx, "handleReplyTo: handling text message")
header := msg.ClientHeader
header.Supersedes = *replyTo
reply, err := s.G().ChatHelper.GetMessage(ctx, uid, convID, *replyTo, false, nil)
if err != nil {
s.Debug(ctx, "handleReplyTo: failed to get reply message: %s", err)
return msg, err
}
if !reply.IsValid() {
s.Debug(ctx, "handleReplyTo: reply message invalid: %v %v", replyTo, err)
return msg, nil
}
replyToUID := reply.Valid().ClientHeader.Sender
newBody := msg.MessageBody.Text().DeepCopy()
newBody.ReplyTo = replyTo
newBody.ReplyToUID = &replyToUID
return chat1.MessagePlaintext{
ClientHeader: header,
MessageBody: chat1.NewMessageBodyWithText(newBody),
SupersedesOutboxID: msg.SupersedesOutboxID,
}, nil
default:
s.Debug(ctx, "handleReplyTo: skipping message of type: %v", typ)
}
return msg, nil
}
func (s *BlockingSender) handleEmojis(ctx context.Context, uid gregor1.UID,
convID chat1.ConversationID, msg chat1.MessagePlaintext, topicType chat1.TopicType) (chat1.MessagePlaintext, error) {
if topicType != chat1.TopicType_CHAT {
return msg, nil
}
typ, err := msg.MessageBody.MessageType()
if err != nil {
s.Debug(ctx, "handleEmojis: failed to get body type: %s", err)
return msg, nil
}
body := msg.MessageBody.TextForDecoration()
if len(body) == 0 {
return msg, nil
}
emojis, err := s.G().EmojiSource.Harvest(ctx, body, uid, convID, types.EmojiHarvestModeNormal)
if err != nil {
return msg, err
}
if len(emojis) == 0 {
return msg, nil
}
ct := make(map[string]chat1.HarvestedEmoji, len(emojis))
for _, emoji := range emojis {
ct[emoji.Alias] = emoji
}
s.Debug(ctx, "handleEmojis: found %d emojis", len(ct))
switch typ {
case chat1.MessageType_TEXT:
newBody := msg.MessageBody.Text().DeepCopy()
newBody.Emojis = ct
return chat1.MessagePlaintext{
ClientHeader: msg.ClientHeader,
MessageBody: chat1.NewMessageBodyWithText(newBody),
SupersedesOutboxID: msg.SupersedesOutboxID,
}, nil
case chat1.MessageType_REACTION:
newBody := msg.MessageBody.Reaction().DeepCopy()
newBody.Emojis = ct
return chat1.MessagePlaintext{
ClientHeader: msg.ClientHeader,
MessageBody: chat1.NewMessageBodyWithReaction(newBody),
SupersedesOutboxID: msg.SupersedesOutboxID,
}, nil
case chat1.MessageType_EDIT:
newBody := msg.MessageBody.Edit().DeepCopy()
newBody.Emojis = ct
return chat1.MessagePlaintext{
ClientHeader: msg.ClientHeader,
MessageBody: chat1.NewMessageBodyWithEdit(newBody),
SupersedesOutboxID: msg.SupersedesOutboxID,
}, nil
case chat1.MessageType_ATTACHMENT:
newBody := msg.MessageBody.Attachment().DeepCopy()
newBody.Emojis = ct
return chat1.MessagePlaintext{
ClientHeader: msg.ClientHeader,
MessageBody: chat1.NewMessageBodyWithAttachment(newBody),
SupersedesOutboxID: msg.SupersedesOutboxID,
}, nil
case chat1.MessageType_HEADLINE:
newBody := msg.MessageBody.Headline().DeepCopy()
newBody.Emojis = ct
return chat1.MessagePlaintext{
ClientHeader: msg.ClientHeader,
MessageBody: chat1.NewMessageBodyWithHeadline(newBody),
SupersedesOutboxID: msg.SupersedesOutboxID,
}, nil
}
return msg, nil
}
func (s *BlockingSender) getUsernamesForMentions(ctx context.Context, uid gregor1.UID,
conv *chat1.ConversationLocal) (res []string, err error) {
if conv == nil {
return nil, nil
}
defer s.Trace(ctx, &err, "getParticipantsForMentions")()
// get the conv that we will look for @ mentions in
switch conv.GetMembersType() {
case chat1.ConversationMembersType_TEAM:
teamID, err := keybase1.TeamIDFromString(conv.Info.Triple.Tlfid.String())
if err != nil {
return res, err
}
team, err := teams.Load(ctx, s.G().ExternalG(), keybase1.LoadTeamArg{
ID: teamID,
})
if err != nil {
return res, err
}
members, err := teams.MembersDetails(ctx, s.G().ExternalG(), team)
if err != nil {
return res, err
}
for _, memb := range members {
res = append(res, memb.Username)
}
return res, nil
default:
res = make([]string, 0, len(conv.Info.Participants))
for _, p := range conv.Info.Participants {
res = append(res, p.Username)
}
return res, nil
}
}
func (s *BlockingSender) handleMentions(ctx context.Context, uid gregor1.UID, msg chat1.MessagePlaintext,
conv *chat1.ConversationLocal) (res chat1.MessagePlaintext, atMentions []gregor1.UID, chanMention chat1.ChannelMention, err error) {
if msg.ClientHeader.Conv.TopicType != chat1.TopicType_CHAT {
return msg, atMentions, chanMention, nil
}
// Function to check that the header and body types match.
// Call this before accessing the body.
// Do not call this for TLFNAME which has no body.
checkHeaderBodyTypeMatch := func() error {
bodyType, err := msg.MessageBody.MessageType()
if err != nil {
return err
}
if msg.ClientHeader.MessageType != bodyType {
return fmt.Errorf("cannot send message with mismatched header/body types: %v != %v",
msg.ClientHeader.MessageType, bodyType)
}
return nil
}
atFromKnown := func(knowns []chat1.KnownUserMention) (res []gregor1.UID) {
for _, known := range knowns {
res = append(res, known.Uid)
}
return res
}
maybeToTeam := func(maybeMentions []chat1.MaybeMention) (res []chat1.KnownTeamMention) {
for _, maybe := range maybeMentions {
if s.G().TeamMentionLoader.IsTeamMention(ctx, uid, maybe, nil) {
res = append(res, chat1.KnownTeamMention(maybe))
}
}
return res
}
// find @ mentions
getConvUsernames := func() ([]string, error) {
return s.getUsernamesForMentions(ctx, uid, conv)
}
var knownUserMentions []chat1.KnownUserMention
var maybeMentions []chat1.MaybeMention
switch msg.ClientHeader.MessageType {
case chat1.MessageType_TEXT:
if err = checkHeaderBodyTypeMatch(); err != nil {
return res, atMentions, chanMention, err
}
knownUserMentions, maybeMentions, chanMention = utils.GetTextAtMentionedItems(ctx, s.G(),
uid, conv.GetConvID(), msg.MessageBody.Text(), getConvUsernames, &s.DebugLabeler)
atMentions = atFromKnown(knownUserMentions)
newBody := msg.MessageBody.Text().DeepCopy()
newBody.TeamMentions = maybeToTeam(maybeMentions)
newBody.UserMentions = knownUserMentions
res = chat1.MessagePlaintext{
ClientHeader: msg.ClientHeader,
MessageBody: chat1.NewMessageBodyWithText(newBody),
SupersedesOutboxID: msg.SupersedesOutboxID,
}
case chat1.MessageType_ATTACHMENT:
if err = checkHeaderBodyTypeMatch(); err != nil {
return res, atMentions, chanMention, err
}
knownUserMentions, maybeMentions, chanMention = utils.ParseAtMentionedItems(ctx, s.G(),
msg.MessageBody.Attachment().GetTitle(), nil, getConvUsernames)
atMentions = atFromKnown(knownUserMentions)
newBody := msg.MessageBody.Attachment().DeepCopy()
newBody.TeamMentions = maybeToTeam(maybeMentions)
newBody.UserMentions = knownUserMentions
res = chat1.MessagePlaintext{
ClientHeader: msg.ClientHeader,
MessageBody: chat1.NewMessageBodyWithAttachment(newBody),
SupersedesOutboxID: msg.SupersedesOutboxID,
}
case chat1.MessageType_FLIP:
if err = checkHeaderBodyTypeMatch(); err != nil {
return res, atMentions, chanMention, err
}
knownUserMentions, maybeMentions, chanMention = utils.ParseAtMentionedItems(ctx, s.G(),
msg.MessageBody.Flip().Text, nil, getConvUsernames)
atMentions = atFromKnown(knownUserMentions)
newBody := msg.MessageBody.Flip().DeepCopy()
newBody.TeamMentions = maybeToTeam(maybeMentions)
newBody.UserMentions = knownUserMentions
res = chat1.MessagePlaintext{
ClientHeader: msg.ClientHeader,
MessageBody: chat1.NewMessageBodyWithFlip(newBody),
SupersedesOutboxID: msg.SupersedesOutboxID,
}
case chat1.MessageType_EDIT:
if err = checkHeaderBodyTypeMatch(); err != nil {
return res, atMentions, chanMention, err
}
knownUserMentions, maybeMentions, chanMention = utils.ParseAtMentionedItems(ctx, s.G(),
msg.MessageBody.Edit().Body, nil, getConvUsernames)
atMentions = atFromKnown(knownUserMentions)
newBody := msg.MessageBody.Edit().DeepCopy()
newBody.TeamMentions = maybeToTeam(maybeMentions)
newBody.UserMentions = knownUserMentions
res = chat1.MessagePlaintext{
ClientHeader: msg.ClientHeader,
MessageBody: chat1.NewMessageBodyWithEdit(newBody),
SupersedesOutboxID: msg.SupersedesOutboxID,
}
case chat1.MessageType_REACTION:
targetUID := msg.MessageBody.Reaction().TargetUID
if targetUID != nil {
atMentions = []gregor1.UID{*targetUID}
}
res = msg
case chat1.MessageType_SYSTEM:
if err = checkHeaderBodyTypeMatch(); err != nil {
return res, atMentions, chanMention, err
}
res = msg
atMentions, chanMention, _ = utils.SystemMessageMentions(ctx, s.G(), uid, msg.MessageBody.System())
default:
res = msg
}
return res, atMentions, chanMention, nil
}
// Prepare a message to be sent.
// Returns (boxedMessage, pendingAssetDeletes, error)
func (s *BlockingSender) Prepare(ctx context.Context, plaintext chat1.MessagePlaintext,
membersType chat1.ConversationMembersType, conv *chat1.ConversationLocal,
inopts *chat1.SenderPrepareOptions) (res types.SenderPrepareResult, err error) {
if plaintext.ClientHeader.MessageType == chat1.MessageType_NONE {
return res, fmt.Errorf("cannot send message without type")
}
// set default options unless some are given to us
var opts chat1.SenderPrepareOptions
if inopts != nil {
opts = *inopts
}
msg, uid, err := s.addSenderToMessage(plaintext)
if err != nil {
return res, err
}
// Make sure our delete message gets everything it should
var pendingAssetDeletes []chat1.Asset
var deleteFlipConvID *chat1.ConversationID
if conv != nil {
convID := conv.GetConvID()
msg.ClientHeader.Conv = conv.Info.Triple
if len(msg.ClientHeader.TlfName) == 0 {
msg.ClientHeader.TlfName = conv.Info.TlfName
msg.ClientHeader.TlfPublic = conv.Info.Visibility == keybase1.TLFVisibility_PUBLIC
}
s.Debug(ctx, "Prepare: performing convID based checks")
// Check for outboxID based edits
if err = s.resolveOutboxIDEdit(ctx, uid, convID, &msg); err != nil {
s.Debug(ctx, "Prepare: error resolving outboxID edit: %s", err)
return res, err
}
// Add and check prev pointers
msg, err = s.addPrevPointersAndCheckConvID(ctx, msg, *conv)
if err != nil {
s.Debug(ctx, "Prepare: error adding prev pointers: %s", err)
return res, err
}
// First process the reactionMessage in case we convert it to a delete
header, body, err := s.processReactionMessage(ctx, uid, convID, msg)
if err != nil {
s.Debug(ctx, "Prepare: error processing reactions: %s", err)
return res, err
}
msg.ClientHeader = header
msg.MessageBody = body
// Handle reply to
if msg, err = s.handleReplyTo(ctx, uid, convID, msg, opts.ReplyTo); err != nil {
s.Debug(ctx, "Prepare: error processing reply: %s", err)
return res, err
}
// Handle cross team emoji
if msg, err = s.handleEmojis(ctx, uid, convID, msg, conv.GetTopicType()); err != nil {
s.Debug(ctx, "Prepare: error processing cross team emoji: %s", err)
return res, err
}
// Be careful not to shadow (msg, pendingAssetDeletes, deleteFlipConvID) with this assignment.
msg, pendingAssetDeletes, deleteFlipConvID, err = s.getAllDeletedEdits(ctx, uid, convID, msg)
if err != nil {
s.Debug(ctx, "Prepare: error getting deleted edits: %s", err)
return res, err
}
if !conv.GetTopicType().EphemeralAllowed() {
if msg.EphemeralMetadata() != nil {
return res, fmt.Errorf("%v messages cannot be ephemeral", conv.GetTopicType())
}
} else {
// If no ephemeral data set, then let's double check to make sure
// no exploding policy or Gregor state should set it if it's required.
if msg.EphemeralMetadata() == nil &&
chat1.IsEphemeralNonSupersederType(msg.ClientHeader.MessageType) &&
conv.GetTopicType().EphemeralRequired() {
s.Debug(ctx, "Prepare: attempting to set ephemeral policy from conversation")
elf, err := utils.EphemeralLifetimeFromConv(ctx, s.G(), *conv)
if err != nil {
s.Debug(ctx, "Prepare: failed to get ephemeral lifetime from conv: %s", err)
elf = nil
}
if elf != nil {
s.Debug(ctx, "Prepare: setting ephemeral lifetime from conv: %v", *elf)
msg.ClientHeader.EphemeralMetadata = &chat1.MsgEphemeralMetadata{
Lifetime: *elf,
}
}
}
msg.ClientHeader.EphemeralMetadata, err = s.getSupersederEphemeralMetadata(ctx, uid, convID, msg)
if err != nil {
s.Debug(ctx, "Prepare: error getting superseder ephemeral metadata: %s", err)
return res, err
}
}
}
// Make sure it is a proper length
if err := msgchecker.CheckMessagePlaintext(msg); err != nil {
s.Debug(ctx, "Prepare: error checking message plaintext: %s", err)
return res, err
}
// Get topic name state if this is a METADATA message, so that we avoid any races to the
// server
var topicNameState *chat1.TopicNameState
var topicNameStateConvs []chat1.ConversationID
if !opts.SkipTopicNameState {
if topicNameState, topicNameStateConvs, err = s.checkTopicNameAndGetState(ctx, msg, membersType); err != nil {
s.Debug(ctx, "Prepare: error checking topic name state: %s", err)
return res, err
}
}
// handle mentions
var atMentions []gregor1.UID
var chanMention chat1.ChannelMention
if msg, atMentions, chanMention, err = s.handleMentions(ctx, uid, msg, conv); err != nil {
s.Debug(ctx, "Prepare: error handling mentions: %s", err)
return res, err
}
// encrypt the message
skp, err := s.getSigningKeyPair(ctx)
if err != nil {
s.Debug(ctx, "Prepare: error getting signing key pair: %s", err)
return res, err
}
// If we are sending a message, and we think the conversation is a KBFS conversation, then set a label
// on the client header in case this conversation gets upgraded to impteam.
msg.ClientHeader.KbfsCryptKeysUsed = new(bool)
if membersType == chat1.ConversationMembersType_KBFS {
s.Debug(ctx, "setting KBFS crypt keys used flag")
*msg.ClientHeader.KbfsCryptKeysUsed = true
} else {
*msg.ClientHeader.KbfsCryptKeysUsed = false
}
var convID *chat1.ConversationID
if conv != nil {
id := conv.GetConvID()
convID = &id
}
botUIDs, err := s.applyTeamBotSettings(ctx, uid, &msg, convID, membersType, atMentions, opts)
if err != nil {
s.Debug(ctx, "Prepare: failed to apply team bot settings: %s", err)
return res, err
}
if len(botUIDs) > 0 {
// TODO HOTPOT-330 Add support for "hidden" messages for multiple bots
msg.ClientHeader.BotUID = &botUIDs[0]
}
s.Debug(ctx, "applyTeamBotSettings: matched %d bots, applied %v", len(botUIDs), msg.ClientHeader.BotUID)
encInfo, err := s.boxer.GetEncryptionInfo(ctx, &msg, membersType, skp)
if err != nil {
s.Debug(ctx, "Prepare: error getting encryption info: %s", err)
return res, err
}
boxed, err := s.boxer.BoxMessage(ctx, msg, membersType, skp, &encInfo)
if err != nil {
s.Debug(ctx, "Prepare: error boxing message: %s", err)
return res, err
}
return types.SenderPrepareResult{
Boxed: boxed,
EncryptionInfo: encInfo,
PendingAssetDeletes: pendingAssetDeletes,
DeleteFlipConv: deleteFlipConvID,
AtMentions: atMentions,
ChannelMention: chanMention,
TopicNameState: topicNameState,
TopicNameStateConvs: topicNameStateConvs,
}, nil
}
func (s *BlockingSender) applyTeamBotSettings(ctx context.Context, uid gregor1.UID,
msg *chat1.MessagePlaintext, convID *chat1.ConversationID, membersType chat1.ConversationMembersType,