-
Notifications
You must be signed in to change notification settings - Fork 11
/
ConversationEventPayloadProcessor.swift
1036 lines (890 loc) · 37 KB
/
ConversationEventPayloadProcessor.swift
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
//
// Wire
// Copyright (C) 2024 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
enum ConversationEventPayloadProcessorError: Error {
case noBackendConversationId
}
struct ConversationEventPayloadProcessor {
enum Source {
case slowSync
case eventStream
}
// MARK: - Properties
private let mlsEventProcessor: MLSEventProcessing
private let removeLocalConversation: RemoveLocalConversationUseCaseProtocol
// MARK: - Life cycle
init(
mlsEventProcessor: MLSEventProcessing,
removeLocalConversation: RemoveLocalConversationUseCaseProtocol
) {
self.mlsEventProcessor = mlsEventProcessor
self.removeLocalConversation = removeLocalConversation
}
// MARK: - Conversation creation
func updateOrCreateConversations(
from payload: Payload.ConversationList,
in context: NSManagedObjectContext
) async {
for payload in payload.conversations {
await updateOrCreateConversation(
from: payload,
source: .slowSync,
in: context
)
}
}
func updateOrCreateConverations(
from payload: Payload.QualifiedConversationList,
in context: NSManagedObjectContext
) async {
for payload in payload.found {
await updateOrCreateConversation(
from: payload,
source: .slowSync,
in: context
)
}
}
func processPayload(
_ payload: Payload.ConversationEvent<Payload.Conversation>,
in context: NSManagedObjectContext
) async {
guard let timestamp = payload.timestamp else {
Logging.eventProcessing.error("Conversation creation missing timestamp in event, aborting...")
return
}
guard let conversationID = payload.id ?? payload.qualifiedID?.uuid else {
Flow.createGroup.fail(ConversationEventPayloadProcessorError.noBackendConversationId)
Logging.eventProcessing.error("Conversation creation missing conversationID in event, aborting...")
return
}
guard await context.perform({
ZMConversation.fetch(with: conversationID, domain: payload.qualifiedID?.domain, in: context) == nil
}) else {
Logging.eventProcessing.warn("Conversation already exists, aborting...")
return
}
await updateOrCreateConversation(
from: payload.data,
serverTimestamp: timestamp,
source: .eventStream,
in: context
)
}
// MARK: - Conversation deletion
func processPayload(
_ payload: Payload.ConversationEvent<Payload.UpdateConversationDeleted>,
in context: NSManagedObjectContext
) async {
let conversation = await context.perform {
self.fetchOrCreateConversation(
from: payload,
in: context
)
}
guard let conversation else {
Logging.eventProcessing.error("Conversation deletion missing conversation in event, aborting...")
return
}
do {
try await removeLocalConversation.invoke(
with: conversation,
syncContext: context
)
} catch {
WireLogger.mls.error("removeLocalConversation threw error: \(String(reflecting: error))")
}
}
// MARK: - Member leave
func processPayload(
_ payload: Payload.ConversationEvent<Payload.UpdateConverationMemberLeave>,
originalEvent: ZMUpdateEvent,
in context: NSManagedObjectContext
) async {
let (conversation, removedUsers) = await context.perform {
let conversation = fetchOrCreateConversation(
from: payload,
in: context
)
let removedUsers = fetchRemovedUsers(
from: payload.data,
in: context
)
return (conversation, removedUsers)
}
guard let conversation, let removedUsers else {
return Logging.eventProcessing.error("Member leave update missing conversation or users, aborting...")
}
let (isSelfUserRemoved, messageProtocol) = await context.perform {
if !conversation.localParticipants.isDisjoint(with: removedUsers) {
// TODO jacob refactor to append method on conversation
_ = ZMSystemMessage.createOrUpdate(
from: originalEvent,
in: context
)
}
let initiatingUser = fetchOrCreateSender(
from: payload,
in: context
)
// Idea for improvement, return removed users from this call to benefit from
// checking that the participants are in the conversation before being removed
conversation.removeParticipantsAndUpdateConversationState(users: Set(removedUsers), initiatingUser: initiatingUser)
let isSelfUserRemoved = removedUsers.contains(where: \.isSelfUser)
return (isSelfUserRemoved, conversation.messageProtocol)
}
if isSelfUserRemoved, messageProtocol.isOne(of: .mls, .mixed) {
await mlsEventProcessor.wipeMLSGroup(forConversation: conversation, context: context)
}
await context.perform {
if payload.data.reason == .userDeleted {
// delete the users locally and/or logout if the self user is affected
let removedUsers = removedUsers.sorted { !$0.isSelfUser && $1.isSelfUser }
for user in removedUsers {
// only delete users that had been members
guard let membership = user.membership else {
WireLogger.updateEvent.error("Trying to delete non existent membership of \(user)")
continue
}
context.delete(membership)
if user.isSelfUser {
// should actually be handled by the "user.delete" event, this is just a fallback
DispatchQueue.main.async {
AccountDeletedNotification(context: context)
.post(in: context.notificationContext)
}
} else {
user.markAccountAsDeleted(at: originalEvent.timestamp ?? Date())
}
}
}
}
}
// MARK: - Member join
func processPayload(
_ payload: Payload.ConversationEvent<Payload.UpdateConverationMemberJoin>,
originalEvent: ZMUpdateEvent,
in context: NSManagedObjectContext
) {
guard let conversation = fetchOrCreateConversation(
from: payload,
in: context
) else {
Logging.eventProcessing.error("Member join update missing conversation, aborting...")
return
}
if let usersAndRoles = payload.data.users?.map({
fetchUserAndRole(
from: $0,
for: conversation,
in: context
)!
}) {
let users = Set(usersAndRoles.map { $0.0 })
let newUsers = !users.subtracting(conversation.localParticipants).isEmpty
if newUsers && conversation.conversationType == .group {
// TODO jacob refactor to append method on conversation
_ = ZMSystemMessage.createOrUpdate(from: originalEvent, in: context)
}
conversation.addParticipantsAndUpdateConversationState(usersAndRoles: usersAndRoles)
} else if let users = payload.data.userIDs?.map({ ZMUser.fetchOrCreate(with: $0, domain: nil, in: context) }) {
// NOTE: legacy code path for backwards compatibility with servers without role support
let users = Set(users)
let selfUser = ZMUser.selfUser(in: context)
if (!users.isSubset(of: conversation.localParticipantsExcludingSelf) || users.contains(selfUser)) && conversation.conversationType == .group {
// TODO jacob refactor to append method on conversation
_ = ZMSystemMessage.createOrUpdate(from: originalEvent, in: context)
}
conversation.addParticipantsAndUpdateConversationState(users: users, role: nil)
}
}
// MARK: - Conversation rename
func processPayload(
_ payload: Payload.ConversationEvent<Payload.UpdateConversationName>,
originalEvent: ZMUpdateEvent,
in context: NSManagedObjectContext
) {
guard let conversation = fetchOrCreateConversation(
from: payload,
in: context
) else {
Logging.eventProcessing.error("Conversation name update missing conversation, aborting...")
return
}
if conversation.userDefinedName != payload.data.name || ((conversation.modifiedKeys?.contains(ZMConversationUserDefinedNameKey)) != nil) {
// TODO jacob refactor to append method on conversation
_ = ZMSystemMessage.createOrUpdate(from: originalEvent, in: context)
}
conversation.userDefinedName = payload.data.name
}
// MARK: - Member update
func processPayload(
_ payload: Payload.ConversationEvent<Payload.ConversationMember>,
in context: NSManagedObjectContext
) {
guard
let conversation = fetchOrCreateConversation(
from: payload,
in: context
),
let targetUser = fetchOrCreateTargetUser(
from: payload.data,
in: context
)
else {
Logging.eventProcessing.error("Conversation member update missing conversation or target user, aborting...")
return
}
if targetUser.isSelfUser {
if let mutedStatus = payload.data.mutedStatus,
let mutedReference = payload.data.mutedReference {
conversation.updateMutedStatus(status: Int32(mutedStatus), referenceDate: mutedReference)
}
if let archived = payload.data.archived,
let archivedReference = payload.data.archivedReference {
conversation.updateArchivedStatus(archived: archived, referenceDate: archivedReference)
}
}
if let role = payload.data.conversationRole.map({ conversation.fetchOrCreateRoleForConversation(name: $0) }) {
conversation.addParticipantAndUpdateConversationState(user: targetUser, role: role)
}
}
// MARK: - Access mode update
func processPayload(
_ payload: Payload.ConversationEvent<Payload.UpdateConversationAccess>,
in context: NSManagedObjectContext
) {
guard let conversation = fetchOrCreateConversation(
from: payload,
in: context
) else {
Logging.eventProcessing.error("Converation access update missing conversation, aborting...")
return
}
if let accessRoles = payload.data.accessRoleV2 {
conversation.updateAccessStatus(accessModes: payload.data.access, accessRoles: accessRoles)
} else if let accessRole = payload.data.accessRole, let legacyAccessRole = ConversationAccessRole(rawValue: accessRole) {
let accessRoles = ConversationAccessRoleV2.fromLegacyAccessRole(legacyAccessRole)
conversation.updateAccessStatus(accessModes: payload.data.access, accessRoles: accessRoles.map(\.rawValue))
}
}
// MARK: - Message timer update
func processPayload(
_ payload: Payload.ConversationEvent<Payload.UpdateConversationMessageTimer>,
in context: NSManagedObjectContext
) {
guard
let sender = fetchOrCreateSender(
from: payload,
in: context
),
let conversation = fetchOrCreateConversation(
from: payload,
in: context
)
else {
Logging.eventProcessing.error("Conversation message timer update missing sender or conversation, aborting...")
return
}
let timeoutValue = (payload.data.messageTimer ?? 0) / 1000
let timeout: MessageDestructionTimeoutValue = .init(rawValue: timeoutValue)
let currentTimeout = conversation.activeMessageDestructionTimeoutValue ?? .init(rawValue: 0)
if let timestamp = payload.timestamp, currentTimeout != timeout {
conversation.appendMessageTimerUpdateMessage(fromUser: sender, timer: timeoutValue, timestamp: timestamp)
}
conversation.setMessageDestructionTimeoutValue(.init(rawValue: timeoutValue), for: .groupConversation)
}
// MARK: - Receipt mode update
func processPayload(
_ payload: Payload.ConversationEvent<Payload.UpdateConversationReceiptMode>,
in context: NSManagedObjectContext
) {
guard
let sender = fetchOrCreateSender(
from: payload,
in: context
),
let conversation = fetchOrCreateConversation(
from: payload,
in: context
),
let timestamp = payload.timestamp,
timestamp > conversation.lastServerTimeStamp // Discard event if it has already been applied
else {
Logging.eventProcessing.error("Conversation receipt mode has already been updated, aborting...")
return
}
let enabled = payload.data.readReceiptMode > 0
conversation.hasReadReceiptsEnabled = enabled
conversation.appendMessageReceiptModeChangedMessage(fromUser: sender, timestamp: timestamp, enabled: enabled)
}
// MARK: - Connection request
func processPayload(
_ payload: Payload.ConversationEvent<Payload.UpdateConversationConnectionRequest>,
originalEvent: ZMUpdateEvent,
in context: NSManagedObjectContext
) {
// TODO jacob refactor to append method on conversation
_ = ZMSystemMessage.createOrUpdate(from: originalEvent, in: context)
}
// MARK: - Protocol Change
func processPayload(
_ payload: Payload.ConversationEvent<Payload.UpdateConversationProtocolChange>,
originalEvent: ZMUpdateEvent,
in context: NSManagedObjectContext
) async {
guard let qualifiedID = payload.qualifiedID else {
Logging.eventProcessing.error("processPayload of event type \(originalEvent.type): Conversation qualifiedID missing, aborting...")
return
}
do {
var action = SyncConversationAction(qualifiedID: qualifiedID)
try await action.perform(in: context.notificationContext)
} catch {
Logging.eventProcessing.error("processPayload of event type \(originalEvent.type): sync conversation failed with error: \(error)")
}
}
// MARK: - Helpers
@discardableResult
func updateOrCreateConversation(
from payload: Payload.Conversation,
serverTimestamp: Date = Date(),
source: Source = .eventStream,
in context: NSManagedObjectContext
) async -> ZMConversation? {
guard let conversationType = payload.type.map(BackendConversationType.clientConversationType) else {
return nil
}
Flow.createGroup.checkpoint(description: "create ZMConversation of type \(conversationType))")
switch conversationType {
case .group:
return await updateOrCreateGroupConversation(
from: payload,
in: context,
serverTimestamp: serverTimestamp,
source: source
)
case .`self`:
return await updateOrCreateSelfConversation(
from: payload,
in: context,
serverTimestamp: serverTimestamp,
source: source
)
case .connection:
// Conversations are of type `connection` while the connection
// is pending.
return await updateOrCreateConnectionConversation(
from: payload,
in: context,
serverTimestamp: serverTimestamp,
source: source
)
case .oneOnOne:
// Conversations are of type `oneOnOne` when the connection
// is accepted.
return await self.updateOrCreateOneToOneConversation(
from: payload,
in: context,
serverTimestamp: serverTimestamp,
source: source
)
default:
return nil
}
}
@discardableResult
func updateOrCreateGroupConversation(
from payload: Payload.Conversation,
in context: NSManagedObjectContext,
serverTimestamp: Date,
source: Source
) async -> ZMConversation? {
guard let conversationID = payload.id ?? payload.qualifiedID?.uuid else {
Flow.createGroup.fail(ConversationEventPayloadProcessorError.noBackendConversationId)
Logging.eventProcessing.error("Missing conversationID in group conversation payload, aborting...")
return nil
}
var created = false
let conversation = await context.perform {
let conversation = ZMConversation.fetchOrCreate(
with: conversationID,
domain: payload.qualifiedID?.domain,
in: context,
created: &created
)
conversation.conversationType = .group
conversation.remoteIdentifier = conversationID
conversation.isPendingMetadataRefresh = false
self.updateAttributes(from: payload, for: conversation, context: context)
self.updateMetadata(from: payload, for: conversation, context: context)
self.updateMembers(from: payload, for: conversation, context: context)
self.updateConversationTimestamps(for: conversation, serverTimestamp: serverTimestamp)
self.updateConversationStatus(from: payload, for: conversation)
if created {
self.assignMessageProtocol(from: payload, for: conversation, in: context)
} else {
self.updateMessageProtocol(from: payload, for: conversation, in: context)
}
Flow.createGroup.checkpoint(description: "conversation created remote id: \(conversation.remoteIdentifier?.safeForLoggingDescription ?? "<nil>")")
return conversation
}
await updateMLSStatus(from: payload, for: conversation, context: context, source: source)
await context.perform {
if created {
// we just got a new conversation, we display new conversation header
conversation.appendNewConversationSystemMessage(
at: serverTimestamp,
users: conversation.localParticipants
)
if source == .slowSync {
// Slow synced conversations should be considered read from the start
conversation.lastReadServerTimeStamp = conversation.lastModifiedDate
}
Flow.createGroup.checkpoint(description: "new system message for conversation inserted")
}
// If we discover this group is actually a fake one on one,
// then we should link the one on one user.
linkOneOnOneUserIfNeeded(for: conversation)
}
return conversation
}
private func linkOneOnOneUserIfNeeded(for conversation: ZMConversation) {
guard
conversation.conversationType == .oneOnOne,
let otherUser = conversation.localParticipantsExcludingSelf.first
else {
return
}
conversation.oneOnOneUser = otherUser
}
@discardableResult
func updateOrCreateSelfConversation(
from payload: Payload.Conversation,
in context: NSManagedObjectContext,
serverTimestamp: Date,
source: Source
) async -> ZMConversation? {
guard let conversationID = payload.id ?? payload.qualifiedID?.uuid else {
Logging.eventProcessing.error("Missing conversationID in self conversation payload, aborting...")
return nil
}
var created = false
let (conversation, mlsGroupID) = await context.perform { [self] in
let conversation = ZMConversation.fetchOrCreate(
with: conversationID,
domain: payload.qualifiedID?.domain,
in: context,
created: &created
)
conversation.conversationType = .`self`
conversation.isPendingMetadataRefresh = false
updateAttributes(from: payload, for: conversation, context: context)
updateMetadata(from: payload, for: conversation, context: context)
updateMembers(from: payload, for: conversation, context: context)
updateConversationTimestamps(for: conversation, serverTimestamp: serverTimestamp)
updateMessageProtocol(from: payload, for: conversation, in: context)
return (conversation, conversation.mlsGroupID)
}
if mlsGroupID != nil {
do {
try await createOrJoinSelfConversation(from: conversation)
} catch {
WireLogger.mls.error("createOrJoinSelfConversation threw error: \(String(reflecting: error))")
}
}
return conversation
}
func createOrJoinSelfConversation(from conversation: ZMConversation) async throws {
guard let context = conversation.managedObjectContext else {
return WireLogger.mls.warn("conversation.managedObjectContext is nil")
}
let (groupID, mlsService, hasRegisteredMLSClient) = await context.perform {
(
conversation.mlsGroupID,
context.mlsService,
ZMUser.selfUser(in: context).selfClient()?.hasRegisteredMLSClient == true
)
}
guard let groupID, let mlsService, hasRegisteredMLSClient else {
WireLogger.mls.warn("no mlsService or not registered mls client to createOrJoinSelfConversation")
return
}
WireLogger.mls.debug("createOrJoinSelfConversation for \(groupID.safeForLoggingDescription); conv payload: \(String(describing: self))")
if await context.perform({ conversation.epoch <= 0 }) {
await mlsService.createSelfGroup(for: groupID)
} else if await !mlsService.conversationExists(groupID: groupID) {
try await mlsService.joinGroup(with: groupID)
}
}
@discardableResult
func updateOrCreateConnectionConversation(
from payload: Payload.Conversation,
in context: NSManagedObjectContext,
serverTimestamp: Date,
source: Source
) async -> ZMConversation? {
guard let conversationID = payload.id ?? payload.qualifiedID?.uuid else {
Logging.eventProcessing.error("Missing conversation or type in 1:1 conversation payload, aborting...")
return nil
}
return await context.perform {
let conversation = ZMConversation.fetchOrCreate(
with: conversationID,
domain: payload.qualifiedID?.domain,
in: context
)
conversation.conversationType = .connection
updateAttributes(from: payload, for: conversation, context: context)
updateMessageProtocol(from: payload, for: conversation, in: context)
updateMetadata(from: payload, for: conversation, context: context)
updateMembers(from: payload, for: conversation, context: context)
updateConversationTimestamps(for: conversation, serverTimestamp: serverTimestamp)
updateConversationStatus(from: payload, for: conversation)
conversation.needsToBeUpdatedFromBackend = false
return conversation
}
}
@discardableResult
func updateOrCreateOneToOneConversation(
from payload: Payload.Conversation,
in context: NSManagedObjectContext,
serverTimestamp: Date,
source: Source
) async -> ZMConversation? {
guard
let conversationID = payload.id ?? payload.qualifiedID?.uuid,
let conversationType = payload.type.map(BackendConversationType.clientConversationType)
else {
Logging.eventProcessing.error("Missing conversation or type in 1:1 conversation payload, aborting...")
return nil
}
let conversation = await context.perform {
let conversation = ZMConversation.fetchOrCreate(
with: conversationID,
domain: payload.qualifiedID?.domain,
in: context
)
conversation.conversationType = self.conversationType(for: conversation, from: conversationType)
updateAttributes(from: payload, for: conversation, context: context)
updateMessageProtocol(from: payload, for: conversation, in: context)
updateMetadata(from: payload, for: conversation, context: context)
updateMembers(from: payload, for: conversation, context: context)
updateConversationTimestamps(for: conversation, serverTimestamp: serverTimestamp)
updateConversationStatus(from: payload, for: conversation)
linkOneOnOneUserIfNeeded(for: conversation)
conversation.needsToBeUpdatedFromBackend = false
if let otherUser = conversation.localParticipantsExcludingSelf.first {
conversation.isPendingMetadataRefresh = otherUser.isPendingMetadataRefresh
}
return conversation
}
return conversation
}
private func updateAttributes(
from payload: Payload.Conversation,
for conversation: ZMConversation,
context: NSManagedObjectContext
) {
conversation.domain = BackendInfo.isFederationEnabled ? payload.qualifiedID?.domain : nil
conversation.needsToBeUpdatedFromBackend = false
if let epoch = payload.epoch {
conversation.epoch = UInt64(epoch)
}
if
let base64String = payload.mlsGroupID,
let mlsGroupID = MLSGroupID(base64Encoded: base64String)
{
conversation.mlsGroupID = mlsGroupID
}
}
func updateMetadata(
from payload: Payload.Conversation,
for conversation: ZMConversation,
context: NSManagedObjectContext
) {
if let teamID = payload.teamID {
conversation.updateTeam(identifier: teamID)
}
if let name = payload.name {
conversation.userDefinedName = name
}
if let creator = fetchCreator(
from: payload,
in: context
) {
conversation.creator = creator
}
}
func updateMembers(
from payload: Payload.Conversation,
for conversation: ZMConversation,
context: NSManagedObjectContext
) {
guard let members = payload.members else {
return
}
let otherMembers = fetchOtherMembers(
from: members,
conversation: conversation,
in: context
)
let selfUserRole = fetchUserAndRole(
from: members.selfMember,
for: conversation,
in: context
)?.1
conversation.updateMembers(otherMembers, selfUserRole: selfUserRole)
}
func updateConversationTimestamps(
for conversation: ZMConversation,
serverTimestamp: Date
) {
// If the lastModifiedDate is non-nil, e.g. restore from backup,
// do not update the lastModifiedDate.
if conversation.lastModifiedDate == nil {
conversation.updateLastModified(serverTimestamp)
}
conversation.updateServerModified(serverTimestamp)
}
func updateConversationStatus(
from payload: Payload.Conversation,
for conversation: ZMConversation
) {
if let selfMember = payload.members?.selfMember {
updateMemberStatus(
from: selfMember,
for: conversation
)
}
if let readReceiptMode = payload.readReceiptMode {
conversation.updateReceiptMode(readReceiptMode)
}
if let accessModes = payload.access {
if let accessRoles = payload.accessRoles {
conversation.updateAccessStatus(accessModes: accessModes, accessRoles: accessRoles)
} else if
let accessRole = payload.legacyAccessRole,
let legacyAccessRole = ConversationAccessRole(rawValue: accessRole) {
let accessRoles = ConversationAccessRoleV2.fromLegacyAccessRole(legacyAccessRole)
conversation.updateAccessStatus(accessModes: accessModes, accessRoles: accessRoles.map(\.rawValue))
}
}
if let messageTimer = payload.messageTimer {
conversation.updateMessageDestructionTimeout(timeout: messageTimer)
}
}
private func assignMessageProtocol(
from payload: Payload.Conversation,
for conversation: ZMConversation,
in context: NSManagedObjectContext
) {
guard let messageProtocolString = payload.messageProtocol else {
Logging.eventProcessing.warn("message protocol is missing")
return
}
guard let newMessageProtocol = MessageProtocol(rawValue: messageProtocolString) else {
Logging.eventProcessing.warn("message protocol is invalid, got: \(messageProtocolString)")
return
}
conversation.messageProtocol = newMessageProtocol
}
private func updateMessageProtocol(
from payload: Payload.Conversation,
for conversation: ZMConversation,
in context: NSManagedObjectContext
) {
guard let messageProtocolString = payload.messageProtocol else {
Logging.eventProcessing.warn("message protocol is missing")
return
}
guard let newMessageProtocol = MessageProtocol(rawValue: messageProtocolString) else {
Logging.eventProcessing.warn("message protocol is invalid, got: \(messageProtocolString)")
return
}
let sender = ZMUser.selfUser(in: context)
switch conversation.messageProtocol {
case .proteus:
switch newMessageProtocol {
case .proteus:
break // no update, ignore
case .mixed:
conversation.appendMLSMigrationStartedSystemMessage(sender: sender, at: .now)
conversation.messageProtocol = newMessageProtocol
case .mls:
let date = conversation.lastModifiedDate ?? .now
conversation.appendMLSMigrationPotentialGapSystemMessage(sender: sender, at: date)
conversation.messageProtocol = newMessageProtocol
}
case .mixed:
switch newMessageProtocol {
case .proteus:
WireLogger.updateEvent.warn("update message protocol from \(conversation.messageProtocol) to \(newMessageProtocol) is not allowed, ignore event!")
case .mixed:
break // no update, ignore
case .mls:
conversation.appendMLSMigrationFinalizedSystemMessage(sender: sender, at: .now)
conversation.messageProtocol = newMessageProtocol
}
case .mls:
switch newMessageProtocol {
case .proteus, .mixed:
WireLogger.updateEvent.warn("update message protocol from '\(conversation.messageProtocol)' to '\(newMessageProtocol)' is not allowed, ignore event!")
case .mls:
break // no update, ignore
}
}
}
private func updateMLSStatus(
from payload: Payload.Conversation,
for conversation: ZMConversation,
context: NSManagedObjectContext,
source: Source
) async {
await mlsEventProcessor.updateConversationIfNeeded(
conversation: conversation,
fallbackGroupID: payload.mlsGroupID.map { .init(base64Encoded: $0) } ?? nil,
context: context
)
}
func fetchCreator(
from payload: Payload.Conversation,
in context: NSManagedObjectContext
) -> ZMUser? {
guard let userID = payload.creator else {
return nil
}
// We assume that the creator always belongs to the same domain as the conversation
return ZMUser.fetchOrCreate(
with: userID,
domain: payload.qualifiedID?.domain,
in: context
)
}
private func conversationType(
for conversation: ZMConversation?,
from type: ZMConversationType
) -> ZMConversationType {
guard let conversation = conversation else {
return type
}
// The backend can't distinguish between one-to-one and connection conversation
// types across federated enviroments so check locally if it's a connection.
if conversation.oneOnOneUser?.connection?.status == .sent {
return .connection
} else {
return type
}
}
func fetchOrCreateConversation<T>(
from payload: Payload.ConversationEvent<T>,
in context: NSManagedObjectContext
) -> ZMConversation? {
guard let conversationID = payload.id ?? payload.qualifiedID?.uuid else {
return nil
}
return ZMConversation.fetchOrCreate(
with: conversationID,
domain: payload.qualifiedID?.domain,
in: context
)
}
func fetchRemovedUsers(
from payload: Payload.UpdateConverationMemberLeave,
in context: NSManagedObjectContext
) -> [ZMUser]? {
if let users = payload.qualifiedUserIDs?.map({ ZMUser.fetchOrCreate(with: $0.uuid, domain: $0.domain, in: context) }) {
return users
}
if let users = payload.userIDs?.map({ ZMUser.fetchOrCreate(with: $0, domain: nil, in: context) }) {
return users
}
return nil
}
func fetchOrCreateSender<T>(
from payload: Payload.ConversationEvent<T>,
in context: NSManagedObjectContext
) -> ZMUser? {
guard let userID = payload.from ?? payload.qualifiedFrom?.uuid else {
return nil
}
return ZMUser.fetchOrCreate(
with: userID,
domain: payload.qualifiedFrom?.domain,
in: context
)
}
func fetchOrCreateTargetUser(
from payload: Payload.ConversationMember,
in context: NSManagedObjectContext
) -> ZMUser? {
guard let userID = payload.target ?? payload.qualifiedTarget?.uuid else {
return nil
}
return ZMUser.fetchOrCreate(
with: userID,
domain: payload.qualifiedTarget?.domain,
in: context
)
}
func fetchOtherMembers(
from payload: Payload.ConversationMembers,
conversation: ZMConversation,
in context: NSManagedObjectContext
) -> [(ZMUser, Role?)] {
return payload.others.compactMap {
fetchUserAndRole(
from: $0,
for: conversation,
in: context
)
}
}
func fetchUserAndRole(
from payload: Payload.ConversationMember,