/
utils.go
1565 lines (1424 loc) Β· 45.5 KB
/
utils.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 utils
import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"
"github.com/keybase/client/go/chat/pager"
"github.com/keybase/go-framed-msgpack-rpc/rpc"
"regexp"
"github.com/keybase/client/go/chat/globals"
"github.com/keybase/client/go/chat/types"
"github.com/keybase/client/go/kbfs"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/go-codec/codec"
context "golang.org/x/net/context"
)
// parseDurationExtended is like time.ParseDuration, but adds "d" unit. "1d" is
// one day, defined as 24*time.Hour. Only whole days are supported for "d"
// unit, but it can be followed by smaller units, e.g., "1d1h".
func ParseDurationExtended(s string) (d time.Duration, err error) {
p := strings.Index(s, "d")
if p == -1 {
// no "d" suffix
return time.ParseDuration(s)
}
var days int
if days, err = strconv.Atoi(s[:p]); err != nil {
return time.Duration(0), err
}
d = time.Duration(days) * 24 * time.Hour
if p < len(s)-1 {
var dur time.Duration
if dur, err = time.ParseDuration(s[p+1:]); err != nil {
return time.Duration(0), err
}
d += dur
}
return d, nil
}
func ParseTimeFromRFC3339OrDurationFromPast(g *globals.Context, s string) (t time.Time, err error) {
var errt, errd error
var d time.Duration
if s == "" {
return
}
if t, errt = time.Parse(time.RFC3339, s); errt == nil {
return t, nil
}
if d, errd = ParseDurationExtended(s); errd == nil {
return g.Clock().Now().Add(-d), nil
}
return time.Time{}, fmt.Errorf("given string is neither a valid time (%s) nor a valid duration (%v)", errt, errd)
}
// upper bounds takes higher priority
func Collar(lower int, ideal int, upper int) int {
if ideal > upper {
return upper
}
if ideal < lower {
return lower
}
return ideal
}
// AggRateLimitsP takes a list of rate limit responses and dedups them to the last one received
// of each category
func AggRateLimitsP(rlimits []*chat1.RateLimit) (res []chat1.RateLimit) {
m := make(map[string]chat1.RateLimit)
for _, l := range rlimits {
if l != nil {
m[l.Name] = *l
}
}
for _, v := range m {
res = append(res, v)
}
return res
}
func AggRateLimits(rlimits []chat1.RateLimit) (res []chat1.RateLimit) {
m := make(map[string]chat1.RateLimit)
for _, l := range rlimits {
m[l.Name] = l
}
for _, v := range m {
res = append(res, v)
}
return res
}
// ReorderParticipants based on the order in activeList.
// Only allows usernames from tlfname in the output.
// This never fails, worse comes to worst it just returns the split of tlfname.
func ReorderParticipants(mctx libkb.MetaContext, g libkb.UIDMapperContext, umapper libkb.UIDMapper,
tlfname string, activeList []gregor1.UID) (writerNames []chat1.ConversationLocalParticipant, err error) {
srcWriterNames, _, _, err := splitAndNormalizeTLFNameCanonicalize(mctx.G(), tlfname, false)
if err != nil {
return writerNames, err
}
var activeKuids []keybase1.UID
for _, a := range activeList {
activeKuids = append(activeKuids, keybase1.UID(a.String()))
}
packages, err := umapper.MapUIDsToUsernamePackages(mctx.Ctx(), g, activeKuids, time.Hour*24, 10*time.Second,
true)
activeMap := make(map[string]chat1.ConversationLocalParticipant)
if err == nil {
for i := 0; i < len(activeKuids); i++ {
activeMap[activeKuids[i].String()] = UsernamePackageToParticipant(packages[i])
}
}
allowedWriters := make(map[string]bool)
// Allow all writers from tlfname.
for _, user := range srcWriterNames {
allowedWriters[user] = true
}
// Fill from the active list first.
for _, uid := range activeList {
kbUID := keybase1.UID(uid.String())
p, ok := activeMap[kbUID.String()]
if !ok {
continue
}
if allowed, _ := allowedWriters[p.Username]; allowed {
writerNames = append(writerNames, p)
// Allow only one occurrence.
allowedWriters[p.Username] = false
}
}
// Include participants even if they weren't in the active list, in stable order.
for _, user := range srcWriterNames {
if allowed, _ := allowedWriters[user]; allowed {
writerNames = append(writerNames, UsernamePackageToParticipant(libkb.UsernamePackage{
NormalizedUsername: libkb.NewNormalizedUsername(user),
FullName: nil,
}))
allowedWriters[user] = false
}
}
return writerNames, nil
}
// Drive splitAndNormalizeTLFName with one attempt to follow TlfNameNotCanonical.
func splitAndNormalizeTLFNameCanonicalize(g *libkb.GlobalContext, name string, public bool) (writerNames, readerNames []string, extensionSuffix string, err error) {
writerNames, readerNames, extensionSuffix, err = kbfs.SplitAndNormalizeTLFName(g, name, public)
if retryErr, retry := err.(kbfs.TlfNameNotCanonical); retry {
return kbfs.SplitAndNormalizeTLFName(g, retryErr.NameToTry, public)
}
return writerNames, readerNames, extensionSuffix, err
}
const (
ChatTopicIDLen = 16
ChatTopicIDSuffix = 0x20
)
func NewChatTopicID() (id []byte, err error) {
if id, err = libkb.RandBytes(ChatTopicIDLen); err != nil {
return nil, err
}
id[len(id)-1] = ChatTopicIDSuffix
return id, nil
}
func AllChatConversationStatuses() (res []chat1.ConversationStatus) {
for _, s := range chat1.ConversationStatusMap {
res = append(res, s)
}
sort.Sort(byConversationStatus(res))
return
}
// ConversationStatusBehavior describes how a ConversationStatus behaves
type ConversationStatusBehavior struct {
// Whether to show the conv in the inbox
ShowInInbox bool
// Whether sending to this conv sets it back to UNFILED
SendingRemovesStatus bool
// Whether any incoming activity sets it back to UNFILED
ActivityRemovesStatus bool
// Whether to show desktop notifications
DesktopNotifications bool
// Whether to send push notifications
PushNotifications bool
// Whether to show as part of badging
ShowBadges bool
}
// ConversationMemberStatusBehavior describes how a ConversationMemberStatus behaves
type ConversationMemberStatusBehavior struct {
// Whether to show the conv in the inbox
ShowInInbox bool
// Whether to show desktop notifications
DesktopNotifications bool
// Whether to send push notifications
PushNotifications bool
// Whether to show as part of badging
ShowBadges bool
}
func GetConversationMemberStatusBehavior(s chat1.ConversationMemberStatus) ConversationMemberStatusBehavior {
switch s {
case chat1.ConversationMemberStatus_ACTIVE:
return ConversationMemberStatusBehavior{
ShowInInbox: true,
DesktopNotifications: true,
PushNotifications: true,
ShowBadges: true,
}
case chat1.ConversationMemberStatus_PREVIEW:
return ConversationMemberStatusBehavior{
ShowInInbox: true,
DesktopNotifications: true,
PushNotifications: true,
ShowBadges: true,
}
case chat1.ConversationMemberStatus_LEFT:
return ConversationMemberStatusBehavior{
ShowInInbox: false,
DesktopNotifications: false,
PushNotifications: false,
ShowBadges: false,
}
case chat1.ConversationMemberStatus_REMOVED:
return ConversationMemberStatusBehavior{
ShowInInbox: false,
DesktopNotifications: false,
PushNotifications: false,
ShowBadges: false,
}
case chat1.ConversationMemberStatus_RESET:
return ConversationMemberStatusBehavior{
ShowInInbox: true,
DesktopNotifications: false,
PushNotifications: false,
ShowBadges: false,
}
default:
return ConversationMemberStatusBehavior{
ShowInInbox: true,
DesktopNotifications: true,
PushNotifications: true,
ShowBadges: true,
}
}
}
// GetConversationStatusBehavior gives information about what is allowed for a conversation status.
// When changing these, be sure to update gregor's postMessage as well
func GetConversationStatusBehavior(s chat1.ConversationStatus) ConversationStatusBehavior {
switch s {
case chat1.ConversationStatus_UNFILED:
return ConversationStatusBehavior{
ShowInInbox: true,
SendingRemovesStatus: false,
ActivityRemovesStatus: false,
DesktopNotifications: true,
PushNotifications: true,
ShowBadges: true,
}
case chat1.ConversationStatus_FAVORITE:
return ConversationStatusBehavior{
ShowInInbox: true,
SendingRemovesStatus: false,
ActivityRemovesStatus: false,
DesktopNotifications: true,
PushNotifications: true,
ShowBadges: true,
}
case chat1.ConversationStatus_IGNORED:
return ConversationStatusBehavior{
ShowInInbox: false,
SendingRemovesStatus: true,
ActivityRemovesStatus: true,
DesktopNotifications: true,
PushNotifications: true,
ShowBadges: true,
}
case chat1.ConversationStatus_REPORTED:
fallthrough
case chat1.ConversationStatus_BLOCKED:
return ConversationStatusBehavior{
ShowInInbox: false,
SendingRemovesStatus: true,
ActivityRemovesStatus: false,
DesktopNotifications: false,
PushNotifications: false,
ShowBadges: false,
}
case chat1.ConversationStatus_MUTED:
return ConversationStatusBehavior{
ShowInInbox: true,
SendingRemovesStatus: false,
ActivityRemovesStatus: false,
DesktopNotifications: false,
PushNotifications: false,
ShowBadges: false,
}
default:
return ConversationStatusBehavior{
ShowInInbox: true,
SendingRemovesStatus: false,
ActivityRemovesStatus: false,
DesktopNotifications: true,
PushNotifications: true,
ShowBadges: true,
}
}
}
type byConversationStatus []chat1.ConversationStatus
func (c byConversationStatus) Len() int { return len(c) }
func (c byConversationStatus) Less(i, j int) bool { return c[i] < c[j] }
func (c byConversationStatus) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
// Which convs show in the inbox.
func VisibleChatConversationStatuses() (res []chat1.ConversationStatus) {
for _, s := range chat1.ConversationStatusMap {
if GetConversationStatusBehavior(s).ShowInInbox {
res = append(res, s)
}
}
sort.Sort(byConversationStatus(res))
return
}
func IsVisibleChatMessageType(messageType chat1.MessageType) bool {
for _, mt := range chat1.VisibleChatMessageTypes() {
if messageType == mt {
return true
}
}
return false
}
func IsNotifiableChatMessageType(messageType chat1.MessageType, atMentions []gregor1.UID, chanMention chat1.ChannelMention) bool {
if IsVisibleChatMessageType(messageType) {
return true
}
if messageType != chat1.MessageType_EDIT {
return false
}
// an edit with atMention or channel mention should generate notifications
if len(atMentions) > 0 || chanMention != chat1.ChannelMention_NONE {
return true
}
return false
}
type DebugLabeler struct {
log logger.Logger
label string
verbose bool
}
func NewDebugLabeler(log logger.Logger, label string, verbose bool) DebugLabeler {
return DebugLabeler{
log: log.CloneWithAddedDepth(1),
label: label,
verbose: verbose,
}
}
func (d DebugLabeler) GetLog() logger.Logger {
return d.log
}
func (d DebugLabeler) showVerbose() bool {
return false
}
func (d DebugLabeler) showLog() bool {
if d.verbose {
return d.showVerbose()
}
return true
}
func (d DebugLabeler) Debug(ctx context.Context, msg string, args ...interface{}) {
if d.showLog() {
d.log.CDebugf(ctx, "++Chat: | "+d.label+": "+msg, args...)
}
}
func (d DebugLabeler) Trace(ctx context.Context, f func() error, format string, args ...interface{}) func() {
if d.showLog() {
msg := fmt.Sprintf(format, args...)
start := time.Now()
d.log.CDebugf(ctx, "++Chat: + %s: %s", d.label, msg)
return func() {
d.log.CDebugf(ctx, "++Chat: - %s: %s -> %s [time=%v]", d.label, msg,
libkb.ErrToOk(f()), time.Since(start))
}
}
return func() {}
}
// FilterByType filters messages based on a query.
// If includeAllErrors then MessageUnboxedError are all returned. Otherwise, they are filtered based on type.
// Messages whose type cannot be determined are considered errors.
func FilterByType(msgs []chat1.MessageUnboxed, query *chat1.GetThreadQuery, includeAllErrors bool) (res []chat1.MessageUnboxed) {
useTypeFilter := (query != nil && len(query.MessageTypes) > 0)
typmap := make(map[chat1.MessageType]bool)
if useTypeFilter {
for _, mt := range query.MessageTypes {
typmap[mt] = true
}
}
for _, msg := range msgs {
state, err := msg.State()
if err != nil {
if includeAllErrors {
res = append(res, msg)
}
continue
}
switch state {
case chat1.MessageUnboxedState_ERROR:
if includeAllErrors {
res = append(res, msg)
}
case chat1.MessageUnboxedState_PLACEHOLDER:
// We don't know what the type is for these, so just include them
res = append(res, msg)
default:
_, match := typmap[msg.GetMessageType()]
if !useTypeFilter || match {
res = append(res, msg)
}
}
}
return res
}
// Filter messages that are both exploded that are no longer shown in the GUI
// (as ash lines)
func FilterExploded(expunge *chat1.Expunge, msgs []chat1.MessageUnboxed, now time.Time) (res []chat1.MessageUnboxed) {
for _, msg := range msgs {
if msg.IsValid() {
mvalid := msg.Valid()
if mvalid.IsEphemeral() && mvalid.HideExplosion(expunge, now) {
continue
}
} else if msg.IsError() {
// If we had an error on an expired message, it's irrelevant now
// that the message has exploded so we hide it.
merr := msg.Error()
if merr.IsEphemeral && merr.IsEphemeralExpired {
continue
}
}
res = append(res, msg)
}
return res
}
// GetSupersedes must be called with a valid msg
func GetSupersedes(msg chat1.MessageUnboxed) ([]chat1.MessageID, error) {
if !msg.IsValidFull() {
return nil, fmt.Errorf("GetSupersedes called with invalid message: %v", msg.GetMessageID())
}
body := msg.Valid().MessageBody
typ, err := body.MessageType()
if err != nil {
return nil, err
}
// We use the message ID in the body over the field in the client header to
// avoid server trust.
switch typ {
case chat1.MessageType_EDIT:
return []chat1.MessageID{msg.Valid().MessageBody.Edit().MessageID}, nil
case chat1.MessageType_REACTION:
return []chat1.MessageID{msg.Valid().MessageBody.Reaction().MessageID}, nil
case chat1.MessageType_DELETE:
return msg.Valid().MessageBody.Delete().MessageIDs, nil
case chat1.MessageType_ATTACHMENTUPLOADED:
return []chat1.MessageID{msg.Valid().MessageBody.Attachmentuploaded().MessageID}, nil
default:
return nil, nil
}
}
var chanNameMentionRegExp = regexp.MustCompile(`\B#([0-9a-zA-Z_-]+)`)
func ParseChannelNameMentions(ctx context.Context, body string, uid gregor1.UID, teamID chat1.TLFID,
ts types.TeamChannelSource) (res []chat1.ChannelNameMention) {
names := parseRegexpNames(ctx, body, chanNameMentionRegExp)
if len(names) == 0 {
return nil
}
chanResponse, err := ts.GetChannelsTopicName(ctx, uid, teamID, chat1.TopicType_CHAT)
if err != nil {
return nil
}
validChans := make(map[string]chat1.ChannelNameMention)
for _, cr := range chanResponse {
validChans[cr.TopicName] = cr
}
for _, name := range names {
if cr, ok := validChans[name]; ok {
res = append(res, cr)
}
}
return res
}
var atMentionRegExp = regexp.MustCompile(`\B@([a-z0-9][a-z0-9_]+)`)
func parseRegexpNames(ctx context.Context, body string, re *regexp.Regexp) (res []string) {
matches := re.FindAllStringSubmatch(body, -1)
for _, m := range matches {
if len(m) >= 2 {
res = append(res, m[1])
}
}
return res
}
func ParseAtMentionsNames(ctx context.Context, body string) (res []string) {
return parseRegexpNames(ctx, body, atMentionRegExp)
}
func ParseAtMentionedUIDs(ctx context.Context, body string, upak libkb.UPAKLoader, debug *DebugLabeler) (atRes []gregor1.UID, chanRes chat1.ChannelMention) {
names := ParseAtMentionsNames(ctx, body)
chanRes = chat1.ChannelMention_NONE
for _, name := range names {
switch name {
case "channel", "everyone":
chanRes = chat1.ChannelMention_ALL
continue
case "here":
if chanRes != chat1.ChannelMention_ALL {
chanRes = chat1.ChannelMention_HERE
}
continue
default:
}
kuid, err := upak.LookupUID(ctx, libkb.NewNormalizedUsername(name))
if err != nil {
if debug != nil {
debug.Debug(ctx, "ParseAtMentionedUIDs: failed to lookup UID for: %s msg: %s",
name, err.Error())
}
continue
}
atRes = append(atRes, kuid.ToBytes())
}
return atRes, chanRes
}
func ParseAndDecorateAtMentionedUIDs(ctx context.Context, body string, upak libkb.UPAKLoader, debug *DebugLabeler) (newBody string, atRes []gregor1.UID, chanRes chat1.ChannelMention) {
atRes, chanRes = ParseAtMentionedUIDs(ctx, body, upak, debug)
newBody = atMentionRegExp.ReplaceAllStringFunc(body, func(m string) string {
replace := false
switch m {
case "@channel", "@here", "@everyone":
replace = true
default:
toks := strings.Split(m, "@")
if len(toks) == 2 {
_, err := upak.LookupUID(ctx, libkb.NewNormalizedUsername(toks[1]))
if err == nil {
replace = true
}
}
}
if replace {
return fmt.Sprintf("`%s`", m)
}
return m
})
return newBody, atRes, chanRes
}
type SystemMessageUIDSource interface {
LookupUID(ctx context.Context, un libkb.NormalizedUsername) (keybase1.UID, error)
}
func SystemMessageMentions(ctx context.Context, body chat1.MessageSystem, upak SystemMessageUIDSource) (atMentions []gregor1.UID, chanMention chat1.ChannelMention) {
typ, err := body.SystemType()
if err != nil {
return atMentions, chanMention
}
switch typ {
case chat1.MessageSystemType_ADDEDTOTEAM:
addeeUID, err := upak.LookupUID(ctx, libkb.NewNormalizedUsername(body.Addedtoteam().Addee))
if err == nil {
atMentions = append(atMentions, addeeUID.ToBytes())
}
case chat1.MessageSystemType_INVITEADDEDTOTEAM:
inviteeUID, err := upak.LookupUID(ctx, libkb.NewNormalizedUsername(body.Inviteaddedtoteam().Invitee))
if err == nil {
atMentions = append(atMentions, inviteeUID.ToBytes())
}
inviterUID, err := upak.LookupUID(ctx, libkb.NewNormalizedUsername(body.Inviteaddedtoteam().Inviter))
if err == nil {
atMentions = append(atMentions, inviterUID.ToBytes())
}
case chat1.MessageSystemType_COMPLEXTEAM:
chanMention = chat1.ChannelMention_ALL
}
sort.Sort(chat1.ByUID(atMentions))
return atMentions, chanMention
}
func PluckMessageIDs(msgs []chat1.MessageSummary) []chat1.MessageID {
res := make([]chat1.MessageID, len(msgs))
for i, m := range msgs {
res[i] = m.GetMessageID()
}
return res
}
func PluckUIMessageIDs(msgs []chat1.UIMessage) (res []chat1.MessageID) {
for _, m := range msgs {
res = append(res, m.GetMessageID())
}
return res
}
func PluckMUMessageIDs(msgs []chat1.MessageUnboxed) (res []chat1.MessageID) {
for _, m := range msgs {
res = append(res, m.GetMessageID())
}
return res
}
func IsConvEmpty(conv chat1.Conversation) bool {
switch conv.GetMembersType() {
case chat1.ConversationMembersType_TEAM:
return false
default:
for _, msg := range conv.MaxMsgSummaries {
if IsVisibleChatMessageType(msg.GetMessageType()) {
return false
}
}
return true
}
}
func PluckConvIDsLocal(convs []chat1.ConversationLocal) (res []chat1.ConversationID) {
for _, conv := range convs {
res = append(res, conv.GetConvID())
}
return res
}
func PluckConvIDs(convs []chat1.Conversation) (res []chat1.ConversationID) {
for _, conv := range convs {
res = append(res, conv.GetConvID())
}
return res
}
func PluckConvIDsRC(convs []types.RemoteConversation) (res []chat1.ConversationID) {
for _, conv := range convs {
res = append(res, conv.GetConvID())
}
return res
}
func SanitizeTopicName(topicName string) string {
return strings.TrimPrefix(topicName, "#")
}
func CreateTopicNameState(cmp chat1.ConversationIDMessageIDPairs) (chat1.TopicNameState, error) {
var data []byte
var err error
mh := codec.MsgpackHandle{WriteExt: true}
enc := codec.NewEncoderBytes(&data, &mh)
if err = enc.Encode(cmp); err != nil {
return chat1.TopicNameState{}, err
}
h := sha256.New()
if _, err = h.Write(data); err != nil {
return chat1.TopicNameState{}, err
}
return h.Sum(nil), nil
}
func GetConvMtime(conv chat1.Conversation) gregor1.Time {
var summaries []chat1.MessageSummary
for _, typ := range chat1.VisibleChatMessageTypes() {
summary, err := conv.GetMaxMessage(typ)
if err == nil {
summaries = append(summaries, summary)
}
}
if len(summaries) == 0 {
return conv.ReaderInfo.Mtime
}
sort.Sort(ByMsgSummaryCtime(summaries))
return summaries[len(summaries)-1].Ctime
}
func PickLatestMessageSummary(conv chat1.Conversation, typs []chat1.MessageType) (res chat1.MessageSummary, err error) {
// nil means all
if typs == nil {
for typ := range chat1.MessageTypeRevMap {
typs = append(typs, typ)
}
}
for _, typ := range typs {
msg, err := conv.GetMaxMessage(typ)
if err == nil && msg.Ctime.After(res.Ctime) {
res = msg
}
}
if res.GetMessageID() == 0 {
return res, errors.New("no message summary found")
}
return res, nil
}
// PickLatestMessageUnboxed gets the latest message with one `typs`.
// This method can return deleted messages which have a blank body.
func PickLatestMessageUnboxed(conv chat1.ConversationLocal, typs []chat1.MessageType) (res chat1.MessageUnboxed, err error) {
var msgs []chat1.MessageUnboxed
for _, typ := range typs {
msg, err := conv.GetMaxMessage(typ)
if err == nil && msg.IsValid() {
msgs = append(msgs, msg)
}
}
if len(msgs) == 0 {
return res, errors.New("no message found")
}
sort.Sort(ByMsgUnboxedCtime(msgs))
return msgs[len(msgs)-1], nil
}
func GetConvMtimeLocal(conv chat1.ConversationLocal) gregor1.Time {
msg, err := PickLatestMessageUnboxed(conv, chat1.VisibleChatMessageTypes())
if err != nil {
return conv.ReaderInfo.Mtime
}
return msg.Valid().ServerHeader.Ctime
}
func GetConvSnippet(conv chat1.ConversationLocal, currentUsername string) (snippet, decoration string) {
msg, err := PickLatestMessageUnboxed(conv, chat1.VisibleChatMessageTypes())
if err != nil {
return "", ""
}
return GetMsgSnippet(msg, conv, currentUsername)
}
func GetMsgSummaryByType(msgs []chat1.MessageSummary, typ chat1.MessageType) (chat1.MessageSummary, error) {
for _, msg := range msgs {
if msg.GetMessageType() == typ {
return msg, nil
}
}
return chat1.MessageSummary{}, errors.New("not found")
}
func systemMessageSnippet(msg chat1.MessageSystem) string {
typ, err := msg.SystemType()
if err != nil {
return ""
}
switch typ {
case chat1.MessageSystemType_ADDEDTOTEAM:
return fmt.Sprintf("%s added to team", msg.Addedtoteam().Addee)
case chat1.MessageSystemType_COMPLEXTEAM:
return fmt.Sprintf("%s converted to big team", msg.Complexteam().Team)
case chat1.MessageSystemType_INVITEADDEDTOTEAM:
return fmt.Sprintf("%s added to team", msg.Inviteaddedtoteam().Invitee)
case chat1.MessageSystemType_GITPUSH:
return fmt.Sprintf("%s pushed to %s", msg.Gitpush().Pusher, msg.Gitpush().RepoName)
case chat1.MessageSystemType_CHANGEAVATAR:
return fmt.Sprintf("%s changed team avatar", msg.Changeavatar().User)
default:
return ""
}
}
// Sender prefix for msg snippets. Will show if a conversation has > 2 members
// or is of type TEAM
func getSenderPrefix(mvalid chat1.MessageUnboxedValid, conv chat1.ConversationLocal, currentUsername string) (senderPrefix string) {
var showPrefix bool
switch conv.GetMembersType() {
case chat1.ConversationMembersType_TEAM:
showPrefix = true
default:
showPrefix = len(conv.Names()) > 2
}
if showPrefix {
sender := mvalid.SenderUsername
if sender == currentUsername {
senderPrefix = "You: "
} else {
senderPrefix = fmt.Sprintf("%s: ", sender)
}
}
return senderPrefix
}
func GetMsgSnippet(msg chat1.MessageUnboxed, conv chat1.ConversationLocal, currentUsername string) (snippet, decoration string) {
if !msg.IsValid() {
return "", ""
}
mvalid := msg.Valid()
senderPrefix := getSenderPrefix(mvalid, conv, currentUsername)
if !msg.IsValidFull() {
if mvalid.IsEphemeral() && mvalid.IsEphemeralExpired(time.Now()) {
return fmt.Sprintf("%s ----------------------------", senderPrefix), "π₯"
}
return "", ""
}
if mvalid.IsEphemeral() {
decoration = "π£"
}
switch msg.GetMessageType() {
case chat1.MessageType_TEXT:
return senderPrefix + msg.Valid().MessageBody.Text().Body, decoration
case chat1.MessageType_ATTACHMENT:
obj := msg.Valid().MessageBody.Attachment().Object
title := obj.Title
if len(title) == 0 {
atyp, err := obj.Metadata.AssetType()
if err != nil {
return senderPrefix + "???", decoration
}
switch atyp {
case chat1.AssetMetadataType_IMAGE:
title = "π· attachment"
case chat1.AssetMetadataType_VIDEO:
title = "π attachment"
default:
title = obj.Filename
}
}
return senderPrefix + title, decoration
case chat1.MessageType_SYSTEM:
return systemMessageSnippet(msg.Valid().MessageBody.System()), decoration
case chat1.MessageType_REQUESTPAYMENT:
return "π payment request", ""
case chat1.MessageType_SENDPAYMENT:
return "π payment sent", ""
}
return "", ""
}
// We don't want to display the contents of an exploding message in notifications
func GetDesktopNotificationSnippet(conv *chat1.ConversationLocal, currentUsername string) string {
if conv == nil {
return ""
}
msg, err := PickLatestMessageUnboxed(*conv, chat1.VisibleChatMessageTypes())
if err != nil || !msg.IsValid() {
return ""
}
mvalid := msg.Valid()
if !mvalid.IsEphemeral() {
snippet, _ := GetMsgSnippet(msg, *conv, currentUsername)
return snippet
}
// If the message is already exploded, nothing to see here.
if !msg.IsValidFull() {
return ""
}
switch msg.GetMessageType() {
case chat1.MessageType_TEXT, chat1.MessageType_ATTACHMENT:
return "π£ exploding message."
default:
return ""
}
}
func PresentRemoteConversation(rc types.RemoteConversation) (res chat1.UnverifiedInboxUIItem) {
var tlfName string
rawConv := rc.Conv
latest, err := PickLatestMessageSummary(rawConv, nil)
if err != nil {
tlfName = ""
} else {
tlfName = latest.TlfName
}
res.ConvID = rawConv.GetConvID().String()
res.TopicType = rawConv.GetTopicType()
res.Name = tlfName
res.Status = rawConv.Metadata.Status
res.Time = GetConvMtime(rawConv)
res.Visibility = rawConv.Metadata.Visibility
res.Notifications = rawConv.Notifications
res.MembersType = rawConv.GetMembersType()
res.MemberStatus = rawConv.ReaderInfo.Status
res.TeamType = rawConv.Metadata.TeamType
res.Version = rawConv.Metadata.Version
res.ReadMsgID = rawConv.ReaderInfo.ReadMsgid
res.MaxMsgID = rawConv.ReaderInfo.MaxMsgid
res.Supersedes = rawConv.Metadata.Supersedes
res.SupersededBy = rawConv.Metadata.SupersededBy
res.FinalizeInfo = rawConv.Metadata.FinalizeInfo
if rc.LocalMetadata != nil {
res.LocalMetadata = &chat1.UnverifiedInboxUIItemMetadata{
ChannelName: rc.LocalMetadata.TopicName,
Headline: rc.LocalMetadata.Headline,
Snippet: rc.LocalMetadata.Snippet,
SnippetDecoration: rc.LocalMetadata.SnippetDecoration,
WriterNames: rc.LocalMetadata.WriterNames,
ResetParticipants: rc.LocalMetadata.ResetParticipants,
}
res.Name = rc.LocalMetadata.Name
}
return res
}
func PresentRemoteConversations(rcs []types.RemoteConversation) (res []chat1.UnverifiedInboxUIItem) {
for _, rc := range rcs {
res = append(res, PresentRemoteConversation(rc))
}
return res
}
func PresentConversationErrorLocal(rawConv chat1.ConversationErrorLocal) (res chat1.InboxUIItemError) {
res.Message = rawConv.Message
res.RekeyInfo = rawConv.RekeyInfo
res.RemoteConv = PresentRemoteConversation(types.RemoteConversation{
Conv: rawConv.RemoteConv,
})
res.Typ = rawConv.Typ
res.UnverifiedTLFName = rawConv.UnverifiedTLFName
return res
}
func PresentConversationLocal(rawConv chat1.ConversationLocal, currentUsername string) (res chat1.InboxUIItem) {
var writerNames []string
fullNames := make(map[string]string)
for _, p := range rawConv.Info.Participants {
writerNames = append(writerNames, p.Username)
if p.Fullname != nil {
fullNames[p.Username] = *p.Fullname
}
}
res.ConvID = rawConv.GetConvID().String()
res.TopicType = rawConv.GetTopicType()
res.Name = rawConv.Info.TlfName
res.Snippet, res.SnippetDecoration = GetConvSnippet(rawConv, currentUsername)
res.Channel = GetTopicName(rawConv)
res.Headline = GetHeadline(rawConv)
res.Participants = writerNames
res.FullNames = fullNames
res.ResetParticipants = rawConv.Info.ResetNames
res.Status = rawConv.Info.Status
res.MembersType = rawConv.GetMembersType()
res.MemberStatus = rawConv.Info.MemberStatus
res.Visibility = rawConv.Info.Visibility
res.Time = GetConvMtimeLocal(rawConv)
res.FinalizeInfo = rawConv.GetFinalizeInfo()
res.SupersededBy = rawConv.SupersededBy
res.Supersedes = rawConv.Supersedes
res.IsEmpty = rawConv.IsEmpty
res.Notifications = rawConv.Notifications
res.CreatorInfo = rawConv.CreatorInfo
res.TeamType = rawConv.Info.TeamType