-
Notifications
You must be signed in to change notification settings - Fork 249
/
messenger_handler.go
3767 lines (3176 loc) · 120 KB
/
messenger_handler.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 protocol
import (
"context"
"crypto/ecdsa"
"database/sql"
"encoding/hex"
"fmt"
"sync"
"time"
"github.com/status-im/status-go/services/browsers"
"github.com/status-im/status-go/signal"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/google/uuid"
"github.com/status-im/status-go/eth-node/crypto"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/images"
"github.com/status-im/status-go/multiaccounts/accounts"
multiaccountscommon "github.com/status-im/status-go/multiaccounts/common"
"github.com/status-im/status-go/multiaccounts/settings"
walletsettings "github.com/status-im/status-go/multiaccounts/settings_wallet"
"github.com/status-im/status-go/protocol/common"
"github.com/status-im/status-go/protocol/common/shard"
"github.com/status-im/status-go/protocol/communities"
"github.com/status-im/status-go/protocol/encryption/multidevice"
"github.com/status-im/status-go/protocol/identity"
"github.com/status-im/status-go/protocol/protobuf"
"github.com/status-im/status-go/protocol/requests"
"github.com/status-im/status-go/protocol/transport"
v1protocol "github.com/status-im/status-go/protocol/v1"
"github.com/status-im/status-go/protocol/verification"
)
const (
transactionRequestDeclinedMessage = "Transaction request declined"
requestAddressForTransactionAcceptedMessage = "Request address for transaction accepted"
requestAddressForTransactionDeclinedMessage = "Request address for transaction declined"
)
var (
ErrMessageNotAllowed = errors.New("message from a non-contact")
ErrMessageForWrongChatType = errors.New("message for the wrong chat type")
ErrNotWatchOnlyAccount = errors.New("an account is not a watch only account")
ErrWalletAccountNotSupportedForMobileApp = errors.New("handling account is not supported for mobile app")
ErrTryingToApplyOldWalletAccountsOrder = errors.New("trying to apply old wallet accounts order")
ErrTryingToStoreOldWalletAccount = errors.New("trying to store an old wallet account")
ErrTryingToStoreOldKeypair = errors.New("trying to store an old keypair")
ErrSomeFieldsMissingForWalletAccount = errors.New("some fields are missing for wallet account")
ErrUnknownKeypairForWalletAccount = errors.New("keypair is not known for the wallet account")
ErrInvalidCommunityID = errors.New("invalid community id")
ErrTryingToApplyOldTokenPreferences = errors.New("trying to apply old token preferences")
)
// HandleMembershipUpdate updates a Chat instance according to the membership updates.
// It retrieves chat, if exists, and merges membership updates from the message.
// Finally, the Chat is updated with the new group events.
func (m *Messenger) HandleMembershipUpdateMessage(messageState *ReceivedMessageState, rawMembershipUpdate *protobuf.MembershipUpdateMessage, statusMessage *v1protocol.StatusMessage) error {
chat, _ := messageState.AllChats.Load(rawMembershipUpdate.ChatId)
return m.HandleMembershipUpdate(messageState, chat, rawMembershipUpdate, m.systemMessagesTranslations)
}
func (m *Messenger) HandleMembershipUpdate(messageState *ReceivedMessageState, chat *Chat, rawMembershipUpdate *protobuf.MembershipUpdateMessage, translations *systemMessageTranslationsMap) error {
var group *v1protocol.Group
var err error
if rawMembershipUpdate == nil {
return nil
}
logger := m.logger.With(zap.String("site", "HandleMembershipUpdate"))
message, err := v1protocol.MembershipUpdateMessageFromProtobuf(rawMembershipUpdate)
if err != nil {
return err
}
if err := ValidateMembershipUpdateMessage(message, messageState.Timesource.GetCurrentTime()); err != nil {
logger.Warn("failed to validate message", zap.Error(err))
return err
}
senderID := messageState.CurrentMessageState.Contact.ID
allowed, err := m.isMessageAllowedFrom(senderID, chat)
if err != nil {
return err
}
if !allowed {
return ErrMessageNotAllowed
}
//if chat.InvitationAdmin exists means we are waiting for invitation request approvement, and in that case
//we need to create a new chat instance like we don't have a chat and just use a regular invitation flow
waitingForApproval := chat != nil && len(chat.InvitationAdmin) > 0
ourKey := contactIDFromPublicKey(&m.identity.PublicKey)
isActive := messageState.CurrentMessageState.Contact.added() || messageState.CurrentMessageState.Contact.ID == ourKey || waitingForApproval
showPushNotification := isActive && messageState.CurrentMessageState.Contact.ID != ourKey
// wasUserAdded indicates whether the user has been added to the group with this update
wasUserAdded := false
if chat == nil || waitingForApproval {
if len(message.Events) == 0 {
return errors.New("can't create new group chat without events")
}
//approve invitations
if waitingForApproval {
groupChatInvitation := &GroupChatInvitation{
GroupChatInvitation: &protobuf.GroupChatInvitation{
ChatId: message.ChatID,
},
From: types.EncodeHex(crypto.FromECDSAPub(&m.identity.PublicKey)),
}
groupChatInvitation, err = m.persistence.InvitationByID(groupChatInvitation.ID())
if err != nil && err != common.ErrRecordNotFound {
return err
}
if groupChatInvitation != nil {
groupChatInvitation.State = protobuf.GroupChatInvitation_APPROVED
err := m.persistence.SaveInvitation(groupChatInvitation)
if err != nil {
return err
}
messageState.GroupChatInvitations[groupChatInvitation.ID()] = groupChatInvitation
}
}
group, err = v1protocol.NewGroupWithEvents(message.ChatID, message.Events)
if err != nil {
return err
}
// A new chat must have contained us at some point
wasEverMember, err := group.WasEverMember(ourKey)
if err != nil {
return err
}
if !wasEverMember {
return errors.New("can't create a new group chat without us being a member")
}
wasUserAdded = group.IsMember(ourKey)
newChat := CreateGroupChat(messageState.Timesource)
// We set group chat inactive and create a notification instead
// unless is coming from us or a contact or were waiting for approval.
// Also, as message MEMBER_JOINED may come from member(not creator, not our contact)
// reach earlier than CHAT_CREATED from creator, we need check if creator is our contact
newChat.Active = isActive || m.checkIfCreatorIsOurContact(group)
newChat.ReceivedInvitationAdmin = senderID
chat = &newChat
chat.updateChatFromGroupMembershipChanges(group)
if err != nil {
return errors.Wrap(err, "failed to get group creator")
}
publicKeys, err := group.MemberPublicKeys()
if err != nil {
return errors.Wrap(err, "failed to get group members")
}
filters, err := m.transport.JoinGroup(publicKeys)
if err != nil {
return errors.Wrap(err, "failed to join group")
}
ok, err := m.scheduleSyncFilters(filters)
if err != nil {
return errors.Wrap(err, "failed to schedule sync filter")
}
m.logger.Debug("result of schedule sync filter", zap.Bool("ok", ok))
} else {
existingGroup, err := newProtocolGroupFromChat(chat)
if err != nil {
return errors.Wrap(err, "failed to create a Group from Chat")
}
updateGroup, err := v1protocol.NewGroupWithEvents(message.ChatID, message.Events)
if err != nil {
return errors.Wrap(err, "invalid membership update")
}
merged := v1protocol.MergeMembershipUpdateEvents(existingGroup.Events(), updateGroup.Events())
group, err = v1protocol.NewGroupWithEvents(chat.ID, merged)
if err != nil {
return errors.Wrap(err, "failed to create a group with new membership updates")
}
chat.updateChatFromGroupMembershipChanges(group)
// Reactivate deleted group chat on re-invite from contact
chat.Active = chat.Active || (isActive && group.IsMember(ourKey))
wasUserAdded = !existingGroup.IsMember(ourKey) && group.IsMember(ourKey)
// Show push notifications when our key is added to members list and chat is Active
showPushNotification = showPushNotification && wasUserAdded
}
maxClockVal := uint64(0)
for _, event := range group.Events() {
if event.ClockValue > maxClockVal {
maxClockVal = event.ClockValue
}
}
if chat.LastClockValue < maxClockVal {
chat.LastClockValue = maxClockVal
}
// Only create a message notification when the user is added, not when removed
if !chat.Active && wasUserAdded {
chat.Highlight = true
m.createMessageNotification(chat, messageState, chat.LastMessage)
}
profilePicturesVisibility, err := m.settings.GetProfilePicturesVisibility()
if err != nil {
return errors.Wrap(err, "failed to get profilePicturesVisibility setting")
}
if showPushNotification {
// chat is highlighted for new group invites or group re-invites
chat.Highlight = true
messageState.Response.AddNotification(NewPrivateGroupInviteNotification(chat.ID, chat, messageState.CurrentMessageState.Contact, profilePicturesVisibility))
}
systemMessages := buildSystemMessages(message.Events, translations)
for _, message := range systemMessages {
messageID := message.ID
exists, err := m.messageExists(messageID, messageState.ExistingMessagesMap)
if err != nil {
m.logger.Warn("failed to check message exists", zap.Error(err))
}
if exists {
continue
}
messageState.Response.AddMessage(message)
}
messageState.Response.AddChat(chat)
// Store in chats map as it might be a new one
messageState.AllChats.Store(chat.ID, chat)
// explicit join has been removed, mimic auto-join for backward compatibility
// no all cases are covered, e.g. if added to a group by non-contact
autoJoin := chat.Active && wasUserAdded
if autoJoin || waitingForApproval {
_, err = m.ConfirmJoiningGroup(context.Background(), chat.ID)
if err != nil {
return err
}
}
if message.Message != nil {
return m.HandleChatMessage(messageState, message.Message, nil, false)
} else if message.EmojiReaction != nil {
return m.HandleEmojiReaction(messageState, message.EmojiReaction, nil)
}
return nil
}
func (m *Messenger) checkIfCreatorIsOurContact(group *v1protocol.Group) bool {
creator, err := group.Creator()
if err == nil {
contact, _ := m.allContacts.Load(creator)
return contact != nil && contact.mutual()
}
m.logger.Warn("failed to get creator from group", zap.String("group name", group.Name()), zap.String("group chat id", group.ChatID()), zap.Error(err))
return false
}
func (m *Messenger) createMessageNotification(chat *Chat, messageState *ReceivedMessageState, message *common.Message) {
var notificationType ActivityCenterType
if chat.OneToOne() {
notificationType = ActivityCenterNotificationTypeNewOneToOne
} else {
notificationType = ActivityCenterNotificationTypeNewPrivateGroupChat
}
notification := &ActivityCenterNotification{
ID: types.FromHex(chat.ID),
Name: chat.Name,
LastMessage: message,
Type: notificationType,
Author: messageState.CurrentMessageState.Contact.ID,
Timestamp: messageState.CurrentMessageState.WhisperTimestamp,
ChatID: chat.ID,
CommunityID: chat.CommunityID,
UpdatedAt: m.GetCurrentTimeInMillis(),
}
err := m.addActivityCenterNotification(messageState.Response, notification, nil)
if err != nil {
m.logger.Warn("failed to create activity center notification", zap.Error(err))
}
}
func (m *Messenger) PendingNotificationContactRequest(contactID string) (*ActivityCenterNotification, error) {
return m.persistence.ActiveContactRequestNotification(contactID)
}
func (m *Messenger) createContactRequestForContactUpdate(contact *Contact, messageState *ReceivedMessageState) (*common.Message, error) {
contactRequest, err := m.generateContactRequest(
contact.ContactRequestRemoteClock,
messageState.CurrentMessageState.WhisperTimestamp,
contact,
defaultContactRequestText(),
false,
)
if err != nil {
return nil, err
}
contactRequest.ID = defaultContactRequestID(contact.ID)
// save this message
messageState.Response.AddMessage(contactRequest)
err = m.persistence.SaveMessages([]*common.Message{contactRequest})
if err != nil {
return nil, err
}
return contactRequest, nil
}
func (m *Messenger) createIncomingContactRequestNotification(contact *Contact, messageState *ReceivedMessageState, contactRequest *common.Message, createNewNotification bool) error {
if contactRequest.ContactRequestState == common.ContactRequestStateAccepted {
// Pull one from the db if there
notification, err := m.persistence.GetActivityCenterNotificationByID(types.FromHex(contactRequest.ID))
if err != nil {
return err
}
if notification != nil {
notification.Name = contact.PrimaryName()
notification.Message = contactRequest
notification.Read = true
notification.Accepted = true
notification.Dismissed = false
notification.UpdatedAt = m.GetCurrentTimeInMillis()
_, err = m.persistence.SaveActivityCenterNotification(notification, true)
if err != nil {
return err
}
messageState.Response.AddMessage(contactRequest)
messageState.Response.AddActivityCenterNotification(notification)
}
return nil
}
if !createNewNotification {
return nil
}
notification := &ActivityCenterNotification{
ID: types.FromHex(contactRequest.ID),
Name: contact.PrimaryName(),
Message: contactRequest,
Type: ActivityCenterNotificationTypeContactRequest,
Author: contactRequest.From,
Timestamp: contactRequest.WhisperTimestamp,
ChatID: contact.ID,
Read: contactRequest.ContactRequestState == common.ContactRequestStateAccepted || contactRequest.ContactRequestState == common.ContactRequestStateDismissed,
Accepted: contactRequest.ContactRequestState == common.ContactRequestStateAccepted,
Dismissed: contactRequest.ContactRequestState == common.ContactRequestStateDismissed,
UpdatedAt: m.GetCurrentTimeInMillis(),
}
return m.addActivityCenterNotification(messageState.Response, notification, nil)
}
func (m *Messenger) handleCommandMessage(state *ReceivedMessageState, message *common.Message) error {
message.ID = state.CurrentMessageState.MessageID
message.From = state.CurrentMessageState.Contact.ID
message.Alias = state.CurrentMessageState.Contact.Alias
message.SigPubKey = state.CurrentMessageState.PublicKey
message.Identicon = state.CurrentMessageState.Contact.Identicon
message.WhisperTimestamp = state.CurrentMessageState.WhisperTimestamp
if err := message.PrepareContent(common.PubkeyToHex(&m.identity.PublicKey)); err != nil {
return fmt.Errorf("failed to prepare content: %v", err)
}
chat, err := m.matchChatEntity(message)
if err != nil {
return err
}
allowed, err := m.isMessageAllowedFrom(state.CurrentMessageState.Contact.ID, chat)
if err != nil {
return err
}
if !allowed {
return ErrMessageNotAllowed
}
// If deleted-at is greater, ignore message
if chat.DeletedAtClockValue >= message.Clock {
return nil
}
// Set the LocalChatID for the message
message.LocalChatID = chat.ID
if c, ok := state.AllChats.Load(chat.ID); ok {
chat = c
}
// Set the LocalChatID for the message
message.LocalChatID = chat.ID
// Increase unviewed count
if !common.IsPubKeyEqual(message.SigPubKey, &m.identity.PublicKey) {
m.updateUnviewedCounts(chat, message)
message.OutgoingStatus = ""
} else {
// Our own message, mark as sent
message.OutgoingStatus = common.OutgoingStatusSent
}
err = chat.UpdateFromMessage(message, state.Timesource)
if err != nil {
return err
}
if !chat.Active {
m.createMessageNotification(chat, state, chat.LastMessage)
}
// Add to response
state.Response.AddChat(chat)
if message != nil {
message.New = true
state.Response.AddMessage(message)
}
// Set in the modified maps chat
state.AllChats.Store(chat.ID, chat)
return nil
}
func (m *Messenger) syncContactRequestForInstallationContact(contact *Contact, state *ReceivedMessageState, chat *Chat, outgoing bool) error {
if chat == nil {
return fmt.Errorf("no chat restored during the contact synchronisation, contact.ID = %s", contact.ID)
}
contactRequestID, err := m.persistence.LatestPendingContactRequestIDForContact(contact.ID)
if err != nil {
return err
}
if contactRequestID != "" {
m.logger.Warn("syncContactRequestForInstallationContact: skipping as contact request found", zap.String("contactRequestID", contactRequestID))
return nil
}
clock, timestamp := chat.NextClockAndTimestamp(m.transport)
contactRequest, err := m.generateContactRequest(clock, timestamp, contact, defaultContactRequestText(), outgoing)
if err != nil {
return err
}
contactRequest.ID = defaultContactRequestID(contact.ID)
state.Response.AddMessage(contactRequest)
err = m.persistence.SaveMessages([]*common.Message{contactRequest})
if err != nil {
return err
}
if outgoing {
notification := m.generateOutgoingContactRequestNotification(contact, contactRequest)
err = m.addActivityCenterNotification(state.Response, notification, nil)
if err != nil {
return err
}
} else {
err = m.createIncomingContactRequestNotification(contact, state, contactRequest, true)
if err != nil {
return err
}
}
return nil
}
func (m *Messenger) HandleSyncInstallationAccount(state *ReceivedMessageState, message *protobuf.SyncInstallationAccount, statusMessage *v1protocol.StatusMessage) error {
// Noop
return nil
}
func (m *Messenger) handleSyncChats(messageState *ReceivedMessageState, chats []*protobuf.SyncChat) error {
for _, syncChat := range chats {
oldChat, ok := m.allChats.Load(syncChat.Id)
clock := int64(syncChat.Clock)
if ok && oldChat.Timestamp > clock {
// We already know this chat and its timestamp is newer than the syncChat
continue
}
chat := &Chat{
ID: syncChat.Id,
Name: syncChat.Name,
Timestamp: clock,
ReadMessagesAtClockValue: 0,
Active: syncChat.Active,
Muted: syncChat.Muted,
Joined: clock,
ChatType: ChatType(syncChat.ChatType),
Highlight: false,
}
if chat.PrivateGroupChat() {
chat.MembershipUpdates = make([]v1protocol.MembershipUpdateEvent, len(syncChat.MembershipUpdateEvents))
for i, membershipUpdate := range syncChat.MembershipUpdateEvents {
chat.MembershipUpdates[i] = v1protocol.MembershipUpdateEvent{
ClockValue: membershipUpdate.Clock,
Type: protobuf.MembershipUpdateEvent_EventType(membershipUpdate.Type),
Members: membershipUpdate.Members,
Name: membershipUpdate.Name,
Signature: membershipUpdate.Signature,
ChatID: membershipUpdate.ChatId,
From: membershipUpdate.From,
RawPayload: membershipUpdate.RawPayload,
Color: membershipUpdate.Color,
Image: membershipUpdate.Image,
}
}
group, err := newProtocolGroupFromChat(chat)
if err != nil {
return err
}
chat.updateChatFromGroupMembershipChanges(group)
}
err := m.saveChat(chat)
if err != nil {
return err
}
messageState.Response.AddChat(chat)
}
return nil
}
func (m *Messenger) HandleSyncInstallationContactV2(state *ReceivedMessageState, message *protobuf.SyncInstallationContactV2, statusMessage *v1protocol.StatusMessage) error {
// Ignore own contact installation
if message.Id == m.myHexIdentity() {
m.logger.Warn("HandleSyncInstallationContactV2: skipping own contact")
return nil
}
removed := message.Removed && !message.Blocked
chat, ok := state.AllChats.Load(message.Id)
if !ok && (message.Added || message.HasAddedUs || message.Muted) && !removed {
pubKey, err := common.HexToPubkey(message.Id)
if err != nil {
return err
}
chat = OneToOneFromPublicKey(pubKey, state.Timesource)
// We don't want to show the chat to the user
chat.Active = false
}
contact, contactFound := state.AllContacts.Load(message.Id)
if !contactFound {
if message.Removed && !message.Blocked {
// Nothing to do in case if contact doesn't exist
return nil
}
var err error
contact, err = buildContactFromPkString(message.Id)
if err != nil {
return err
}
}
if message.ContactRequestRemoteClock != 0 || message.ContactRequestLocalClock != 0 {
// Some local action about contact requests were performed,
// process them
contact.ProcessSyncContactRequestState(
ContactRequestState(message.ContactRequestRemoteState),
uint64(message.ContactRequestRemoteClock),
ContactRequestState(message.ContactRequestLocalState),
uint64(message.ContactRequestLocalClock))
state.ModifiedContacts.Store(contact.ID, true)
state.AllContacts.Store(contact.ID, contact)
err := m.syncContactRequestForInstallationContact(contact, state, chat, contact.ContactRequestLocalState == ContactRequestStateSent)
if err != nil {
return err
}
} else if message.Added || message.HasAddedUs {
// NOTE(cammellos): this is for handling backward compatibility, old clients
// won't propagate ContactRequestRemoteClock or ContactRequestLocalClock
if message.Added && contact.LastUpdatedLocally < message.LastUpdatedLocally {
contact.ContactRequestSent(message.LastUpdatedLocally)
err := m.syncContactRequestForInstallationContact(contact, state, chat, true)
if err != nil {
return err
}
}
if message.HasAddedUs && contact.LastUpdated < message.LastUpdated {
contact.ContactRequestReceived(message.LastUpdated)
err := m.syncContactRequestForInstallationContact(contact, state, chat, false)
if err != nil {
return err
}
}
if message.Removed && contact.LastUpdatedLocally < message.LastUpdatedLocally {
err := m.removeContact(context.Background(), state.Response, contact.ID, false)
if err != nil {
return err
}
}
}
// Sync last updated field
// We don't set `LastUpdated`, since that would cause some issues
// as `LastUpdated` tracks both display name & picture.
// The case where it would break is as follow:
// 1) User A pairs A1 with device A2.
// 2) User B publishes display name and picture with LastUpdated = 3.
// 3) Device A1 receives message from step 2.
// 4) Device A1 syncs with A2 (which has not received message from step 3).
// 5) Device A2 saves Display name and sets LastUpdated = 3,
// note that picture has not been set as it's not synced.
// 6) Device A2 receives the message from 2. because LastUpdated is 3
// it will be discarded, A2 will not have B's picture.
// The correct solution is to either sync profile image (expensive)
// or split the clock for image/display name, so they can be synced
// independently.
if !contactFound || (contact.LastUpdated < message.LastUpdated) {
if message.DisplayName != "" {
contact.DisplayName = message.DisplayName
}
state.ModifiedContacts.Store(contact.ID, true)
state.AllContacts.Store(contact.ID, contact)
}
if contact.LastUpdatedLocally < message.LastUpdatedLocally {
// NOTE(cammellos): probably is cleaner to pass a flag
// to method to tell them not to sync, or factor out in different
// methods
contact.IsSyncing = true
defer func() {
contact.IsSyncing = false
}()
if message.EnsName != "" && contact.EnsName != message.EnsName {
contact.EnsName = message.EnsName
publicKey, err := contact.PublicKey()
if err != nil {
return err
}
err = m.ENSVerified(common.PubkeyToHex(publicKey), message.EnsName)
if err != nil {
contact.ENSVerified = false
}
contact.ENSVerified = true
}
contact.LastUpdatedLocally = message.LastUpdatedLocally
contact.LocalNickname = message.LocalNickname
contact.TrustStatus = verification.TrustStatus(message.TrustStatus)
contact.VerificationStatus = VerificationStatus(message.VerificationStatus)
_, err := m.verificationDatabase.UpsertTrustStatus(contact.ID, contact.TrustStatus, message.LastUpdatedLocally)
if err != nil {
return err
}
if message.Blocked != contact.Blocked {
if message.Blocked {
state.AllContacts.Store(contact.ID, contact)
response, err := m.BlockContact(context.TODO(), contact.ID, true)
if err != nil {
return err
}
err = state.Response.Merge(response)
if err != nil {
return err
}
} else {
contact.Unblock(message.LastUpdatedLocally)
}
}
if chat != nil && message.Muted != chat.Muted {
if message.Muted {
_, err := m.muteChat(chat, contact, time.Time{})
if err != nil {
return err
}
} else {
err := m.unmuteChat(chat, contact)
if err != nil {
return err
}
}
state.Response.AddChat(chat)
}
state.ModifiedContacts.Store(contact.ID, true)
state.AllContacts.Store(contact.ID, contact)
}
if chat != nil {
state.AllChats.Store(chat.ID, chat)
}
return nil
}
func (m *Messenger) HandleSyncProfilePictures(state *ReceivedMessageState, message *protobuf.SyncProfilePictures, statusMessage *v1protocol.StatusMessage) error {
dbImages, err := m.multiAccounts.GetIdentityImages(message.KeyUid)
if err != nil {
return err
}
dbImageMap := make(map[string]*images.IdentityImage)
for _, img := range dbImages {
dbImageMap[img.Name] = img
}
idImages := make([]images.IdentityImage, len(message.Pictures))
i := 0
for _, message := range message.Pictures {
dbImg := dbImageMap[message.Name]
if dbImg != nil && message.Clock <= dbImg.Clock {
continue
}
image := images.IdentityImage{
Name: message.Name,
Payload: message.Payload,
Width: int(message.Width),
Height: int(message.Height),
FileSize: int(message.FileSize),
ResizeTarget: int(message.ResizeTarget),
Clock: message.Clock,
}
idImages[i] = image
i++
}
if i == 0 {
return nil
}
err = m.multiAccounts.StoreIdentityImages(message.KeyUid, idImages[:i], false)
if err == nil {
state.Response.IdentityImages = idImages[:i]
}
return err
}
func (m *Messenger) HandleSyncChat(state *ReceivedMessageState, message *protobuf.SyncChat, statusMessage *v1protocol.StatusMessage) error {
chatID := message.Id
existingChat, ok := state.AllChats.Load(chatID)
if ok && (existingChat.Active || uint32(message.GetClock()/1000) < existingChat.SyncedTo) {
return nil
}
chat := existingChat
if !ok {
chats := make([]*protobuf.SyncChat, 1)
chats[0] = message
return m.handleSyncChats(state, chats)
}
existingChat.Joined = int64(message.Clock)
state.AllChats.Store(chat.ID, chat)
state.Response.AddChat(chat)
return nil
}
func (m *Messenger) HandleSyncChatRemoved(state *ReceivedMessageState, message *protobuf.SyncChatRemoved, statusMessage *v1protocol.StatusMessage) error {
chat, ok := m.allChats.Load(message.Id)
if !ok {
return ErrChatNotFound
}
if chat.Joined > int64(message.Clock) {
return nil
}
if chat.DeletedAtClockValue > message.Clock {
return nil
}
if chat.PrivateGroupChat() {
_, err := m.leaveGroupChat(context.Background(), state.Response, message.Id, true, false)
if err != nil {
return err
}
}
response, err := m.deactivateChat(message.Id, message.Clock, false, true)
if err != nil {
return err
}
return state.Response.Merge(response)
}
func (m *Messenger) HandleSyncChatMessagesRead(state *ReceivedMessageState, message *protobuf.SyncChatMessagesRead, statusMessage *v1protocol.StatusMessage) error {
chat, ok := m.allChats.Load(message.Id)
if !ok {
return ErrChatNotFound
}
if chat.ReadMessagesAtClockValue > message.Clock {
return nil
}
err := m.markAllRead(message.Id, message.Clock, false)
if err != nil {
return err
}
state.Response.AddChat(chat)
return nil
}
func (m *Messenger) handlePinMessage(pinner *Contact, whisperTimestamp uint64, response *MessengerResponse, message *protobuf.PinMessage, forceSeen bool) error {
logger := m.logger.With(zap.String("site", "HandlePinMessage"))
logger.Info("Handling pin message")
publicKey, err := pinner.PublicKey()
if err != nil {
return err
}
pinMessage := &common.PinMessage{
PinMessage: message,
// MessageID: message.MessageId,
WhisperTimestamp: whisperTimestamp,
From: pinner.ID,
SigPubKey: publicKey,
Identicon: pinner.Identicon,
Alias: pinner.Alias,
}
chat, err := m.matchChatEntity(pinMessage)
if err != nil {
return err // matchChatEntity returns a descriptive error message
}
pinMessage.ID, err = generatePinMessageID(&m.identity.PublicKey, pinMessage, chat)
if err != nil {
return err
}
// If deleted-at is greater, ignore message
if chat.DeletedAtClockValue >= pinMessage.Clock {
return nil
}
if c, ok := m.allChats.Load(chat.ID); ok {
chat = c
}
// Set the LocalChatID for the message
pinMessage.LocalChatID = chat.ID
inserted, err := m.persistence.SavePinMessage(pinMessage)
if err != nil {
return err
}
// Nothing to do, returning
if !inserted {
m.logger.Info("pin message already processed")
return nil
}
if message.Pinned {
id, err := generatePinMessageNotificationID(&m.identity.PublicKey, pinMessage, chat)
if err != nil {
return err
}
systemMessage := &common.Message{
ChatMessage: &protobuf.ChatMessage{
Clock: message.Clock,
Timestamp: whisperTimestamp,
ChatId: chat.ID,
MessageType: message.MessageType,
ResponseTo: message.MessageId,
ContentType: protobuf.ChatMessage_SYSTEM_MESSAGE_PINNED_MESSAGE,
},
WhisperTimestamp: whisperTimestamp,
ID: id,
LocalChatID: chat.ID,
From: pinner.ID,
}
if forceSeen {
systemMessage.Seen = true
}
response.AddMessage(systemMessage)
chat.UnviewedMessagesCount++
}
if chat.LastClockValue < message.Clock {
chat.LastClockValue = message.Clock
}
response.AddPinMessage(pinMessage)
// Set in the modified maps chat
response.AddChat(chat)
m.allChats.Store(chat.ID, chat)
return nil
}
func (m *Messenger) HandlePinMessage(state *ReceivedMessageState, message *protobuf.PinMessage, statusMessage *v1protocol.StatusMessage, fromArchive bool) error {
return m.handlePinMessage(state.CurrentMessageState.Contact, state.CurrentMessageState.WhisperTimestamp, state.Response, message, fromArchive)
}
func (m *Messenger) handleAcceptContactRequest(
response *MessengerResponse,
contact *Contact,
originalRequest *common.Message,
clock uint64) (ContactRequestProcessingResponse, error) {
m.logger.Debug("received contact request", zap.Uint64("clock-sent", clock), zap.Uint64("current-clock", contact.ContactRequestRemoteClock), zap.Uint64("current-state", uint64(contact.ContactRequestRemoteState)))
if contact.ContactRequestRemoteClock > clock {
m.logger.Debug("not handling accept since clock lower")
return ContactRequestProcessingResponse{}, nil
}
// The contact request accepted wasn't found, a reason for this might
// be that we sent a legacy contact request/contact-update, or another
// device has sent it, and we haven't synchronized it
if originalRequest == nil {
return contact.ContactRequestAccepted(clock), nil
}
if originalRequest.LocalChatID != contact.ID {
return ContactRequestProcessingResponse{}, errors.New("can't accept contact request not sent to user")
}
contact.ContactRequestAccepted(clock)
originalRequest.ContactRequestState = common.ContactRequestStateAccepted
err := m.persistence.SetContactRequestState(originalRequest.ID, originalRequest.ContactRequestState)
if err != nil {
return ContactRequestProcessingResponse{}, err
}
response.AddMessage(originalRequest)
return ContactRequestProcessingResponse{}, nil
}
func (m *Messenger) handleAcceptContactRequestMessage(state *ReceivedMessageState, clock uint64, contactRequestID string, isOutgoing bool) error {
request, err := m.persistence.MessageByID(contactRequestID)
if err != nil && err != common.ErrRecordNotFound {
return err
}
contact := state.CurrentMessageState.Contact
processingResponse, err := m.handleAcceptContactRequest(state.Response, contact, request, clock)
if err != nil {
return err
}
// If the state has changed from non-mutual contact, to mutual contact
// we want to notify the user
if contact.mutual() {
// We set the chat as active, this is currently the expected behavior
// for mobile, it might change as we implement further the activity
// center
chat, _, err := m.getOneToOneAndNextClock(contact)
if err != nil {
return err
}