/
extras.go
3468 lines (3007 loc) · 84.4 KB
/
extras.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 chat1
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"hash"
"math"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/client/go/protocol/keybase1"
)
// we will show some representation of an exploded message in the UI for a week
const ShowExplosionLifetime = time.Hour * 24 * 7
// If a conversation is larger, only admins can @channel.
const MaxChanMentionConvSize = 100
func (i FlipGameIDStr) String() string {
return string(i)
}
func (i TLFIDStr) String() string {
return string(i)
}
func (i ConvIDStr) String() string {
return string(i)
}
type ByUID []gregor1.UID
type ConvIDShort = []byte
func (b ByUID) Len() int { return len(b) }
func (b ByUID) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b ByUID) Less(i, j int) bool {
return bytes.Compare(b[i].Bytes(), b[j].Bytes()) < 0
}
// Eq compares two TLFIDs
func (id TLFID) Eq(other TLFID) bool {
return bytes.Equal([]byte(id), []byte(other))
}
// EqString is like EqualsTo, except that it accepts a fmt.Stringer. This
// can be useful for comparing keybase1.TLFID and chat1.TLFID.
func (id TLFID) EqString(other fmt.Stringer) bool {
return hex.EncodeToString(id) == other.String()
}
func (id TLFID) String() string {
return hex.EncodeToString(id)
}
func (id TLFID) Bytes() []byte {
return []byte(id)
}
func (id TLFID) TLFIDStr() TLFIDStr {
return TLFIDStr(id.String())
}
func (id TLFID) IsNil() bool {
return len(id) == 0
}
func (id TLFID) IsTeamID() bool {
if len(id) != keybase1.TEAMID_LEN {
return false
}
switch id[len(id)-1] {
case keybase1.TEAMID_PRIVATE_SUFFIX,
keybase1.TEAMID_PUBLIC_SUFFIX,
keybase1.SUB_TEAMID_PRIVATE_SUFFIX,
keybase1.SUB_TEAMID_PUBLIC_SUFFIX:
return true
default:
return false
}
}
func MakeConvID(val string) (ConversationID, error) {
return hex.DecodeString(val)
}
func (cid ConversationID) String() string {
return hex.EncodeToString(cid)
}
func (cid ConversationID) Bytes() []byte {
return []byte(cid)
}
func (cid ConversationID) ConvIDStr() ConvIDStr {
return ConvIDStr(cid.String())
}
func (cid ConversationID) IsNil() bool {
return len(cid) < DbShortFormLen
}
func (cid ConversationID) Eq(c ConversationID) bool {
return bytes.Equal(cid, c)
}
func (cid ConversationID) Less(c ConversationID) bool {
return bytes.Compare(cid, c) < 0
}
const DbShortFormLen = 10
// DbShortForm should only be used when interacting with the database, and should
// never leave Gregor
func (cid ConversationID) DbShortForm() ConvIDShort {
end := DbShortFormLen
if end > len(cid) {
end = len(cid)
}
return cid[:end]
}
func (cid ConversationID) DbShortFormString() string {
return DbShortFormToString(cid.DbShortForm())
}
func DbShortFormToString(cid ConvIDShort) string {
return hex.EncodeToString(cid)
}
func DbShortFormFromString(cid string) (ConvIDShort, error) {
return hex.DecodeString(cid)
}
func MakeTLFID(val string) (TLFID, error) {
return hex.DecodeString(val)
}
func MakeTopicID(val string) (TopicID, error) {
return hex.DecodeString(val)
}
func MakeTopicType(val int64) TopicType {
return TopicType(val)
}
func (mid MessageID) String() string {
return strconv.FormatUint(uint64(mid), 10)
}
func (mid MessageID) Min(mid2 MessageID) MessageID {
if mid < mid2 {
return mid
}
return mid2
}
func (mid MessageID) IsNil() bool {
return uint(mid) == 0
}
func (mid MessageID) Advance(num uint) MessageID {
return MessageID(uint(mid) + num)
}
func (t MessageType) String() string {
s, ok := MessageTypeRevMap[t]
if ok {
return s
}
return "UNKNOWN"
}
// Message types deletable by a standard DELETE message.
var deletableMessageTypesByDelete = []MessageType{
MessageType_TEXT,
MessageType_ATTACHMENT,
MessageType_EDIT,
MessageType_ATTACHMENTUPLOADED,
MessageType_REACTION,
MessageType_REQUESTPAYMENT,
MessageType_UNFURL,
MessageType_PIN,
MessageType_HEADLINE,
MessageType_SYSTEM,
MessageType_FLIP,
}
// Messages types NOT deletable by a DELETEHISTORY message.
var nonDeletableMessageTypesByDeleteHistory = []MessageType{
MessageType_NONE,
MessageType_DELETE,
MessageType_TLFNAME,
MessageType_DELETEHISTORY,
}
func DeletableMessageTypesByDelete() []MessageType {
return deletableMessageTypesByDelete
}
func IsSystemMsgDeletableByDelete(typ MessageSystemType) bool {
switch typ {
case MessageSystemType_ADDEDTOTEAM,
MessageSystemType_INVITEADDEDTOTEAM,
MessageSystemType_GITPUSH,
MessageSystemType_CHANGEAVATAR,
MessageSystemType_CHANGERETENTION,
MessageSystemType_BULKADDTOCONV,
MessageSystemType_SBSRESOLVE,
MessageSystemType_NEWCHANNEL:
return true
case MessageSystemType_COMPLEXTEAM,
MessageSystemType_CREATETEAM:
return false
default:
return false
}
}
var visibleMessageTypes = []MessageType{
MessageType_TEXT,
MessageType_ATTACHMENT,
MessageType_JOIN,
MessageType_LEAVE,
MessageType_SYSTEM,
MessageType_SENDPAYMENT,
MessageType_REQUESTPAYMENT,
MessageType_FLIP,
MessageType_HEADLINE,
MessageType_PIN,
}
// Visible chat messages appear visually as a message in the conv.
// For counterexample REACTION and DELETE_HISTORY have visual effects but do not appear as a message.
func VisibleChatMessageTypes() []MessageType {
return visibleMessageTypes
}
var badgeableMessageTypes = []MessageType{
MessageType_TEXT,
MessageType_ATTACHMENT,
MessageType_SYSTEM,
MessageType_SENDPAYMENT,
MessageType_REQUESTPAYMENT,
MessageType_FLIP,
MessageType_HEADLINE,
MessageType_PIN,
}
// Message types that cause badges.
// JOIN and LEAVE are Visible but are too minute to badge.
func BadgeableMessageTypes() []MessageType {
return badgeableMessageTypes
}
// A conversation is considered 'empty' unless it has one of these message types.
// Used for filtering empty convs out of the the inbox.
func NonEmptyConvMessageTypes() []MessageType {
return badgeableMessageTypes
}
var snippetMessageTypes = []MessageType{
MessageType_TEXT,
MessageType_ATTACHMENT,
MessageType_SYSTEM,
MessageType_DELETEHISTORY,
MessageType_SENDPAYMENT,
MessageType_REQUESTPAYMENT,
MessageType_FLIP,
MessageType_HEADLINE,
MessageType_PIN,
}
// Snippet chat messages can be the snippet of a conversation.
func SnippetChatMessageTypes() []MessageType {
return snippetMessageTypes
}
var editableMessageTypesByEdit = []MessageType{
MessageType_TEXT,
MessageType_ATTACHMENT,
}
func EditableMessageTypesByEdit() []MessageType {
return editableMessageTypesByEdit
}
func IsEphemeralSupersederType(typ MessageType) bool {
switch typ {
case MessageType_EDIT,
MessageType_ATTACHMENTUPLOADED,
MessageType_REACTION,
MessageType_UNFURL:
return true
default:
return false
}
}
func IsEphemeralNonSupersederType(typ MessageType) bool {
switch typ {
case MessageType_TEXT,
MessageType_ATTACHMENT,
MessageType_FLIP:
return true
default:
return false
}
}
func IsEphemeralType(typ MessageType) bool {
return IsEphemeralNonSupersederType(typ) || IsEphemeralSupersederType(typ)
}
func DeletableMessageTypesByDeleteHistory() (res []MessageType) {
banned := make(map[MessageType]bool)
for _, mt := range nonDeletableMessageTypesByDeleteHistory {
banned[mt] = true
}
for _, mt := range MessageTypeMap {
if !banned[mt] {
res = append(res, mt)
}
}
sort.Slice(res, func(i, j int) bool {
return res[i] < res[j]
})
return res
}
func IsDeletableByDelete(typ MessageType) bool {
for _, typ2 := range deletableMessageTypesByDelete {
if typ == typ2 {
return true
}
}
return false
}
func IsDeletableByDeleteHistory(typ MessageType) bool {
for _, typ2 := range nonDeletableMessageTypesByDeleteHistory {
if typ == typ2 {
return false
}
}
return true
}
// EphemeralAllowed flags if the given topic type is allowed to send ephemeral
// messages at all.
func (t TopicType) EphemeralAllowed() bool {
switch t {
case TopicType_KBFSFILEEDIT,
TopicType_EMOJI,
TopicType_EMOJICROSS:
return false
default:
return true
}
}
// EphemeralRequired flags if the given topic type required to respect the
// ephemeral retention policy if set.
func (t TopicType) EphemeralRequired() bool {
switch t {
case TopicType_DEV:
return false
default:
return t.EphemeralAllowed()
}
}
func (t TopicType) String() string {
s, ok := TopicTypeRevMap[t]
if ok {
return s
}
return "UNKNOWN"
}
func (t TopicID) String() string {
return hex.EncodeToString(t)
}
func (t TopicID) Eq(r TopicID) bool {
return bytes.Equal([]byte(t), []byte(r))
}
func (t ConversationIDTriple) Eq(other ConversationIDTriple) bool {
return t.Tlfid.Eq(other.Tlfid) &&
bytes.Equal([]byte(t.TopicID), []byte(other.TopicID)) &&
t.TopicType == other.TopicType
}
func (hash Hash) String() string {
return hex.EncodeToString(hash)
}
func (hash Hash) Eq(other Hash) bool {
return bytes.Equal(hash, other)
}
func (m MessageUnboxed) SenderEq(o MessageUnboxed) bool {
if state, err := m.State(); err == nil {
if ostate, err := o.State(); err == nil && state == ostate {
switch state {
case MessageUnboxedState_VALID:
return m.Valid().SenderEq(o.Valid())
case MessageUnboxedState_ERROR:
return m.Error().SenderEq(o.Error())
case MessageUnboxedState_OUTBOX:
return m.Outbox().SenderEq(o.Outbox())
}
}
}
return false
}
func (m MessageUnboxed) OutboxID() *OutboxID {
if state, err := m.State(); err == nil {
switch state {
case MessageUnboxedState_VALID:
return m.Valid().ClientHeader.OutboxID
case MessageUnboxedState_ERROR:
return nil
case MessageUnboxedState_PLACEHOLDER:
return nil
case MessageUnboxedState_OUTBOX:
return m.Outbox().Msg.ClientHeader.OutboxID
default:
return nil
}
}
return nil
}
func (m MessageUnboxed) GetMessageID() MessageID {
if state, err := m.State(); err == nil {
switch state {
case MessageUnboxedState_VALID:
return m.Valid().ServerHeader.MessageID
case MessageUnboxedState_ERROR:
return m.Error().MessageID
case MessageUnboxedState_PLACEHOLDER:
return m.Placeholder().MessageID
case MessageUnboxedState_OUTBOX:
return m.Outbox().Msg.ClientHeader.OutboxInfo.Prev
case MessageUnboxedState_JOURNEYCARD:
return m.Journeycard().PrevID
default:
return 0
}
}
return 0
}
func (m MessageUnboxed) IsEphemeral() bool {
if state, err := m.State(); err == nil {
switch state {
case MessageUnboxedState_VALID:
return m.Valid().IsEphemeral()
case MessageUnboxedState_ERROR:
return m.Error().IsEphemeral
}
}
return false
}
func (m MessageUnboxed) HideExplosion(maxDeletedUpto MessageID, now time.Time) bool {
if state, err := m.State(); err == nil {
switch state {
case MessageUnboxedState_VALID:
return m.Valid().HideExplosion(maxDeletedUpto, now)
case MessageUnboxedState_ERROR:
return m.Error().HideExplosion(maxDeletedUpto, now)
}
}
return false
}
func (m MessageUnboxed) GetOutboxID() *OutboxID {
if state, err := m.State(); err == nil {
switch state {
case MessageUnboxedState_VALID:
return m.Valid().ClientHeader.OutboxID
case MessageUnboxedState_ERROR:
return nil
case MessageUnboxedState_PLACEHOLDER:
return nil
case MessageUnboxedState_OUTBOX:
obid := m.Outbox().OutboxID
return &obid
case MessageUnboxedState_JOURNEYCARD:
return nil
default:
return nil
}
}
return nil
}
func (m MessageUnboxed) GetTopicType() TopicType {
if state, err := m.State(); err == nil {
switch state {
case MessageUnboxedState_VALID:
return m.Valid().ClientHeader.Conv.TopicType
case MessageUnboxedState_ERROR:
return TopicType_NONE
case MessageUnboxedState_OUTBOX:
return m.Outbox().Msg.ClientHeader.Conv.TopicType
case MessageUnboxedState_PLACEHOLDER:
return TopicType_NONE
case MessageUnboxedState_JOURNEYCARD:
return TopicType_NONE
}
}
return TopicType_NONE
}
func (m MessageUnboxed) GetMessageType() MessageType {
if state, err := m.State(); err == nil {
switch state {
case MessageUnboxedState_VALID:
return m.Valid().ClientHeader.MessageType
case MessageUnboxedState_ERROR:
return m.Error().MessageType
case MessageUnboxedState_OUTBOX:
return m.Outbox().Msg.ClientHeader.MessageType
case MessageUnboxedState_PLACEHOLDER:
// All we know about a place holder is the ID, so just
// call it type NONE
return MessageType_NONE
case MessageUnboxedState_JOURNEYCARD:
return MessageType_NONE
}
}
return MessageType_NONE
}
func (m MessageUnboxed) IsValid() bool {
if state, err := m.State(); err == nil {
return state == MessageUnboxedState_VALID
}
return false
}
func (m MessageUnboxed) IsError() bool {
if state, err := m.State(); err == nil {
return state == MessageUnboxedState_ERROR
}
return false
}
func (m MessageUnboxed) IsOutbox() bool {
if state, err := m.State(); err == nil {
return state == MessageUnboxedState_OUTBOX
}
return false
}
func (m MessageUnboxed) IsPlaceholder() bool {
if state, err := m.State(); err == nil {
return state == MessageUnboxedState_PLACEHOLDER
}
return false
}
func (m MessageUnboxed) IsJourneycard() bool {
if state, err := m.State(); err == nil {
return state == MessageUnboxedState_JOURNEYCARD
}
return false
}
// IsValidFull returns whether the message is both:
// 1. Valid
// 2. Has a non-deleted body with a type matching the header
// (TLFNAME is an exception as it has no body)
func (m MessageUnboxed) IsValidFull() bool {
if !m.IsValid() {
return false
}
valid := m.Valid()
headerType := valid.ClientHeader.MessageType
switch headerType {
case MessageType_NONE:
return false
case MessageType_TLFNAME:
// Skip body check
return true
}
bodyType, err := valid.MessageBody.MessageType()
if err != nil {
return false
}
return bodyType == headerType
}
// IsValidDeleted returns whether a message is valid and has been deleted.
// This statement does not hold: IsValidFull != IsValidDeleted
func (m MessageUnboxed) IsValidDeleted() bool {
if !m.IsValid() {
return false
}
valid := m.Valid()
headerType := valid.ClientHeader.MessageType
switch headerType {
case MessageType_NONE:
return false
case MessageType_TLFNAME:
// Undeletable and may have no body
return false
}
bodyType, err := valid.MessageBody.MessageType()
if err != nil {
return false
}
return bodyType == MessageType_NONE
}
func (m MessageUnboxed) IsVisible() bool {
typ := m.GetMessageType()
for _, visType := range VisibleChatMessageTypes() {
if typ == visType {
return true
}
}
return false
}
func (m MessageUnboxed) HasReactions() bool {
if !m.IsValid() {
return false
}
return len(m.Valid().Reactions.Reactions) > 0
}
func (m MessageUnboxed) HasUnfurls() bool {
if !m.IsValid() {
return false
}
return len(m.Valid().Unfurls) > 0
}
func (m MessageUnboxed) SearchableText() string {
if !m.IsValidFull() {
return ""
}
return m.Valid().MessageBody.SearchableText()
}
func (m MessageUnboxed) SenderUsername() string {
if !m.IsValid() {
return ""
}
return m.Valid().SenderUsername
}
func (m MessageUnboxed) Ctime() gregor1.Time {
if !m.IsValid() {
return 0
}
return m.Valid().ServerHeader.Ctime
}
func (m MessageUnboxed) AtMentionUsernames() []string {
if !m.IsValid() {
return nil
}
return m.Valid().AtMentionUsernames
}
func (m MessageUnboxed) ChannelMention() ChannelMention {
if !m.IsValid() {
return ChannelMention_NONE
}
return m.Valid().ChannelMention
}
func (m MessageUnboxed) SenderIsBot() bool {
if m.IsValid() {
valid := m.Valid()
return gregor1.UIDPtrEq(valid.ClientHeader.BotUID, &valid.ClientHeader.Sender)
}
return false
}
func (m *MessageUnboxed) DebugString() string {
if m == nil {
return "[nil]"
}
state, err := m.State()
if err != nil {
return fmt.Sprintf("[INVALID err:%v]", err)
}
if state == MessageUnboxedState_ERROR {
merr := m.Error()
return fmt.Sprintf("[%v %v mt:%v (%v) (%v)]", state, m.GetMessageID(), merr.ErrType, merr.ErrMsg, merr.InternalErrMsg)
}
switch state {
case MessageUnboxedState_VALID:
valid := m.Valid()
headerType := valid.ClientHeader.MessageType
s := fmt.Sprintf("%v %v", state, valid.ServerHeader.MessageID)
bodyType, err := valid.MessageBody.MessageType()
if err != nil {
return fmt.Sprintf("[INVALID-BODY err:%v]", err)
}
if headerType == bodyType {
s = fmt.Sprintf("%v %v", s, headerType)
} else {
if headerType == MessageType_TLFNAME {
s = fmt.Sprintf("%v h:%v (b:%v)", s, headerType, bodyType)
} else {
s = fmt.Sprintf("%v h:%v != b:%v", s, headerType, bodyType)
}
}
if valid.ServerHeader.SupersededBy != 0 {
s = fmt.Sprintf("%v supBy:%v", s, valid.ServerHeader.SupersededBy)
}
return fmt.Sprintf("[%v]", s)
case MessageUnboxedState_OUTBOX:
obr := m.Outbox()
var ostateStr string
ostate, err := obr.State.State()
if err != nil {
ostateStr = "CORRUPT"
} else {
ostateStr = fmt.Sprintf("%v", ostate)
}
return fmt.Sprintf("[%v obid:%v prev:%v ostate:%v %v]",
state, obr.OutboxID, obr.Msg.ClientHeader.OutboxInfo.Prev, ostateStr, obr.Msg.ClientHeader.MessageType)
case MessageUnboxedState_JOURNEYCARD:
jc := m.Journeycard()
return fmt.Sprintf("[JOURNEYCARD %v]", jc.CardType)
default:
return fmt.Sprintf("[state:%v %v]", state, m.GetMessageID())
}
}
func MessageUnboxedDebugStrings(ms []MessageUnboxed) (res []string) {
for _, m := range ms {
res = append(res, m.DebugString())
}
return res
}
func MessageUnboxedDebugList(ms []MessageUnboxed) string {
return fmt.Sprintf("{ %v %v }", len(ms), strings.Join(MessageUnboxedDebugStrings(ms), ","))
}
func MessageUnboxedDebugLines(ms []MessageUnboxed) string {
return strings.Join(MessageUnboxedDebugStrings(ms), "\n")
}
const (
VersionErrorMessageBoxed VersionKind = "messageboxed"
VersionErrorHeader VersionKind = "header"
VersionErrorBody VersionKind = "body"
)
// NOTE: these values correspond to the maximum accepted values in
// chat/boxer.go. If these values are changed, they must also be accepted
// there.
var MaxMessageBoxedVersion MessageBoxedVersion = MessageBoxedVersion_V4
var MaxHeaderVersion HeaderPlaintextVersion = HeaderPlaintextVersion_V1
var MaxBodyVersion BodyPlaintextVersion = BodyPlaintextVersion_V2
// ParseableVersion checks if this error has a version that is now able to be
// understood by our client.
func (m MessageUnboxedError) ParseableVersion() bool {
switch m.ErrType {
case MessageUnboxedErrorType_BADVERSION, MessageUnboxedErrorType_BADVERSION_CRITICAL:
// only applies to these types
default:
return false
}
kind := m.VersionKind
version := m.VersionNumber
// This error was stored from an old client, we have parse out the info we
// need from the error message.
// TODO remove this check once it has be live for a few cycles.
if kind == "" && version == 0 {
re := regexp.MustCompile(`.* Chat version error: \[ unhandled: (\w+) version: (\d+) .*\]`)
matches := re.FindStringSubmatch(m.ErrMsg)
if len(matches) != 3 {
return false
}
kind = VersionKind(matches[1])
var err error
version, err = strconv.Atoi(matches[2])
if err != nil {
return false
}
}
var maxVersion int
switch kind {
case VersionErrorMessageBoxed:
maxVersion = int(MaxMessageBoxedVersion)
case VersionErrorHeader:
maxVersion = int(MaxHeaderVersion)
case VersionErrorBody:
maxVersion = int(MaxBodyVersion)
default:
return false
}
return maxVersion >= version
}
func (m MessageUnboxedError) IsEphemeralError() bool {
return m.IsEphemeral && (m.ErrType == MessageUnboxedErrorType_EPHEMERAL || m.ErrType == MessageUnboxedErrorType_PAIRWISE_MISSING)
}
func (m MessageUnboxedError) IsEphemeralExpired(now time.Time) bool {
if !m.IsEphemeral {
return false
}
etime := m.Etime.Time()
// There are a few ways a message could be considered expired
// 1. We were "exploded now"
// 2. Our lifetime is up
return m.ExplodedBy != nil || etime.Before(now) || etime.Equal(now)
}
func (m MessageUnboxedError) HideExplosion(maxDeletedUpto MessageID, now time.Time) bool {
if !m.IsEphemeral {
return false
}
etime := m.Etime
// Don't show ash lines for messages that have been expunged.
return etime.Time().Add(ShowExplosionLifetime).Before(now) || m.MessageID < maxDeletedUpto
}
func (m MessageUnboxedError) SenderEq(o MessageUnboxedError) bool {
return m.SenderUsername == o.SenderUsername
}
func (m OutboxRecord) SenderEq(o OutboxRecord) bool {
return m.Msg.ClientHeader.Sender.Eq(o.Msg.ClientHeader.Sender)
}
func (m MessageUnboxedValid) AsDeleteHistory() (res MessageDeleteHistory, err error) {
if m.ClientHeader.MessageType != MessageType_DELETEHISTORY {
return res, fmt.Errorf("message is %v not %v", m.ClientHeader.MessageType, MessageType_DELETEHISTORY)
}
if m.MessageBody.IsNil() {
return res, fmt.Errorf("missing message body")
}
btyp, err := m.MessageBody.MessageType()
if err != nil {
return res, err
}
if btyp != MessageType_DELETEHISTORY {
return res, fmt.Errorf("message has wrong body type: %v", btyp)
}
return m.MessageBody.Deletehistory(), nil
}
func (m *MsgEphemeralMetadata) String() string {
if m == nil {
return "<nil>"
}
var explodedBy string
if m.ExplodedBy == nil {
explodedBy = "<nil>"
} else {
explodedBy = *m.ExplodedBy
}
return fmt.Sprintf("{ Lifetime: %v, Generation: %v, ExplodedBy: %v }", m.Lifetime.ToDuration(), m.Generation, explodedBy)
}
func (m MessagePlaintext) MessageType() MessageType {
typ, err := m.MessageBody.MessageType()
if err != nil {
return MessageType_NONE
}
return typ
}
func (m MessagePlaintext) IsVisible() bool {
typ := m.MessageType()
for _, visType := range VisibleChatMessageTypes() {
if typ == visType {
return true
}
}
return false
}
func (m MessagePlaintext) IsBadgableType() bool {
typ := m.MessageType()
switch typ {
case MessageType_TEXT, MessageType_ATTACHMENT:
return true
default:
return false
}
}
func (m MessagePlaintext) SearchableText() string {
return m.MessageBody.SearchableText()
}
func (m MessagePlaintext) IsEphemeral() bool {
return m.EphemeralMetadata() != nil
}
func (m MessagePlaintext) EphemeralMetadata() *MsgEphemeralMetadata {
return m.ClientHeader.EphemeralMetadata
}
func (o *MsgEphemeralMetadata) Eq(r *MsgEphemeralMetadata) bool {
if o != nil && r != nil {
return *o == *r
}
return (o == nil) && (r == nil)
}
func (m MessageUnboxedValid) SenderEq(o MessageUnboxedValid) bool {
return m.ClientHeader.Sender.Eq(o.ClientHeader.Sender)
}
func (m MessageUnboxedValid) HasPairwiseMacs() bool {
return m.ClientHeader.HasPairwiseMacs
}
func (m MessageUnboxedValid) IsEphemeral() bool {
return m.EphemeralMetadata() != nil
}
func (m MessageUnboxedValid) EphemeralMetadata() *MsgEphemeralMetadata {
return m.ClientHeader.EphemeralMetadata
}
func (m MessageUnboxedValid) ExplodedBy() *string {
if !m.IsEphemeral() {
return nil
}
return m.EphemeralMetadata().ExplodedBy
}
func Etime(lifetime gregor1.DurationSec, ctime, rtime, now gregor1.Time) gregor1.Time {
originalLifetime := lifetime.ToDuration()
elapsedLifetime := now.Time().Sub(ctime.Time())
remainingLifetime := originalLifetime - elapsedLifetime
// If the server's view doesn't make sense, just use the signed lifetime
// from the message.
if remainingLifetime > originalLifetime {
remainingLifetime = originalLifetime
}
etime := rtime.Time().Add(remainingLifetime)
return gregor1.ToTime(etime)
}
func (m MessageUnboxedValid) Etime() gregor1.Time {
// The server sends us (untrusted) ctime of the message and server's view
// of now. We use these to calculate the remaining lifetime on an ephemeral
// message, returning an etime based on our received time.
metadata := m.EphemeralMetadata()
if metadata == nil {
return 0
}
header := m.ServerHeader
return Etime(metadata.Lifetime, header.Ctime, m.ClientHeader.Rtime, header.Now)
}
func (m MessageUnboxedValid) RemainingEphemeralLifetime(now time.Time) time.Duration {
remainingLifetime := m.Etime().Time().Sub(now).Round(time.Second)
return remainingLifetime
}
func (m MessageUnboxedValid) IsEphemeralExpired(now time.Time) bool {
if !m.IsEphemeral() {
return false
}
etime := m.Etime().Time()
// There are a few ways a message could be considered expired
// 1. Our body is already nil (deleted from DELETEHISTORY or a server purge)
// 2. We were "exploded now"
// 3. Our lifetime is up
return m.MessageBody.IsNil() || m.EphemeralMetadata().ExplodedBy != nil || etime.Before(now) || etime.Equal(now)
}
func (m MessageUnboxedValid) HideExplosion(maxDeletedUpto MessageID, now time.Time) bool {
if !m.IsEphemeral() {