-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathFetchingClientRequestStrategy.swift
More file actions
536 lines (438 loc) · 19 KB
/
Copy pathFetchingClientRequestStrategy.swift
File metadata and controls
536 lines (438 loc) · 19 KB
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
//
// Wire
// Copyright (C) 2025 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 WireCryptobox
import WireDataModel
import WireSystem
import WireTransport
import WireUtilities
public let ZMNeedsToUpdateUserClientsNotificationUserObjectIDKey = "userObjectID"
@objc
public extension ZMUser {
func fetchUserClients() {
NotificationInContext(
name: FetchingClientRequestStrategy.needsToUpdateUserClientsNotificationName,
context: managedObjectContext!.notificationContext,
object: objectID
).post()
}
}
@objc
public final class FetchingClientRequestStrategy: AbstractRequestStrategy {
fileprivate static let needsToUpdateUserClientsNotificationName = Notification
.Name("ZMNeedsToUpdateUserClientsNotification")
fileprivate var userClientsObserverToken: Any?
fileprivate var userClientsByUserID: IdentifierObjectSync<UserClientByUserIDTranscoder>
fileprivate var userClientsByUserClientID: IdentifierObjectSync<UserClientByUserClientIDTranscoder>
fileprivate var userClientsByQualifiedUserID: IdentifierObjectSync<UserClientByQualifiedUserIDTranscoder>
var userClientByUserIDTranscoder: UserClientByUserIDTranscoder
var userClientByUserClientIDTranscoder: UserClientByUserClientIDTranscoder
var userClientByQualifiedUserIDTranscoder: UserClientByQualifiedUserIDTranscoder
private let entitySync: EntityActionSync
private let apiVersion: WireTransport.APIVersion?
private let localDomain: String?
public init(
withManagedObjectContext managedObjectContext: NSManagedObjectContext,
applicationStatus: ApplicationStatus,
apiVersion: WireTransport.APIVersion?,
localDomain: String?
) {
self.userClientByUserIDTranscoder = UserClientByUserIDTranscoder(managedObjectContext: managedObjectContext)
self
.userClientByUserClientIDTranscoder =
UserClientByUserClientIDTranscoder(managedObjectContext: managedObjectContext)
self
.userClientByQualifiedUserIDTranscoder =
UserClientByQualifiedUserIDTranscoder(managedObjectContext: managedObjectContext)
self.userClientsByUserID = IdentifierObjectSync(
managedObjectContext: managedObjectContext,
transcoder: userClientByUserIDTranscoder
)
self.userClientsByUserClientID = IdentifierObjectSync(
managedObjectContext: managedObjectContext,
transcoder: userClientByUserClientIDTranscoder
)
self.userClientsByQualifiedUserID = IdentifierObjectSync(
managedObjectContext: managedObjectContext,
transcoder: userClientByQualifiedUserIDTranscoder
)
self.entitySync = EntityActionSync(actionHandlers: [
FetchUserClientsActionHandler(context: managedObjectContext)
])
self.apiVersion = apiVersion
self.localDomain = localDomain
super.init(withManagedObjectContext: managedObjectContext, applicationStatus: applicationStatus)
self.configuration = [
.allowsRequestsWhileOnline,
.allowsRequestsDuringQuickSync,
.allowsRequestsWhileWaitingForWebsocket,
.allowsRequestsWhileInBackground
]
userClientByQualifiedUserIDTranscoder.contextChangedTracker = self
self.userClientsObserverToken = NotificationInContext.addObserver(
name: FetchingClientRequestStrategy.needsToUpdateUserClientsNotificationName,
context: self.managedObjectContext.notificationContext,
object: nil
) { [weak self] note in
guard let self, let objectID = note.object as? NSManagedObjectID else { return }
self.managedObjectContext.performGroupedBlock {
guard
let apiVersion,
let user = (try? self.managedObjectContext.existingObject(with: objectID)) as? ZMUser,
let userID = user.remoteIdentifier
else {
return
}
switch apiVersion {
case .v0:
let userIdSet: Set<UserClientByUserIDTranscoder.T> = [userID]
self.userClientsByUserID.sync(identifiers: userIdSet)
case .v1:
if let domain = user.domain {
let qualifiedID = QualifiedID(uuid: userID, domain: domain)
self.userClientsByQualifiedUserID.sync(identifiers: [qualifiedID])
} else {
let userIdSet: Set<UserClientByUserIDTranscoder.T> = [userID]
self.userClientsByUserID.sync(identifiers: userIdSet)
}
case .v2, .v3, .v4, .v5, .v6, .v7, .v8, .v9, .v10, .v11, .v12, .v13:
let domain = if let domain = user.domain, !domain.isEmpty { domain } else { localDomain }
if let domain {
let qualifiedID = QualifiedID(uuid: userID, domain: domain)
self.userClientsByQualifiedUserID.sync(identifiers: [qualifiedID])
}
}
RequestAvailableNotification.notifyNewRequestsAvailable(self)
}
}
}
public override func nextRequestIfAllowed(for apiVersion: APIVersion) -> ZMTransportRequest? {
// There may exist some clients that need an update, so try to sync any before asking
// for requests.
syncClientsNeedingUpdateIfNeeded()
return
userClientsByUserClientID.nextRequest(for: apiVersion) ??
userClientsByUserID.nextRequest(for: apiVersion) ??
userClientsByQualifiedUserID.nextRequest(for: apiVersion) ??
entitySync.nextRequest(for: apiVersion)
}
private func syncClientsNeedingUpdateIfNeeded() {
let clients = UserClient.fetchClientsNeedingUpdateFromBackend(in: managedObjectContext)
fetch(userClients: clients)
}
}
extension FetchingClientRequestStrategy: ZMContextChangeTracker, ZMContextChangeTrackerSource {
public var contextChangeTrackers: [ZMContextChangeTracker] {
[self]
}
public func fetchRequestForTrackedObjects() -> NSFetchRequest<NSFetchRequestResult>? {
UserClient.sortedFetchRequest(with: UserClient.predicateForNeedingToBeUpdatedFromBackend())
}
public func addTrackedObjects(_ objects: Set<NSManagedObject>) {
let clientsNeedingToBeUpdated = objects.compactMap { $0 as? UserClient }
fetch(userClients: clientsNeedingToBeUpdated)
}
public func objectsDidChange(_ object: Set<NSManagedObject>) {
let clientsNeedingToBeUpdated = object.compactMap { $0 as? UserClient }.filter(\.needsToBeUpdatedFromBackend)
fetch(userClients: clientsNeedingToBeUpdated)
}
private func fetch(userClients: [UserClient]) {
guard let apiVersion else { return }
let initialResult: ([QualifiedID], [UserClientByUserClientIDTranscoder.UserClientID]) = ([], [])
let result = userClients.reduce(into: initialResult) { result, userClient in
switch apiVersion {
case .v0:
guard let userClientID = userClientID(from: userClient) else { return }
result.1.append(userClientID)
case .v1:
// We prefer to by qualifiedUserID since can be done in batches and is more efficent.
if let qualifiedID = qualifiedID(from: userClient) {
result.0.append(qualifiedID)
} else if let userClientID = userClientID(from: userClient) {
// Fallback.
result.1.append(userClientID)
}
case .v2, .v3, .v4, .v5, .v6, .v7, .v8, .v9, .v10, .v11, .v12, .v13:
if let qualifiedID = qualifiedIDWithFallback(from: userClient) {
result.0.append(qualifiedID)
}
}
}
userClientsByQualifiedUserID.sync(identifiers: Set(result.0))
userClientsByUserClientID.sync(identifiers: Set(result.1))
}
private func userClientID(from userClient: UserClient) -> UserClientByUserClientIDTranscoder.UserClientID? {
guard
let userID = userClient.user?.remoteIdentifier,
let clientID = userClient.remoteIdentifier
else {
return nil
}
return .init(userId: userID, clientId: clientID)
}
private func qualifiedID(from userClient: UserClient) -> QualifiedID? {
guard
let userID = userClient.user?.remoteIdentifier,
let domain = userClient.user?.domain
else {
return nil
}
return .init(uuid: userID, domain: domain)
}
private func qualifiedIDWithFallback(from userClient: UserClient) -> QualifiedID? {
let domain = if let domain = userClient.user?.domain, !domain.isEmpty { domain } else { localDomain }
guard let userID = userClient.user?.remoteIdentifier, let domain else { return nil }
return .init(uuid: userID, domain: domain)
}
}
final class UserClientByUserClientIDTranscoder: IdentifierObjectSyncTranscoder {
struct UserClientID: Hashable {
let userId: UUID
let clientId: String
}
public typealias T = UserClientID
var managedObjectContext: NSManagedObjectContext
let decoder: JSONDecoder = .defaultDecoder
private let processor = UserClientPayloadProcessor()
init(managedObjectContext: NSManagedObjectContext) {
self.managedObjectContext = managedObjectContext
}
var fetchLimit: Int {
1
}
public func request(for identifiers: Set<UserClientID>, apiVersion: APIVersion) -> ZMTransportRequest? {
guard let identifier = identifiers.first else { return nil }
let path = "/users/\(identifier.userId.transportString())/clients/\(identifier.clientId)"
return ZMTransportRequest(path: path, method: .get, payload: nil, apiVersion: apiVersion.rawValue)
}
public func didReceive(
response: ZMTransportResponse,
for identifiers: Set<UserClientID>,
completionHandler: @escaping () -> Void
) {
guard
let identifier = identifiers.first,
let client = UserClient.fetchUserClient(
withRemoteId: identifier.clientId,
forUser: ZMUser.fetchOrCreate(
with: identifier.userId,
domain: nil,
in: managedObjectContext
),
createIfNeeded: true
)
else {
Logging.network.warn("Can't process response, aborting.")
return completionHandler()
}
if response.result == .permanentError {
WaitingGroupTask(context: managedObjectContext) {
await client.deleteClientAndEndSession()
completionHandler()
}
} else if let rawData = response.rawData,
let payload = Payload.UserClient(rawData, decoder: decoder) {
processor.updateClient(
client,
from: payload
)
let selfClient = ZMUser.selfUser(in: managedObjectContext).selfClient()
let clientSet: Set<UserClient> = [client]
selfClient?.updateSecurityLevelAfterDiscovering(clientSet)
completionHandler()
}
}
}
final class UserClientByQualifiedUserIDTranscoder: IdentifierObjectSyncTranscoder {
public typealias T = QualifiedID
weak var contextChangedTracker: ZMContextChangeTracker?
var managedObjectContext: NSManagedObjectContext
let decoder: JSONDecoder = .defaultDecoder
let encoder: JSONEncoder = .defaultEncoder
private let processor = UserClientPayloadProcessor()
init(managedObjectContext: NSManagedObjectContext) {
self.managedObjectContext = managedObjectContext
}
var fetchLimit: Int {
100
}
struct RequestPayload: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case qualifiedIDs = "qualified_users"
}
let qualifiedIDs: Set<QualifiedID>
}
public func request(for identifiers: Set<QualifiedID>, apiVersion: APIVersion) -> ZMTransportRequest? {
switch apiVersion {
case .v0:
Logging.network.warn("fetching user clients by qualified id is not available on API V0.")
return nil
case .v1:
return v1Request(for: identifiers)
case .v2, .v3, .v4, .v5, .v6, .v7, .v8, .v9, .v10, .v11, .v12, .v13:
return v2Request(for: identifiers, apiVersion: apiVersion)
}
}
private func v1Request(for identifiers: Set<QualifiedID>) -> ZMTransportRequest? {
guard
let payloadData = RequestPayload(qualifiedIDs: identifiers).payloadData(encoder: encoder),
let payloadAsString = String(bytes: payloadData, encoding: .utf8)
else {
return nil
}
return ZMTransportRequest(
path: "/users/list-clients/v2",
method: .post,
payload: payloadAsString as ZMTransportData?,
apiVersion: 1
)
}
private func v2Request(for identifiers: Set<QualifiedID>, apiVersion: APIVersion) -> ZMTransportRequest? {
guard
let payloadData = RequestPayload(qualifiedIDs: identifiers).payloadData(encoder: encoder),
let payloadAsString = String(bytes: payloadData, encoding: .utf8)
else {
return nil
}
return ZMTransportRequest(
path: "/users/list-clients",
method: .post,
payload: payloadAsString as ZMTransportData?,
apiVersion: apiVersion.rawValue
)
}
struct ResponsePayload: Codable {
enum CodingKeys: String, CodingKey {
case qualifiedUsers = "qualified_user_map"
}
let qualifiedUsers: Payload.UserClientByDomain
}
public func didReceive(
response: ZMTransportResponse,
for identifiers: Set<QualifiedID>,
completionHandler: @escaping () -> Void
) {
guard let apiVersion = APIVersion(rawValue: response.apiVersion) else { return }
switch apiVersion {
case .v0:
completionHandler()
return
case .v1, .v2, .v3, .v4, .v5, .v6, .v7, .v8, .v9, .v10, .v11, .v12, .v13:
WaitingGroupTask(context: managedObjectContext) { [self] in
await commonResponseHandling(response: response, for: identifiers)
completionHandler()
}
}
}
private func commonResponseHandling(response: ZMTransportResponse, for identifiers: Set<QualifiedID>) async {
guard
let rawData = response.rawData,
let payload = ResponsePayload(rawData, decoder: decoder),
let selfClient = await managedObjectContext
.perform({ ZMUser.selfUser(in: self.managedObjectContext).selfClient() })
else {
Logging.network.warn("Can't process response, aborting.")
await managedObjectContext.perform {
self.markAllClientsAsUpdated(identifiers: identifiers)
}
return
}
for (domain, users) in payload.qualifiedUsers {
for (userID, clientPayloads) in users {
guard let userID = UUID(uuidString: userID) else {
continue
}
let user = await managedObjectContext.perform { ZMUser.fetchOrCreate(
with: userID,
domain: domain,
in: self.managedObjectContext
) }
await processor.createOrUpdateClients(
from: clientPayloads,
for: user,
selfClient: selfClient
)
}
}
// We mark all clients as synced, even if they did not appear in
// the reponse payload, in order to avoid a possible request loop.
await managedObjectContext.perform {
self.markAllClientsAsUpdated(identifiers: identifiers)
}
}
private func markAllClientsAsUpdated(identifiers: Set<QualifiedID>) {
let clients = UserClient.fetchClientsNeedingUpdateFromBackend(in: managedObjectContext)
for client in clients {
if let qualifiedID = client.user?.qualifiedID {
if identifiers.contains(qualifiedID) {
client.needsToBeUpdatedFromBackend = false
}
}
}
managedObjectContext.saveOrRollback()
}
}
final class UserClientByUserIDTranscoder: IdentifierObjectSyncTranscoder {
public typealias T = UUID
var managedObjectContext: NSManagedObjectContext
let decoder: JSONDecoder = .defaultDecoder
private let processor = UserClientPayloadProcessor()
init(managedObjectContext: NSManagedObjectContext) {
self.managedObjectContext = managedObjectContext
}
var fetchLimit: Int {
1
}
public func request(for identifiers: Set<UUID>, apiVersion: APIVersion) -> ZMTransportRequest? {
guard let userId = identifiers.first?.transportString() else { return nil }
let path = "/users/\(userId)/clients"
return ZMTransportRequest(path: path, method: .get, payload: nil, apiVersion: apiVersion.rawValue)
}
public func didReceive(
response: ZMTransportResponse,
for identifiers: Set<UUID>,
completionHandler: @escaping () -> Void
) {
guard
let rawData = response.rawData,
let payload = Payload.UserClients(rawData, decoder: decoder),
let identifier = identifiers.first,
let selfClient = ZMUser.selfUser(in: managedObjectContext).selfClient()
else {
Logging.network.warn("Can't process response, aborting.")
completionHandler()
return
}
let user = ZMUser.fetchOrCreate(
with: identifier,
domain: nil,
in: managedObjectContext
)
WaitingGroupTask(context: managedObjectContext) { [self] in
await processor.createOrUpdateClients(
from: payload,
for: user,
selfClient: selfClient
)
await managedObjectContext.perform { [managedObjectContext] in
managedObjectContext.enqueueDelayedSave()
}
completionHandler()
}
}
}