Crossmate/Sync/FriendController.swift (41874B)
1import CloudKit
2import CoreData
3import Foundation
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20@MainActor
21final class FriendController {
22
23
24
25 typealias FriendInvitationKeyPublisher =
26 (_ pairKey: String, _ friendZoneID: CKRecordZone.ID, _ friendZoneScope: DatabaseScope) async -> Void
27
28 let container: CKContainer
29 private let persistence: PersistenceController
30 private let syncEngine: SyncEngine
31 private let syncMonitor: SyncMonitor?
32 private let eventLog: EventLog?
33 private let fetchAccountDecisionRecord: (CKRecord.ID) async throws -> CKRecord
34 private let publishFriendInvitationKey: FriendInvitationKeyPublisher?
35
36 init(
37 container: CKContainer,
38 persistence: PersistenceController,
39 syncEngine: SyncEngine,
40 syncMonitor: SyncMonitor? = nil,
41 eventLog: EventLog? = nil,
42 publishFriendInvitationKey: FriendInvitationKeyPublisher? = nil,
43 fetchAccountDecisionRecord: ((CKRecord.ID) async throws -> CKRecord)? = nil
44 ) {
45 self.container = container
46 self.persistence = persistence
47 self.syncEngine = syncEngine
48 self.syncMonitor = syncMonitor
49 self.eventLog = eventLog
50 self.publishFriendInvitationKey = publishFriendInvitationKey
51 self.fetchAccountDecisionRecord = fetchAccountDecisionRecord
52 ?? { try await container.privateCloudDatabase.record(for: $0) }
53 }
54
55 enum FriendError: Error {
56 case invalidShareRecord
57 case missingShareURL
58 case participantNotFound
59 case missingShareURLInPayload
60 case friendNotFound
61 case friendBlocked
62 case friendshipNotReady
63 case payloadEncodingFailed
64 }
65
66
67
68
69
70
71
72
73
74
75
76
77 func establish(
78 localAuthorID: String,
79 remoteAuthorID: String,
80 localDisplayName: String?,
81 viaGameID: UUID
82 ) async {
83 guard !remoteAuthorID.isEmpty,
84 localAuthorID != remoteAuthorID
85 else { return }
86
87 let pairKey = FriendZone.pairKey(localAuthorID, remoteAuthorID)
88 if FriendZone.inboxEstablished(pairKey: pairKey) { return }
89 let zoneID = FriendZone.inboxZoneID(pairKey: pairKey)
90
91 syncMonitor?.recordStart("establish friendship")
92 do {
93 try await createZone(zoneID)
94
95
96
97
98
99 if try await existingZoneWideShare(zoneID: zoneID) != nil {
100 persistFriend(authorID: remoteAuthorID, pairKey: pairKey)
101 FriendZone.markInboxEstablished(pairKey: pairKey)
102 syncMonitor?.recordSuccess("establish friendship")
103 return
104 }
105
106 let share: CKShare
107 do {
108 share = try await saveZoneWideShare(
109 zoneID: zoneID,
110 addingParticipant: remoteAuthorID
111 )
112 } catch let error as CKError where error.code == .serverRecordChanged {
113
114
115 persistFriend(authorID: remoteAuthorID, pairKey: pairKey)
116 FriendZone.markInboxEstablished(pairKey: pairKey)
117 syncMonitor?.recordSuccess("establish friendship")
118 return
119 }
120 guard let url = share.url else { throw FriendError.missingShareURL }
121
122 persistFriend(authorID: remoteAuthorID, pairKey: pairKey)
123 FriendZone.markInboxEstablished(pairKey: pairKey)
124
125 let payload = FriendZone.BootstrapPayload(
126 friendShareURL: url.absoluteString,
127 pairKey: pairKey,
128 ownerAuthorID: localAuthorID
129 )
130 await syncEngine.enqueuePing(
131 kind: .friend,
132 gameID: viaGameID,
133 authorID: localAuthorID,
134 playerName: localDisplayName ?? "",
135 payload: payload.encodedString()
136 )
137 syncMonitor?.recordSuccess("establish friendship")
138 } catch {
139 syncMonitor?.recordError("establish friendship", error)
140 }
141 }
142
143
144
145
146
147
148
149 private func seedOwnNameDecision(
150 localAuthorID: String,
151 localDisplayName: String?,
152 zoneID: CKRecordZone.ID
153 ) async {
154 let name = (localDisplayName ?? "")
155 .trimmingCharacters(in: .whitespacesAndNewlines)
156 guard !name.isEmpty else { return }
157 await syncEngine.enqueueNameDecision(
158 authorID: localAuthorID,
159 name: name,
160 version: NameVersionStore.current(authorID: localAuthorID),
161 zoneID: zoneID,
162
163
164 scope: .shared
165 )
166 }
167
168
169
170
171
172
173
174
175 func applyFriendPing(
176 _ ping: Ping,
177 localAuthorID: String?,
178 localDisplayName: String?
179 ) async {
180 guard ping.kind == .friend,
181 let payload = FriendZone.BootstrapPayload.decode(ping.payload)
182 else { return }
183 guard FriendZone.canAcceptBootstrap(payload, localAuthorID: localAuthorID) else { return }
184
185
186
187
188 if FriendZone.outboxAccepted(pairKey: payload.pairKey) { return }
189 guard let url = URL(string: payload.friendShareURL) else { return }
190
191 syncMonitor?.recordStart("accept friendship")
192 do {
193 let metadata = try await fetchShareMetadata(url: url)
194
195
196 let outboxZoneID = metadata.share.recordID.zoneID
197
198
199
200
201
202
203
204
205
206 guard outboxZoneID.zoneName == FriendZone.zoneName(pairKey: payload.pairKey) else {
207 syncMonitor?.note("accept friendship rejected: accepted zone name does not match pair key")
208 return
209 }
210
211
212
213
214
215
216
217
218
219
220
221
222 guard outboxZoneID.ownerName == payload.ownerAuthorID else {
223 syncMonitor?.note("accept friendship rejected: accepted zone owner does not match claimed friend")
224 return
225 }
226 try await accept(metadata)
227 FriendZone.markOutboxAccepted(pairKey: payload.pairKey)
228 persistFriend(authorID: payload.ownerAuthorID, pairKey: payload.pairKey)
229 if let localAuthorID, !localAuthorID.isEmpty {
230
231
232 await seedOwnNameDecision(
233 localAuthorID: localAuthorID,
234 localDisplayName: localDisplayName,
235 zoneID: outboxZoneID
236 )
237 }
238
239
240
241 Task { [weak self] in
242 await self?.publishFriendInvitationKey?(payload.pairKey, outboxZoneID, .shared)
243 }
244 syncMonitor?.recordSuccess("accept friendship")
245
246
247
248
249
250
251
252
253
254
255
256
257
258 Task.detached { [syncEngine, syncMonitor] in
259 await syncMonitor?.run("friendship accept fetch") {
260 try await syncEngine.fetchChanges()
261 }
262 }
263 } catch {
264 syncMonitor?.recordError("accept friendship", error)
265 }
266 }
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286 func healPendingBootstraps(localAuthorID: String, localDisplayName: String?) async {
287 guard !localAuthorID.isEmpty else { return }
288
289 struct PendingPair {
290 let friendAuthorID: String
291 let pairKey: String
292 let viaGameID: UUID?
293 }
294 let ctx = persistence.viewContext
295 let req = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
296 req.predicate = NSPredicate(format: "isBlocked == NO")
297 let pairs: [PendingPair] = ((try? ctx.fetch(req)) ?? []).compactMap { friend in
298 guard let authorID = friend.authorID, !authorID.isEmpty,
299 let pairKey = friend.pairKey
300 else { return nil }
301 return PendingPair(
302 friendAuthorID: authorID,
303 pairKey: pairKey,
304 viaGameID: Self.bootstrapCarrierGameID(friendAuthorID: authorID, in: ctx)
305 )
306 }
307 guard !pairs.isEmpty else { return }
308
309 var healthy = 0, announced = 0, skipped = 0
310 for pair in pairs {
311 do {
312 guard var share = try await existingZoneWideShare(
313 zoneID: FriendZone.inboxZoneID(pairKey: pair.pairKey)
314 ) else {
315
316
317 skipped += 1
318 continue
319 }
320 let participant = share.participants.first {
321 $0.userIdentity.userRecordID?.recordName == pair.friendAuthorID
322 }
323 if participant?.acceptanceStatus == .accepted {
324 healthy += 1
325 continue
326 }
327 guard FriendZone.canAttemptBootstrapHeal(pairKey: pair.pairKey) else {
328 skipped += 1
329 continue
330 }
331 guard let viaGameID = pair.viaGameID else {
332
333
334 skipped += 1
335 continue
336 }
337 if participant == nil || participant?.acceptanceStatus == .removed {
338
339
340
341 let restored = try await fetchParticipant(
342 forUserRecordName: pair.friendAuthorID
343 )
344 restored.permission = .readWrite
345 share.addParticipant(restored)
346 guard let saved = try await container.privateCloudDatabase
347 .save(share) as? CKShare
348 else { throw FriendError.invalidShareRecord }
349 share = saved
350 }
351 guard let url = share.url else { throw FriendError.missingShareURL }
352 FriendZone.markBootstrapHealAttempted(pairKey: pair.pairKey)
353 let payload = FriendZone.BootstrapPayload(
354 friendShareURL: url.absoluteString,
355 pairKey: pair.pairKey,
356 ownerAuthorID: localAuthorID
357 )
358 await syncEngine.enqueuePing(
359 kind: .friend,
360 gameID: viaGameID,
361 authorID: localAuthorID,
362 playerName: localDisplayName ?? "",
363 payload: payload.encodedString()
364 )
365 announced += 1
366 syncMonitor?.note(
367 "friendship heal: re-announced inbox share to " +
368 "\(pair.friendAuthorID.prefix(8))… via game " +
369 "\(viaGameID.uuidString.prefix(8))"
370 )
371 } catch {
372 skipped += 1
373 syncMonitor?.note(
374 "friendship heal: check failed for " +
375 "\(pair.friendAuthorID.prefix(8))… — \(error.localizedDescription)"
376 )
377 }
378 }
379 syncMonitor?.note(
380 "friendship heal: pairs=\(pairs.count) healthy=\(healthy) " +
381 "announced=\(announced) skipped=\(skipped)"
382 )
383 }
384
385
386
387
388
389 private static func bootstrapCarrierGameID(
390 friendAuthorID: String,
391 in ctx: NSManagedObjectContext
392 ) -> UUID? {
393 let req = NSFetchRequest<PlayerEntity>(entityName: "PlayerEntity")
394 req.predicate = NSPredicate(
395 format: "authorID == %@ AND game.isAccessRevoked == NO AND " +
396 "(game.databaseScope == 1 OR game.ckShareRecordName != nil)",
397 friendAuthorID
398 )
399 req.sortDescriptors = [NSSortDescriptor(key: "game.updatedAt", ascending: false)]
400 req.fetchLimit = 1
401 return (try? ctx.fetch(req).first)?.game?.id
402 }
403
404
405
406
407
408
409
410
411
412 func sendInvite(
413 toFriendAuthorID friendAuthorID: String,
414 gameID: UUID,
415 gameTitle: String,
416 inviterAuthorID: String,
417 inviterName: String,
418 gameShareURL: URL,
419 gridSilhouette: String? = nil,
420 puzzleSource: String? = nil,
421 notification: String? = nil,
422 rollbackParticipantOnFailure: Bool = false
423 ) async throws {
424 let ctx = persistence.viewContext
425 let req = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
426 req.predicate = NSPredicate(format: "authorID == %@", friendAuthorID)
427 req.fetchLimit = 1
428 guard let friend = try ctx.fetch(req).first else {
429 throw FriendError.friendNotFound
430 }
431 guard !friend.isBlocked else { throw FriendError.friendBlocked }
432 guard let pairKey = friend.pairKey else { throw FriendError.friendNotFound }
433 try await ensureOutboxAccepted(pairKey: pairKey, friendAuthorID: friendAuthorID)
434
435 let payload = FriendZone.InvitePayload(
436 gameShareURL: gameShareURL.absoluteString,
437 gridSilhouette: gridSilhouette,
438 puzzleSource: puzzleSource,
439 notification: notification
440 )
441 guard let encoded = payload.encodedString() else {
442 throw FriendError.payloadEncodingFailed
443 }
444
445 try await syncEngine.enqueueFriendZonePing(
446 kind: .invite,
447 gameID: gameID,
448 gameTitle: gameTitle,
449 authorID: inviterAuthorID,
450 playerName: inviterName,
451 addressee: friendAuthorID,
452 friendZoneID: FriendZone.outboxZoneID(pairKey: pairKey, friendAuthorID: friendAuthorID),
453 friendZoneScope: .shared,
454 payload: encoded,
455 rollbackParticipantOnFailure: rollbackParticipantOnFailure,
456 waitForServerConfirmation: true
457 )
458 }
459
460
461
462
463
464
465
466 func sendDecline(
467 toInviterAuthorID inviterAuthorID: String,
468 gameID: UUID,
469 gameTitle: String,
470 declinerAuthorID: String,
471 declinerName: String
472 ) async throws {
473 let ctx = persistence.viewContext
474 let req = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
475 req.predicate = NSPredicate(format: "authorID == %@", inviterAuthorID)
476 req.fetchLimit = 1
477 guard let friend = try ctx.fetch(req).first else {
478 throw FriendError.friendNotFound
479 }
480 guard !friend.isBlocked else { throw FriendError.friendBlocked }
481 guard let pairKey = friend.pairKey else { throw FriendError.friendNotFound }
482 try await ensureOutboxAccepted(pairKey: pairKey, friendAuthorID: inviterAuthorID)
483
484 try await syncEngine.enqueueFriendZonePing(
485 kind: .decline,
486 gameID: gameID,
487 gameTitle: gameTitle,
488 authorID: declinerAuthorID,
489 playerName: declinerName,
490 addressee: inviterAuthorID,
491 friendZoneID: FriendZone.outboxZoneID(pairKey: pairKey, friendAuthorID: inviterAuthorID),
492 friendZoneScope: .shared
493 )
494 }
495
496
497
498
499
500
501
502 func deleteFriendZonePing(fromFriendAuthorID friendAuthorID: String, recordName: String) async {
503 let ctx = persistence.viewContext
504 let req = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
505 req.predicate = NSPredicate(format: "authorID == %@", friendAuthorID)
506 req.fetchLimit = 1
507 guard let friend = try? ctx.fetch(req).first,
508 let pairKey = friend.pairKey
509 else { return }
510
511
512
513
514 await syncEngine.deletePing(
515 recordName: recordName,
516 zoneID: FriendZone.inboxZoneID(pairKey: pairKey),
517 databaseScope: .private
518 )
519 }
520
521
522
523
524
525
526
527
528
529
530 func block(friendAuthorID: String) async throws {
531 try await setBlocked(friendAuthorID: friendAuthorID, blocked: true)
532 }
533
534
535
536
537 func unblock(friendAuthorID: String) async throws {
538 try await setBlocked(friendAuthorID: friendAuthorID, blocked: false)
539 }
540
541 private func setBlocked(friendAuthorID: String, blocked: Bool) async throws {
542 let ctx = persistence.viewContext
543 let req = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
544 req.predicate = NSPredicate(format: "authorID == %@", friendAuthorID)
545 req.fetchLimit = 1
546 guard let friend = try ctx.fetch(req).first,
547 let pairKey = friend.pairKey
548 else { return }
549 let version = friend.blockVersion + 1
550
551 let label = blocked ? "block friend" : "unblock friend"
552 syncMonitor?.recordStart(label)
553 do {
554 try await setInboxParticipantPermission(
555 friendAuthorID: friendAuthorID,
556 pairKey: pairKey,
557 permission: blocked ? .readOnly : .readWrite
558 )
559 friend.isBlocked = blocked
560 friend.blockVersion = version
561 try ctx.save()
562
563
564
565
566
567 await syncEngine.enqueueDecision(
568 kind: RecordSerializer.blockDecisionKind,
569 key: friendAuthorID,
570 payload: blocked ? "1" : "0",
571 version: version
572 )
573 syncMonitor?.recordSuccess(label)
574 } catch {
575 syncMonitor?.recordError(label, error)
576 throw error
577 }
578 }
579
580
581
582
583 private func setInboxParticipantPermission(
584 friendAuthorID: String,
585 pairKey: String,
586 permission: CKShare.ParticipantPermission
587 ) async throws {
588 let zoneID = FriendZone.inboxZoneID(pairKey: pairKey)
589 let shareID = CKRecord.ID(recordName: CKRecordNameZoneWideShare, zoneID: zoneID)
590 let database = container.privateCloudDatabase
591 guard let share = try await database.record(for: shareID) as? CKShare else {
592 throw FriendError.invalidShareRecord
593 }
594 guard let participant = share.participants.first(where: {
595 $0.userIdentity.userRecordID?.recordName == friendAuthorID
596 }) else {
597 throw FriendError.participantNotFound
598 }
599 participant.permission = permission
600 _ = try await database.save(share)
601 }
602
603
604
605
606
607 func ensureOutboxReady(friendAuthorID: String) async throws {
608 let ctx = persistence.viewContext
609 let req = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
610 req.predicate = NSPredicate(format: "authorID == %@", friendAuthorID)
611 req.fetchLimit = 1
612 guard let friend = try ctx.fetch(req).first else {
613 throw FriendError.friendNotFound
614 }
615 guard !friend.isBlocked else { throw FriendError.friendBlocked }
616 guard let pairKey = friend.pairKey else { throw FriendError.friendNotFound }
617 try await ensureOutboxAccepted(pairKey: pairKey, friendAuthorID: friendAuthorID)
618 }
619
620 private func ensureOutboxAccepted(pairKey: String, friendAuthorID: String) async throws {
621 if FriendZone.outboxAccepted(pairKey: pairKey) { return }
622 let zoneID = FriendZone.outboxZoneID(pairKey: pairKey, friendAuthorID: friendAuthorID)
623 if try await zoneExists(zoneID, in: container.sharedCloudDatabase) {
624 FriendZone.markOutboxAccepted(pairKey: pairKey)
625 return
626 }
627 throw FriendError.friendshipNotReady
628 }
629
630
631
632
633
634
635
636
637
638
639 func setNickname(friendAuthorID: String, nickname: String) async throws {
640 let ctx = persistence.viewContext
641 let req = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
642 req.predicate = NSPredicate(format: "authorID == %@", friendAuthorID)
643 req.fetchLimit = 1
644 guard let friend = try ctx.fetch(req).first else {
645 throw FriendError.friendNotFound
646 }
647 let trimmed = nickname.trimmingCharacters(in: .whitespacesAndNewlines)
648 let version = friend.nicknameVersion + 1
649 friend.nickname = trimmed.isEmpty ? nil : trimmed
650 friend.nicknameVersion = version
651 try ctx.save()
652 FriendEntity.rebuildNicknameDirectory(in: ctx)
653
654
655 await syncEngine.enqueueDecision(
656 kind: RecordSerializer.nicknameDecisionKind,
657 key: friendAuthorID,
658 payload: trimmed.isEmpty ? nil : trimmed,
659 version: version
660 )
661 }
662
663
664
665 private func createZone(_ zoneID: CKRecordZone.ID) async throws {
666 try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
667 let op = CKModifyRecordZonesOperation(
668 recordZonesToSave: [CKRecordZone(zoneID: zoneID)],
669 recordZoneIDsToDelete: nil
670 )
671 op.qualityOfService = .userInitiated
672 op.modifyRecordZonesResultBlock = { result in cont.resume(with: result) }
673 self.container.privateCloudDatabase.add(op)
674 }
675 }
676
677 private func saveZoneWideShare(
678 zoneID: CKRecordZone.ID,
679 addingParticipant remoteAuthorID: String
680 ) async throws -> CKShare {
681 let share = CKShare(recordZoneID: zoneID)
682 share.publicPermission = .none
683 let participant = try await fetchParticipant(forUserRecordName: remoteAuthorID)
684 participant.permission = .readWrite
685 share.addParticipant(participant)
686 let saved = try await container.privateCloudDatabase.save(share)
687 guard let savedShare = saved as? CKShare else {
688 throw FriendError.invalidShareRecord
689 }
690 return savedShare
691 }
692
693
694
695
696 private func existingZoneWideShare(
697 zoneID: CKRecordZone.ID
698 ) async throws -> CKShare? {
699 let shareID = CKRecord.ID(
700 recordName: CKRecordNameZoneWideShare,
701 zoneID: zoneID
702 )
703 do {
704 let record = try await container.privateCloudDatabase.record(for: shareID)
705 return record as? CKShare
706 } catch let error as CKError
707 where error.code == .unknownItem || error.code == .zoneNotFound {
708 return nil
709 }
710 }
711
712 private func zoneExists(_ zoneID: CKRecordZone.ID, in database: CKDatabase) async throws -> Bool {
713 try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Bool, Error>) in
714 var exists = false
715 var perZoneError: Error?
716 let op = CKFetchRecordZonesOperation(recordZoneIDs: [zoneID])
717 op.qualityOfService = .userInitiated
718 op.perRecordZoneResultBlock = { _, result in
719 switch result {
720 case .success:
721 exists = true
722 case .failure(let error as CKError)
723 where error.code == .zoneNotFound || error.code == .unknownItem:
724 exists = false
725 case .failure(let error):
726 perZoneError = error
727 }
728 }
729 op.fetchRecordZonesResultBlock = { result in
730 switch result {
731 case .success:
732 if let perZoneError {
733 cont.resume(throwing: perZoneError)
734 } else {
735 cont.resume(returning: exists)
736 }
737 case .failure(let error as CKError)
738 where error.code == .zoneNotFound || error.code == .unknownItem:
739 cont.resume(returning: false)
740 case .failure(let error):
741 cont.resume(throwing: error)
742 }
743 }
744 database.add(op)
745 }
746 }
747
748 private func fetchParticipant(
749 forUserRecordName recordName: String
750 ) async throws -> CKShare.Participant {
751 let lookup = CKUserIdentity.LookupInfo(
752 userRecordID: CKRecord.ID(recordName: recordName)
753 )
754 return try await withCheckedThrowingContinuation { cont in
755 var found: CKShare.Participant?
756 let op = CKFetchShareParticipantsOperation(userIdentityLookupInfos: [lookup])
757 op.perShareParticipantResultBlock = { _, result in
758 if case .success(let participant) = result { found = participant }
759 }
760 op.fetchShareParticipantsResultBlock = { result in
761 switch result {
762 case .success:
763 if let found {
764 cont.resume(returning: found)
765 } else {
766 cont.resume(throwing: FriendError.participantNotFound)
767 }
768 case .failure(let error):
769 cont.resume(throwing: error)
770 }
771 }
772 self.container.add(op)
773 }
774 }
775
776 private func fetchShareMetadata(url: URL) async throws -> CKShare.Metadata {
777 try await withCheckedThrowingContinuation { cont in
778 var metadata: CKShare.Metadata?
779 let op = CKFetchShareMetadataOperation(shareURLs: [url])
780 op.shouldFetchRootRecord = false
781 op.perShareMetadataResultBlock = { _, result in
782 if case .success(let m) = result { metadata = m }
783 }
784 op.fetchShareMetadataResultBlock = { result in
785 switch result {
786 case .success:
787 if let metadata {
788 cont.resume(returning: metadata)
789 } else {
790 cont.resume(throwing: FriendError.invalidShareRecord)
791 }
792 case .failure(let error):
793 cont.resume(throwing: error)
794 }
795 }
796 self.container.add(op)
797 }
798 }
799
800 private func accept(_ metadata: CKShare.Metadata) async throws {
801 try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
802 let op = CKAcceptSharesOperation(shareMetadatas: [metadata])
803 op.acceptSharesResultBlock = { result in cont.resume(with: result) }
804 self.container.add(op)
805 }
806 }
807
808
809
810
811
812
813
814
815
816
817 private func persistFriend(authorID: String, pairKey: String) {
818 let ctx = persistence.viewContext
819 let req = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
820 req.predicate = NSPredicate(format: "pairKey == %@", pairKey)
821 req.fetchLimit = 1
822 let entity = (try? ctx.fetch(req).first) ?? FriendEntity(context: ctx)
823 entity.authorID = authorID
824 entity.pairKey = pairKey
825 if entity.createdAt == nil { entity.createdAt = Date() }
826 do {
827 try ctx.save()
828 Task { [weak self] in
829 await self?.applyAccountNicknameDecisionIfPresent(for: authorID)
830 }
831 } catch {
832 eventLog?.note("FriendController: persistFriend save failed — \(error)", level: "error")
833 }
834 }
835
836
837
838
839
840
841 func applyAccountNicknameDecisionIfPresent(for friendAuthorID: String) async {
842 let recordName = RecordSerializer.decisionRecordName(
843 kind: RecordSerializer.nicknameDecisionKind,
844 key: friendAuthorID
845 )
846 let recordID = CKRecord.ID(
847 recordName: recordName,
848 zoneID: RecordSerializer.accountZoneID
849 )
850 do {
851 let record = try await fetchAccountDecisionRecord(recordID)
852 let ctx = persistence.viewContext
853 let wrote = RecordSerializer.applyDecisionRecord(
854 record,
855 to: ctx,
856 localAuthorID: nil,
857 databaseScope: .private
858 )
859 if wrote {
860 try ctx.save()
861 FriendEntity.rebuildNicknameDirectory(in: ctx)
862 eventLog?.note(
863 "FriendController: replayed nickname decision \(recordName)",
864 level: "info"
865 )
866 }
867 } catch let error as CKError
868 where error.code == .unknownItem || error.code == .zoneNotFound {
869
870 } catch {
871 eventLog?.note(
872 "FriendController: nickname decision replay failed for \(friendAuthorID) — \(error)",
873 level: "error"
874 )
875 }
876 }
877}
878
879extension FriendController.FriendError: LocalizedError {
880 var errorDescription: String? {
881 switch self {
882 case .invalidShareRecord:
883 return "The crossmate record in iCloud is invalid."
884 case .missingShareURL, .missingShareURLInPayload:
885 return "The crossmate share link is missing."
886 case .participantNotFound:
887 return "That player could not be found in iCloud."
888 case .friendNotFound:
889 return "That Crossmate is not available yet."
890 case .friendBlocked:
891 return "That Crossmate is blocked."
892 case .friendshipNotReady:
893 return "This Crossmate is still syncing. Try again in a moment."
894 case .payloadEncodingFailed:
895 return "The invitation could not be prepared."
896 }
897 }
898}