From 922efb1b9739f60acf10aead6fc7bab8ffb22bac Mon Sep 17 00:00:00 2001 From: Sarah Wolff Date: Thu, 9 Jul 2026 16:49:05 -0400 Subject: [PATCH] feat(settings): add iCloud controls --- Piperly.xcodeproj/project.pbxproj | 12 + Piperly/App/ContentView.swift | 1 + Piperly/App/PiperlyApp.swift | 41 ++- .../Services/Sync/CloudKitLibrarySync.swift | 170 ++++++++-- .../Services/Sync/ICloudSyncController.swift | 234 +++++++++++++ Piperly/Services/Sync/LibrarySyncing.swift | 4 + Piperly/Services/Sync/SyncStatus.swift | 10 + .../Settings/ICloudSyncSettingsView.swift | 317 ++++++++++++++++++ Piperly/Views/Settings/SettingsView.swift | 37 +- PiperlyTests/ICloudSettingsTests.swift | 101 ++++++ PiperlyUITests/PiperlyUITests.swift | 20 ++ docs/app-store-privacy-review.md | 28 +- docs/icloud-release-checklist.md | 87 +++++ docs/testflight-release-checklist.md | 4 + 14 files changed, 1016 insertions(+), 50 deletions(-) create mode 100644 Piperly/Services/Sync/ICloudSyncController.swift create mode 100644 Piperly/Views/Settings/ICloudSyncSettingsView.swift create mode 100644 PiperlyTests/ICloudSettingsTests.swift create mode 100644 docs/icloud-release-checklist.md diff --git a/Piperly.xcodeproj/project.pbxproj b/Piperly.xcodeproj/project.pbxproj index 02b14f6..fbbcf59 100644 --- a/Piperly.xcodeproj/project.pbxproj +++ b/Piperly.xcodeproj/project.pbxproj @@ -35,7 +35,9 @@ 6C211085478661C47382156D /* BookmarkListSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2A1B958B2C979E3FC7F5F17 /* BookmarkListSheet.swift */; }; 73ACA44C6478B51A602B48B4 /* word-tap.js in Resources */ = {isa = PBXBuildFile; fileRef = AEC8DDABC8527ECA9066D42E /* word-tap.js */; }; 7B61C8E28DA7A9C27B7B27D6 /* reader-theme.css in Resources */ = {isa = PBXBuildFile; fileRef = 219B546B88E956F5EC6324D7 /* reader-theme.css */; }; + 7E157E48ADD1E43C562C329F /* ICloudSyncSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 300C9BECAE99B3F67325BF48 /* ICloudSyncSettingsView.swift */; }; 80F2409594CBAF3AA74C2614 /* Voice.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBF9B6B19370415EA2352127 /* Voice.swift */; }; + 827FE5E3F83B6832BE3CA3EE /* ICloudSettingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0726ED52E3805394C07CBDB3 /* ICloudSettingsTests.swift */; }; 876B3E27B8C741FF25C8D629 /* ImportButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 907A4ACDFF28240D2A04EC58 /* ImportButton.swift */; }; 8BD901E5E3524F619CF71CF2 /* ReadingState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DB2CC0ED8AAE37072017ABF /* ReadingState.swift */; }; 96A0782B38BA02C7827B1F6F /* Typography.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0B5EA42469618622432905D /* Typography.swift */; }; @@ -50,6 +52,7 @@ C8CD69CC9A21D1069657FB65 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 456BD662A32FF2E09E8B91CA /* Assets.xcassets */; }; C8EB86567BED41A31D9493EB /* Colors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32263DACC627AF31FFB42A6F /* Colors.swift */; }; D08A7543219A4B94086FC580 /* SyncStateStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93B5EEAF793B1FBB4652973E /* SyncStateStore.swift */; }; + D09253F67DC62099492F3C8F /* ICloudSyncController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D5B324587C00013C076C03E /* ICloudSyncController.swift */; }; D70FB9ABBE67AD59491D9F22 /* ReaderNavigator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E04B476A4331F7545247076 /* ReaderNavigator.swift */; }; DC10B557D03A8F34EB5681B6 /* ReadiumShared in Frameworks */ = {isa = PBXBuildFile; productRef = FB84F84F12F294A465FEFEB0 /* ReadiumShared */; }; DF716393D2AE9BE536866564 /* BookAssetStaging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EBA4D5ED091891FB10D3B5C /* BookAssetStaging.swift */; }; @@ -80,6 +83,7 @@ /* Begin PBXFileReference section */ 020FF465ED5DAE55F3F23078 /* BookCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BookCard.swift; sourceTree = ""; }; 0575D688D631F115AF497590 /* PiperlyApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PiperlyApp.swift; sourceTree = ""; }; + 0726ED52E3805394C07CBDB3 /* ICloudSettingsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ICloudSettingsTests.swift; sourceTree = ""; }; 07DB7B7BEB14F0757464F4FD /* ReaderProfile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReaderProfile.swift; sourceTree = ""; }; 0B48C597C42056AFD320ACB1 /* ReaderTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReaderTheme.swift; sourceTree = ""; }; 0EBA4D5ED091891FB10D3B5C /* BookAssetStaging.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BookAssetStaging.swift; sourceTree = ""; }; @@ -91,6 +95,7 @@ 1E04B476A4331F7545247076 /* ReaderNavigator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReaderNavigator.swift; sourceTree = ""; }; 2051654FEEB7BC3200F4830D /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = ""; }; 219B546B88E956F5EC6324D7 /* reader-theme.css */ = {isa = PBXFileReference; lastKnownFileType = text.css; path = "reader-theme.css"; sourceTree = ""; }; + 300C9BECAE99B3F67325BF48 /* ICloudSyncSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ICloudSyncSettingsView.swift; sourceTree = ""; }; 32263DACC627AF31FFB42A6F /* Colors.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Colors.swift; sourceTree = ""; }; 37668E902B9B08AB7690046F /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; 3F0C8334C49EE044ECDF320F /* VoiceSetupSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceSetupSheet.swift; sourceTree = ""; }; @@ -99,6 +104,7 @@ 505AE8E196D11F1F4CEC38BA /* Book.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Book.swift; sourceTree = ""; }; 5E9F47EB6E2EDF5E9E04B49B /* Piperly.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = Piperly.app; sourceTree = BUILT_PRODUCTS_DIR; }; 67C736D8D95AF555808BAB07 /* WordListSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WordListSheet.swift; sourceTree = ""; }; + 6D5B324587C00013C076C03E /* ICloudSyncController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ICloudSyncController.swift; sourceTree = ""; }; 6D67EDBA545BF502AADA33A5 /* LibraryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LibraryView.swift; sourceTree = ""; }; 79007FAFBAC9B7FCDF89D151 /* ReaderToolbar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReaderToolbar.swift; sourceTree = ""; }; 79209FD4DBEB0A7745E96BCA /* SyncStatus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SyncStatus.swift; sourceTree = ""; }; @@ -243,6 +249,7 @@ 73BD50056A415FA38530BC14 /* Settings */ = { isa = PBXGroup; children = ( + 300C9BECAE99B3F67325BF48 /* ICloudSyncSettingsView.swift */, CFADC6967714E5F36F446A79 /* ReadingSettingsSheet.swift */, 2051654FEEB7BC3200F4830D /* SettingsView.swift */, 0F33AE51FAB9D371EE0F1F67 /* VoicePickerSheet.swift */, @@ -279,6 +286,7 @@ children = ( 0EBA4D5ED091891FB10D3B5C /* BookAssetStaging.swift */, 90EA411DA826F78E32B4DA71 /* CloudKitLibrarySync.swift */, + 6D5B324587C00013C076C03E /* ICloudSyncController.swift */, 144FD302072287A2F625E295 /* LibraryConflictResolver.swift */, C236C568C7927FEA271E2B08 /* LibraryRecord.swift */, 1D2F068169DAE06D75030A39 /* LibraryRecordCodec.swift */, @@ -307,6 +315,7 @@ children = ( E7864762CD3DC06CFF339B7C /* BookAssetTests.swift */, B342D7030508E0F3805E6C75 /* CloudKitSyncTests.swift */, + 0726ED52E3805394C07CBDB3 /* ICloudSettingsTests.swift */, CEE3796984A778CA18D6B83F /* PiperlyTests.swift */, ); path = PiperlyTests; @@ -501,6 +510,7 @@ files = ( 5EF464C9DDE293B2B3A1D360 /* BookAssetTests.swift in Sources */, B24843B385E539F6569F539E /* CloudKitSyncTests.swift in Sources */, + 827FE5E3F83B6832BE3CA3EE /* ICloudSettingsTests.swift in Sources */, 3AC16D4D89F0CBC50AC41C91 /* PiperlyTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -526,6 +536,8 @@ AA8EF4C5E8B7096587E9AC6C /* CloudKitLibrarySync.swift in Sources */, C8EB86567BED41A31D9493EB /* Colors.swift in Sources */, 06D163B795C07C40FDD4C639 /* ContentView.swift in Sources */, + D09253F67DC62099492F3C8F /* ICloudSyncController.swift in Sources */, + 7E157E48ADD1E43C562C329F /* ICloudSyncSettingsView.swift in Sources */, 876B3E27B8C741FF25C8D629 /* ImportButton.swift in Sources */, AEB761A1B95187D81344E32E /* LibraryConflictResolver.swift in Sources */, 4CB3CB697D6FC2D125D0CADC /* LibraryRecord.swift in Sources */, diff --git a/Piperly/App/ContentView.swift b/Piperly/App/ContentView.swift index 82aa7d3..b3789af 100644 --- a/Piperly/App/ContentView.swift +++ b/Piperly/App/ContentView.swift @@ -71,6 +71,7 @@ struct ContentView: View { .font(.title2) .foregroundStyle(Piperly.Colors.accent) } + .accessibilityLabel("Settings") if selectedTab == .library { Button { diff --git a/Piperly/App/PiperlyApp.swift b/Piperly/App/PiperlyApp.swift index 9b56a41..7f6db95 100644 --- a/Piperly/App/PiperlyApp.swift +++ b/Piperly/App/PiperlyApp.swift @@ -19,6 +19,7 @@ import SwiftUI @main struct PiperlyApp: App { @StateObject private var bookStore: BookStore + @StateObject private var iCloudSyncController: ICloudSyncController private let ttsEngine = TTSEngine() @State private var showVoiceSetup = false @Environment(\.scenePhase) private var scenePhase @@ -29,36 +30,34 @@ struct PiperlyApp: App { let store = BookStore(librarySync: router) _bookStore = StateObject(wrappedValue: store) - guard CloudKitLibrarySync.isEnabled() else { return } - Task { - guard let cloudSync = try? CloudKitLibrarySync( - enabled: true, - localSnapshotProvider: { [weak store] in - store?.librarySnapshotRecords() ?? [] - }, - localBookAssetProvider: { [weak store] book in - store?.localBookAssets(for: book) - }, - assetStagingURL: store.assetStagingURL, - remoteChangeHandler: { [weak store] changes, scope in - guard let store else { return .complete } - if scope.isCurrentAccount { - return router.applyingCurrentAccountChanges(scope: scope) { - store.applyRemoteChanges(changes) - } + _iCloudSyncController = StateObject(wrappedValue: ICloudSyncController( + router: router, + localSnapshotProvider: { [weak store] in + store?.librarySnapshotRecords() ?? [] + }, + localBookAssetProvider: { [weak store] book in + store?.localBookAssets(for: book) + }, + assetStagingURL: store.assetStagingURL, + remoteChangeHandler: { [weak store] changes, scope in + guard let store else { return .complete } + if scope.isCurrentAccount { + return router.applyingCurrentAccountChanges(scope: scope) { + store.applyRemoteChanges(changes) } - return store.applyRemoteChanges(changes) } - ) else { return } - await router.use(cloudSync) - } + return store.applyRemoteChanges(changes) + } + )) } var body: some Scene { WindowGroup { ContentView(ttsEngine: ttsEngine) .environmentObject(bookStore) + .environmentObject(iCloudSyncController) .task { + await iCloudSyncController.startIfEnabled() await bookStore.importSampleBooksIfNeeded() } .onChange(of: bookStore.selectedProfileID, initial: true) { diff --git a/Piperly/Services/Sync/CloudKitLibrarySync.swift b/Piperly/Services/Sync/CloudKitLibrarySync.swift index b21a0f0..0eb2fc7 100644 --- a/Piperly/Services/Sync/CloudKitLibrarySync.swift +++ b/Piperly/Services/Sync/CloudKitLibrarySync.swift @@ -13,6 +13,7 @@ actor CloudKitLibrarySync: LibrarySyncSink { ) -> RemoteApplicationResult typealias LocalSnapshotProvider = @MainActor @Sendable () -> [LibraryRecord] typealias LocalBookAssetProvider = @MainActor @Sendable (SyncedBook) -> BookAssetURLs? + typealias StatusHandler = @MainActor @Sendable (LibrarySyncStatus) -> Void static let containerIdentifier = "iCloud.com.piperly.app" static let enabledDefaultsKey = "piperly_icloud_sync_enabled" @@ -28,14 +29,29 @@ actor CloudKitLibrarySync: LibrarySyncSink { private let localBookAssetProvider: LocalBookAssetProvider private let assetStaging: BookAssetStaging private let automaticallySync: Bool + private let statusHandler: StatusHandler + private let activityToken = CloudSyncActivityToken() private var snapshot: SyncStateSnapshot private var engine: CKSyncEngine? + private var engineActivityToken: CloudSyncActivityToken? private var needsAccountConfirmation = false private var accountTransitionInProgress = false private var transitionAssetApplicationInProgress = false private var activeUploadAssets: [String: [String: BookAssetURLs]] = [:] private var assetRetryQueue = BookAssetRetryQueue() - private(set) var status: LibrarySyncStatus + private var isStopped = false + private var lifecycleGeneration = 0 + private(set) var status: LibrarySyncStatus { + didSet { + guard !isStopped, status != oldValue else { return } + let status = status + let activityToken = activityToken + Task { @MainActor [statusHandler] in + guard activityToken.isActive else { return } + statusHandler(status) + } + } + } init( enabled: Bool, @@ -45,6 +61,7 @@ actor CloudKitLibrarySync: LibrarySyncSink { localSnapshotProvider: @escaping LocalSnapshotProvider = { [] }, localBookAssetProvider: @escaping LocalBookAssetProvider = { _ in nil }, assetStagingURL: URL? = nil, + statusHandler: @escaping StatusHandler = { _ in }, remoteChangeHandler: @escaping RemoteChangeHandler ) throws { self.container = container @@ -66,6 +83,7 @@ actor CloudKitLibrarySync: LibrarySyncSink { } )) self.automaticallySync = automaticallySync + self.statusHandler = statusHandler status = enabled ? BookAssetSyncStatusResolver.status(for: snapshot.bookAssetFailures) : .disabled needsAccountConfirmation = enabled @@ -81,10 +99,14 @@ actor CloudKitLibrarySync: LibrarySyncSink { } private func prepareInitialAccount() async { + let generation = lifecycleGeneration + guard isActive(generation) else { return } guard let currentUser = try? await container.userRecordID() else { + guard isActive(generation) else { return } status = .blocked(.accountUnavailable) return } + guard isActive(generation) else { return } if SyncCurrentAccountOperations.hasOperations(snapshot: snapshot) { SyncCurrentAccountOperations.reQuarantine(snapshot: &snapshot) snapshot.confirmedAccountRecordName = nil @@ -100,12 +122,13 @@ actor CloudKitLibrarySync: LibrarySyncSink { needsAccountConfirmation = false persistSnapshot() await applyDeferredRemoteChanges() + guard isActive(generation) else { return } start() await resumeDurableAssetRetries() } func start(automaticallySync override: Bool? = nil, restorePending: Bool = true) { - guard status != .disabled, engine == nil, !needsAccountConfirmation else { return } + guard !isStopped, status != .disabled, engine == nil, !needsAccountConfirmation else { return } Task { @MainActor in UIApplication.shared.registerForRemoteNotifications() } @@ -117,11 +140,14 @@ actor CloudKitLibrarySync: LibrarySyncSink { configuration.automaticallySync = override ?? automaticallySync configuration.subscriptionID = "PiperlyLibrary-private" let newEngine = CKSyncEngine(configuration) + engineActivityToken?.invalidate() + engineActivityToken = CloudSyncActivityToken() engine = newEngine if restorePending { restorePendingChanges(to: newEngine) } } func acceptSave(_ record: LibraryRecord, scope: RemoteApplicationScope) async throws { + guard !isStopped else { throw SyncLifecycleError.stopped } let reference = record.reference if scope.isCurrentAccount { guard let accountRecordName = scope.accountRecordName, @@ -160,6 +186,7 @@ actor CloudKitLibrarySync: LibrarySyncSink { _ reference: LibraryRecordReference, scope: RemoteApplicationScope ) async throws { + guard !isStopped else { throw SyncLifecycleError.stopped } if scope.isCurrentAccount { guard let accountRecordName = scope.accountRecordName, let transitionGeneration = scope.transitionGeneration else { return } @@ -197,12 +224,46 @@ actor CloudKitLibrarySync: LibrarySyncSink { } func syncNow() async throws { + let generation = lifecycleGeneration + guard isActive(generation) else { throw SyncLifecycleError.stopped } guard let engine = activeEngine() else { return } try await engine.fetchChanges(CKSyncEngine.FetchChangesOptions()) + guard isActive(generation), engine === self.engine else { throw SyncLifecycleError.stopped } try await engine.sendChanges(CKSyncEngine.SendChangesOptions()) + guard isActive(generation), engine === self.engine else { throw SyncLifecycleError.stopped } + } + + func stop() async { + guard !isStopped else { return } + isStopped = true + activityToken.invalidate() + lifecycleGeneration += 1 + let engineToStop = detachEngine() + status = .disabled + if let engineToStop { await engineToStop.cancelOperations() } + cleanupActiveUploads() + } + + func currentStatus() -> LibrarySyncStatus { + status + } + + func accountConfirmationContext() -> SyncAccountConfirmationContext { + let hasPendingWork = !snapshot.quarantinedSaves.isEmpty + || !snapshot.quarantinedDeletes.isEmpty + || SyncCurrentAccountOperations.hasOperations(snapshot: snapshot) + if snapshot.didSeedExistingLibrary || snapshot.confirmedAccountRecordName != nil { + return hasPendingWork ? .accountChangedWithPendingWork : .accountChanged + } + return .firstEnable + } + + func failedAssetIdentities() -> Set { + Set(snapshot.bookAssetFailures.keys).union(snapshot.assetDownloadRetryRecordNames) } func requestBookAssets(contentIdentity: String) async { + guard !isStopped else { return } snapshot.recordAssetFailure( .retryable, recordName: contentIdentity, @@ -216,7 +277,7 @@ actor CloudKitLibrarySync: LibrarySyncSink { private func drainAssetRetryQueue() async { defer { assetRetryQueue.finish() } while !assetRetryQueue.queued.isEmpty { - guard !needsAccountConfirmation, !accountTransitionInProgress else { return } + guard !isStopped, !needsAccountConfirmation, !accountTransitionInProgress else { return } let requested = assetRetryQueue.takeNext() await performAssetRetry(for: requested) } @@ -231,44 +292,49 @@ actor CloudKitLibrarySync: LibrarySyncSink { } private func performAssetRetry(for identities: Set) async { + let lifecycle = lifecycleGeneration guard !identities.isEmpty, + isActive(lifecycle), !needsAccountConfirmation, !accountTransitionInProgress, let expectedAccount = snapshot.confirmedAccountRecordName else { return } let expectedGeneration = snapshot.accountTransitionGeneration - if let engine { await engine.cancelOperations() } - guard !needsAccountConfirmation, + let previousEngine = detachEngine() + if let previousEngine { await previousEngine.cancelOperations() } + guard isActive(lifecycle), + !needsAccountConfirmation, !accountTransitionInProgress, snapshot.confirmedAccountRecordName == expectedAccount, snapshot.accountTransitionGeneration == expectedGeneration else { return } cleanupActiveUploads() - engine = nil snapshot.engineState = nil persistSnapshot() start() guard let retryEngine = engine else { return } do { try await retryEngine.fetchChanges(CKSyncEngine.FetchChangesOptions()) + guard isActive(lifecycle), retryEngine === engine else { return } } catch { recordRetryError(error, identities: identities) return } guard retryAccountMatches(expectedAccount, generation: expectedGeneration) else { - if let engine { await engine.cancelOperations() } + let staleEngine = detachEngine() + if let staleEngine { await staleEngine.cancelOperations() } cleanupActiveUploads() - engine = nil return } do { try await retryEngine.sendChanges(CKSyncEngine.SendChangesOptions()) + guard isActive(lifecycle), retryEngine === engine else { return } } catch { recordRetryError(error, identities: identities) return } guard retryAccountMatches(expectedAccount, generation: expectedGeneration) else { - if let engine { await engine.cancelOperations() } + let staleEngine = detachEngine() + if let staleEngine { await staleEngine.cancelOperations() } cleanupActiveUploads() - engine = nil return } } @@ -304,16 +370,20 @@ actor CloudKitLibrarySync: LibrarySyncSink { } private func retryAccountMatches(_ accountRecordName: String, generation: Int) -> Bool { - !needsAccountConfirmation + !isStopped + && !needsAccountConfirmation && !accountTransitionInProgress && snapshot.confirmedAccountRecordName == accountRecordName && snapshot.accountTransitionGeneration == generation } func accountState() async -> SyncAccountState { - guard status != .disabled else { return .couldNotDetermine } + let lifecycle = lifecycleGeneration + guard isActive(lifecycle), status != .disabled else { return .couldNotDetermine } do { - switch try await container.accountStatus() { + let accountStatus = try await container.accountStatus() + guard isActive(lifecycle) else { return .couldNotDetermine } + switch accountStatus { case .available: return .available case .noAccount: @@ -333,7 +403,7 @@ actor CloudKitLibrarySync: LibrarySyncSink { } func confirmAccountChange(policy: AccountTransitionPolicy) async throws { - guard needsAccountConfirmation else { return } + guard !isStopped, needsAccountConfirmation else { return } do { let generation = beginAccountTransition() let currentUser = try await container.userRecordID() @@ -348,9 +418,9 @@ actor CloudKitLibrarySync: LibrarySyncSink { } try await fetchEngine.fetchChanges(CKSyncEngine.FetchChangesOptions()) try requireAccountTransition(generation) + _ = detachEngine() await fetchEngine.cancelOperations() try requireAccountTransition(generation) - engine = nil let firstVerification = try await container.userRecordID() try requireAccountTransition(generation) try SyncAccountTransitionValidator.validate( @@ -452,9 +522,9 @@ actor CloudKitLibrarySync: LibrarySyncSink { invalidateAccountTransition() return } - if let engine { Task { await engine.cancelOperations() } } + let staleEngine = detachEngine() + if let staleEngine { Task { await staleEngine.cancelOperations() } } cleanupActiveUploads() - engine = nil SyncAccountTransition.quarantine(snapshot: &snapshot) snapshot.confirmedAccountRecordName = nil needsAccountConfirmation = true @@ -462,11 +532,20 @@ actor CloudKitLibrarySync: LibrarySyncSink { } private func activeEngine() -> CKSyncEngine? { - guard status != .disabled, !needsAccountConfirmation, !accountTransitionInProgress else { return nil } + guard !isStopped, status != .disabled, + !needsAccountConfirmation, !accountTransitionInProgress else { return nil } if engine == nil { start() } return engine } + private func detachEngine() -> CKSyncEngine? { + let detached = engine + engine = nil + engineActivityToken?.invalidate() + engineActivityToken = nil + return detached + } + private func restorePendingChanges(to engine: CKSyncEngine) { engine.state.add(pendingDatabaseChanges: [.saveZone(CKRecordZone(zoneID: LibraryRecordCodec.zoneID))]) let saves = snapshot.pendingSaves.values.map { record in @@ -483,6 +562,7 @@ actor CloudKitLibrarySync: LibrarySyncSink { } private func persistSnapshot() { + guard !isStopped else { return } do { try stateStore.save(snapshot) } catch { @@ -491,6 +571,7 @@ actor CloudKitLibrarySync: LibrarySyncSink { } private func persistSnapshotOrThrow() throws { + guard !isStopped else { throw SyncLifecycleError.stopped } do { try stateStore.save(snapshot) } catch { @@ -499,6 +580,10 @@ actor CloudKitLibrarySync: LibrarySyncSink { } } + private func isActive(_ generation: Int) -> Bool { + !isStopped && lifecycleGeneration == generation + } + private func assetFailure(for error: Error) -> BookAssetTransferFailure { BookAssetFailureClassifier.classify(error) } @@ -636,6 +721,8 @@ actor CloudKitLibrarySync: LibrarySyncSink { } private func applyDeferredRemoteChanges() async { + let lifecycle = lifecycleGeneration + guard isActive(lifecycle) else { return } let assets = snapshot.pendingRemoteAssets let changes = snapshot.deferredRemoteDeletions.map(LibraryRemoteChange.delete) + snapshot.deferredRemoteRecords.values.map(LibraryRemoteChange.save) @@ -643,6 +730,7 @@ actor CloudKitLibrarySync: LibrarySyncSink { let result = changes.isEmpty ? RemoteApplicationResult.complete : await remoteChangeHandler(changes, .normal) + guard isActive(lifecycle) else { return } snapshot.deferredRemoteRecords = Dictionary( uniqueKeysWithValues: result.unresolvedRecords.map { ($0.reference.recordName, $0) } ) @@ -654,6 +742,7 @@ actor CloudKitLibrarySync: LibrarySyncSink { transitionGeneration: snapshot.accountTransitionGeneration, scope: .normal ) + guard isActive(lifecycle) else { return } applyAssetOutcomes(outcomes, deliveredAssets: assets) } persistSnapshot() @@ -662,6 +751,9 @@ actor CloudKitLibrarySync: LibrarySyncSink { extension CloudKitLibrarySync: CKSyncEngineDelegate { func handleEvent(_ event: CKSyncEngine.Event, syncEngine: CKSyncEngine) async { + let lifecycle = lifecycleGeneration + guard isActive(lifecycle), syncEngine === engine, + engineActivityToken?.isActive == true else { return } switch event { case .stateUpdate(let update): snapshot.engineState = update.stateSerialization @@ -673,7 +765,7 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { case .accountChange: break case .fetchedRecordZoneChanges(let changes): - await handleFetched(changes) + await handleFetched(changes, lifecycle: lifecycle) case .sentRecordZoneChanges(let changes): handleSent(changes, syncEngine: syncEngine) case .sentDatabaseChanges(let changes): @@ -701,7 +793,10 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { _ context: CKSyncEngine.SendChangesContext, syncEngine: CKSyncEngine ) async -> CKSyncEngine.RecordZoneChangeBatch? { - guard !needsAccountConfirmation, !accountTransitionInProgress else { return nil } + let lifecycle = lifecycleGeneration + guard isActive(lifecycle), syncEngine === engine, + engineActivityToken?.isActive == true, + !needsAccountConfirmation, !accountTransitionInProgress else { return nil } let pending = syncEngine.state.pendingRecordZoneChanges.filter { context.options.scope.contains($0) } let pendingSaveNames = Set(pending.compactMap { change -> String? in guard case .saveRecord(let recordID) = change else { return nil } @@ -713,9 +808,11 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { for (recordName, record) in records where pendingSaveNames.contains(recordName) { guard case .book(let book) = record else { continue } guard let source = await localBookAssetProvider(book), source.epub != nil else { + guard isActive(lifecycle), syncEngine === engine else { return nil } recordAssetFailure(.missingLocalData, recordName: recordName) continue } + guard isActive(lifecycle), syncEngine === engine else { return nil } do { let staged = try assetStaging.stageUpload(source, recordName: recordName) do { @@ -734,7 +831,9 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { } persistSnapshot() let stagedAssets = assetsByRecordName + guard let engineActivityToken, engineActivityToken.isActive else { return nil } return await CKSyncEngine.RecordZoneChangeBatch(pendingChanges: pending) { recordID in + guard engineActivityToken.isActive else { return nil } guard let record = records[recordID.recordName] else { return nil } if case .book = record, stagedAssets[recordID.recordName]?.epub == nil { return nil } return try? LibraryRecordCodec.encode( @@ -745,8 +844,11 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { } } - private func handleFetched(_ event: CKSyncEngine.Event.FetchedRecordZoneChanges) async { - guard !needsAccountConfirmation else { return } + private func handleFetched( + _ event: CKSyncEngine.Event.FetchedRecordZoneChanges, + lifecycle: Int + ) async { + guard isActive(lifecycle), !needsAccountConfirmation else { return } if accountTransitionInProgress { stageFetchedForAccountTransition(event) persistSnapshot() @@ -833,6 +935,7 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { let result = metadataChanges.isEmpty ? RemoteApplicationResult.complete : await remoteChangeHandler(metadataChanges, .normal) + guard isActive(lifecycle) else { return } snapshot.deferredRemoteRecords = Dictionary( uniqueKeysWithValues: result.unresolvedRecords.map { ($0.reference.recordName, $0) } ) @@ -844,6 +947,7 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { transitionGeneration: snapshot.accountTransitionGeneration, scope: .normal ) + guard isActive(lifecycle) else { return } applyAssetOutcomes(assetOutcomes, deliveredAssets: deliveredAssetFiles) } } @@ -1001,6 +1105,7 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { } private func apply(error: CKError) { + guard !isStopped else { return } let failure = CloudKitErrorClassifier.classify(error) if case .retryable(let retryAfter) = failure { status = .waitingToRetry(retryAfter) @@ -1028,7 +1133,7 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { snapshot.accountTransitionRemoteAssets = [:] cleanupActiveUploads() snapshot.accountTransitionGeneration += 1 - engine = nil + _ = detachEngine() snapshot.engineState = nil snapshot.systemFields = [:] snapshot.accountTransitionRemoteRecords = [:] @@ -1042,6 +1147,7 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { } private func requireAccountTransition(_ generation: Int) throws { + guard !isStopped else { throw SyncLifecycleError.stopped } try SyncAccountTransitionValidator.validateGeneration( expected: generation, current: snapshot.accountTransitionGeneration, @@ -1145,7 +1251,8 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { private func failAccountTransitionIfActive() { guard accountTransitionInProgress else { return } - if let engine { Task { await engine.cancelOperations() } } + let staleEngine = detachEngine() + if let staleEngine { Task { await staleEngine.cancelOperations() } } invalidateAccountTransition() persistSnapshot() } @@ -1158,7 +1265,7 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { } cleanupActiveUploads() snapshot.accountTransitionGeneration += 1 - engine = nil + _ = detachEngine() snapshot.engineState = nil snapshot.systemFields = [:] snapshot.confirmedAccountRecordName = nil @@ -1179,6 +1286,19 @@ extension CloudKitLibrarySync: CKSyncEngineDelegate { } } +final class CloudSyncActivityToken: @unchecked Sendable { + private let lock = NSLock() + private var active = true + + var isActive: Bool { + lock.withLock { active } + } + + func invalidate() { + lock.withLock { active = false } + } +} + enum SyncAccountTransitionError: Error, Equatable { case accountChangedDuringConfirmation } diff --git a/Piperly/Services/Sync/ICloudSyncController.swift b/Piperly/Services/Sync/ICloudSyncController.swift new file mode 100644 index 0000000..e40c7b9 --- /dev/null +++ b/Piperly/Services/Sync/ICloudSyncController.swift @@ -0,0 +1,234 @@ +// Piperly - iPad ebook reader for kids +// Copyright (C) 2026 Interactive Buffoonery + +import Combine +import Foundation + +@MainActor +final class ICloudSyncController: ObservableObject { + @Published private(set) var status: LibrarySyncStatus + @Published private(set) var confirmationContext: SyncAccountConfirmationContext? + @Published private(set) var failedAssetIdentities: Set = [] + @Published private(set) var isWorking = false + @Published private(set) var isEnabled: Bool + @Published var errorMessage: String? + + private let router: LibrarySyncRouter + private let defaults: UserDefaults + private let localSnapshotProvider: CloudKitLibrarySync.LocalSnapshotProvider + private let localBookAssetProvider: CloudKitLibrarySync.LocalBookAssetProvider + private let assetStagingURL: URL + private let remoteChangeHandler: CloudKitLibrarySync.RemoteChangeHandler + private var cloudSync: CloudKitLibrarySync? + private var lifecycleToken: ICloudSyncLifecycleToken? + + init( + router: LibrarySyncRouter, + defaults: UserDefaults = .standard, + localSnapshotProvider: @escaping CloudKitLibrarySync.LocalSnapshotProvider, + localBookAssetProvider: @escaping CloudKitLibrarySync.LocalBookAssetProvider, + assetStagingURL: URL, + remoteChangeHandler: @escaping CloudKitLibrarySync.RemoteChangeHandler + ) { + self.router = router + self.defaults = defaults + self.localSnapshotProvider = localSnapshotProvider + self.localBookAssetProvider = localBookAssetProvider + self.assetStagingURL = assetStagingURL + self.remoteChangeHandler = remoteChangeHandler + let isEnabled = CloudKitLibrarySync.isEnabled(in: defaults) + self.isEnabled = isEnabled + status = isEnabled ? .idle : .disabled + } + + func startIfEnabled() async { + guard cloudSync == nil, CloudKitLibrarySync.isEnabled(in: defaults) else { return } + await startSync() + } + + func prepareEnable() async { + errorMessage = nil + isWorking = true + defer { isWorking = false } + do { + await stopCurrentSync() + let (sync, token) = try makeSync() + cloudSync = sync + await router.use(sync) + guard isCurrent(sync, token: token) else { return } + let accountState = await sync.accountState() + guard isCurrent(sync, token: token) else { return } + switch accountState { + case .available: + confirmationContext = await sync.accountConfirmationContext() + status = .accountConfirmationRequired + case .noAccount: + status = .blocked(.accountUnavailable) + errorMessage = "Sign in to iCloud in iPad Settings, then try again." + case .restricted: + status = .blocked(.accountRestricted) + errorMessage = "iCloud is restricted on this iPad. Check Screen Time or account settings." + case .temporarilyUnavailable, .couldNotDetermine: + status = .waitingToRetry(nil) + errorMessage = "Piperly could not reach iCloud. Check the connection and try again." + } + } catch { + status = .blocked(.unknown(code: (error as NSError).code)) + errorMessage = "Piperly could not prepare iCloud sync. Your local library is unchanged." + } + } + + func confirmEnable(policy: AccountTransitionPolicy) async { + guard let cloudSync, let token = lifecycleToken else { return } + errorMessage = nil + isWorking = true + defer { isWorking = false } + do { + try await cloudSync.confirmAccountChange(policy: policy) + guard isCurrent(cloudSync, token: token) else { return } + defaults.set(true, forKey: CloudKitLibrarySync.enabledDefaultsKey) + isEnabled = true + confirmationContext = nil + await refreshStatus(cloudSync, token: token) + await refreshFailedAssets() + } catch { + guard isCurrent(cloudSync, token: token) else { return } + confirmationContext = await cloudSync.accountConfirmationContext() + status = .accountConfirmationRequired + errorMessage = "The iCloud account changed before setup finished. Nothing was uploaded. Please try again." + } + } + + func disable() async { + errorMessage = nil + isWorking = true + await stopCurrentSync() + defaults.set(false, forKey: CloudKitLibrarySync.enabledDefaultsKey) + isEnabled = false + confirmationContext = nil + failedAssetIdentities = [] + status = .disabled + isWorking = false + } + + func retrySync() async { + guard CloudKitLibrarySync.isEnabled(in: defaults), let cloudSync else { + await prepareEnable() + return + } + guard let token = lifecycleToken else { return } + errorMessage = nil + isWorking = true + defer { isWorking = false } + do { + try await cloudSync.syncNow() + guard isCurrent(cloudSync, token: token) else { return } + await refreshStatus(cloudSync, token: token) + await refreshFailedAssets() + } catch { + guard isCurrent(cloudSync, token: token) else { return } + await refreshStatus(cloudSync, token: token) + errorMessage = "Sync could not finish. Your changes are safe on this iPad. Try again later." + } + } + + func retryBookAssets(contentIdentity: String) async { + guard CloudKitLibrarySync.isEnabled(in: defaults), let cloudSync else { + errorMessage = "Enable iCloud sync and confirm the current account before retrying a book." + return + } + guard let token = lifecycleToken else { return } + errorMessage = nil + isWorking = true + await cloudSync.requestBookAssets(contentIdentity: contentIdentity) + guard isCurrent(cloudSync, token: token) else { return } + await refreshFailedAssets() + await refreshStatus(cloudSync, token: token) + isWorking = false + } + + private func startSync() async { + guard cloudSync == nil else { return } + do { + let (sync, token) = try makeSync() + cloudSync = sync + await router.use(sync) + guard isCurrent(sync, token: token) else { return } + await refreshStatus(sync, token: token) + await refreshFailedAssets() + } catch { + status = .blocked(.unknown(code: (error as NSError).code)) + errorMessage = "Piperly could not start iCloud sync. Your local library is unchanged." + } + } + + private func makeSync() throws -> (sync: CloudKitLibrarySync, token: ICloudSyncLifecycleToken) { + let token = ICloudSyncLifecycleToken() + lifecycleToken = token + let sync = try CloudKitLibrarySync( + enabled: true, + localSnapshotProvider: localSnapshotProvider, + localBookAssetProvider: localBookAssetProvider, + assetStagingURL: assetStagingURL, + statusHandler: { [weak self, token] status in + guard token.isActive else { return } + self?.status = status + if status == .accountConfirmationRequired { + Task { await self?.loadConfirmationContext() } + } + }, + remoteChangeHandler: { [remoteChangeHandler, token] changes, scope in + guard token.isActive else { return .complete } + return remoteChangeHandler(changes, scope) + } + ) + return (sync, token) + } + + private func loadConfirmationContext() async { + guard let sync = cloudSync, let token = lifecycleToken else { return } + let context = await sync.accountConfirmationContext() + guard isCurrent(sync, token: token) else { return } + confirmationContext = context + } + + private func refreshFailedAssets() async { + guard let sync = cloudSync, let token = lifecycleToken else { return } + let identities = await sync.failedAssetIdentities() + guard isCurrent(sync, token: token) else { return } + failedAssetIdentities = identities + } + + private func refreshStatus( + _ sync: CloudKitLibrarySync, + token: ICloudSyncLifecycleToken + ) async { + let currentStatus = await sync.currentStatus() + guard isCurrent(sync, token: token) else { return } + status = currentStatus + } + + private func stopCurrentSync() async { + lifecycleToken?.invalidate() + lifecycleToken = nil + await router.stop() + if let cloudSync { await cloudSync.stop() } + cloudSync = nil + } + + private func isCurrent( + _ sync: CloudKitLibrarySync, + token: ICloudSyncLifecycleToken + ) -> Bool { + token.isActive && lifecycleToken === token && cloudSync === sync + } +} + +@MainActor +final class ICloudSyncLifecycleToken { + private(set) var isActive = true + + func invalidate() { + isActive = false + } +} diff --git a/Piperly/Services/Sync/LibrarySyncing.swift b/Piperly/Services/Sync/LibrarySyncing.swift index 8e0dd93..86dd343 100644 --- a/Piperly/Services/Sync/LibrarySyncing.swift +++ b/Piperly/Services/Sync/LibrarySyncing.swift @@ -235,6 +235,10 @@ actor LibrarySyncRouter: LibrarySyncing { await drain() } + func stop() { + target = nil + } + nonisolated func enqueue(_ operations: [LibraryOutboxOperation]) throws { try outbox.append(operations) Task { await self.drain() } diff --git a/Piperly/Services/Sync/SyncStatus.swift b/Piperly/Services/Sync/SyncStatus.swift index a32e0f9..d713f56 100644 --- a/Piperly/Services/Sync/SyncStatus.swift +++ b/Piperly/Services/Sync/SyncStatus.swift @@ -69,6 +69,16 @@ enum AccountTransitionPolicy: Sendable, Equatable { case keepLocalAndUploadAfterFetch } +enum SyncAccountConfirmationContext: Sendable, Equatable { + case firstEnable + case accountChanged + case accountChangedWithPendingWork +} + +enum SyncLifecycleError: Error, Equatable { + case stopped +} + enum SyncAccountTransition { static func quarantine(snapshot: inout SyncStateSnapshot) { snapshot.quarantinedSaves.merge(snapshot.pendingSaves) { _, current in current } diff --git a/Piperly/Views/Settings/ICloudSyncSettingsView.swift b/Piperly/Views/Settings/ICloudSyncSettingsView.swift new file mode 100644 index 0000000..a82912a --- /dev/null +++ b/Piperly/Views/Settings/ICloudSyncSettingsView.swift @@ -0,0 +1,317 @@ +// Piperly - iPad ebook reader for kids +// Copyright (C) 2026 Interactive Buffoonery + +import SwiftUI + +struct ICloudSyncSettingsView: View { + @Environment(\.scenePhase) private var scenePhase + @EnvironmentObject private var bookStore: BookStore + @EnvironmentObject private var controller: ICloudSyncController + @State private var isUnlocked = false + @State private var confirmDisable = false + @State private var confirmDiscard = false + + var body: some View { + Group { + if isUnlocked { + controls + } else { + ParentGateView( + title: "iCloud Sync", + message: "A parent manages where the family library is stored and when it syncs.", + successTitle: "Manage iCloud Sync", + onSuccess: { isUnlocked = true } + ) + } + } + .navigationTitle("iCloud Sync") + .navigationBarTitleDisplayMode(.inline) + .onChange(of: scenePhase) { _, newPhase in + if ParentGateAccessPolicy.shouldReset(when: newPhase) { + isUnlocked = false + confirmDisable = false + confirmDiscard = false + } + } + .confirmationDialog( + "Turn Off iCloud Sync?", + isPresented: $confirmDisable, + titleVisibility: .visible + ) { + Button("Turn Off Sync", role: .destructive) { + Task { await controller.disable() } + } + Button("Cancel", role: .cancel) {} + } message: { + Text("Network syncing will stop. Books and reading information already on this iPad will stay here. Nothing is deleted from iCloud.") + } + .confirmationDialog( + "Discard Pending Work From the Previous Account?", + isPresented: $confirmDiscard, + titleVisibility: .visible + ) { + Button("Discard Pending Work", role: .destructive) { + Task { await controller.confirmEnable(policy: .discardPendingChanges) } + } + Button("Cancel", role: .cancel) {} + } message: { + Text( + "Piperly will first fetch this account's library, then discard only work " + + "that was waiting to upload to the previous account. This does not " + + "delete data from either iCloud account." + ) + } + } + + private var controls: some View { + List { + statusSection + accountChoiceSection + recoverySection + privacySection + } + .scrollContentBackground(.hidden) + .background(Piperly.Colors.background) + .disabled(controller.isWorking) + } + + private var statusSection: some View { + let presentation = ICloudStatusPresentation(controller.status) + return Section("Status") { + Label { + VStack(alignment: .leading, spacing: 4) { + Text(presentation.title) + .font(.system(size: 15, weight: .semibold, design: .rounded)) + Text(presentation.explanation) + .font(Piperly.Typography.caption) + .foregroundStyle(Piperly.Colors.textSecondary) + } + } icon: { + Image(systemName: presentation.symbolName) + .foregroundStyle(Piperly.Colors.accent) + } + .accessibilityElement(children: .combine) + .accessibilityLabel("iCloud sync status") + .accessibilityValue("\(presentation.title). \(presentation.explanation)") + + if actions.showsEnable { + Button("Enable iCloud Sync") { + Task { await controller.prepareEnable() } + } + .accessibilityHint("Checks the iCloud account before any information is uploaded") + } else if actions.showsDisable { + Button("Turn Off iCloud Sync", role: .destructive) { + confirmDisable = true + } + .accessibilityHint("Stops network sync and keeps local data") + } + + if controller.isWorking { + HStack { + ProgressView() + Text("Checking iCloud…") + } + .accessibilityElement(children: .combine) + } + + if let errorMessage = controller.errorMessage { + Text(errorMessage) + .font(Piperly.Typography.caption) + .foregroundStyle(Piperly.Colors.error) + .accessibilityLabel("iCloud sync error. \(errorMessage)") + } + } + .listRowBackground(Piperly.Colors.surface) + } + + @ViewBuilder + private var accountChoiceSection: some View { + if let context = controller.confirmationContext { + Section("Confirm iCloud Account") { + Text(accountExplanation(context)) + .font(Piperly.Typography.caption) + .foregroundStyle(Piperly.Colors.textSecondary) + + Button("Fetch iCloud, Then Keep and Upload Local Work") { + Task { await controller.confirmEnable(policy: .keepLocalAndUploadAfterFetch) } + } + .accessibilityHint("Fetches this account first, merges it with this iPad, then uploads local work") + + if actions.showsDiscardPendingWork { + Button("Discard Previous Account's Pending Work", role: .destructive) { + confirmDiscard = true + } + .accessibilityHint("Requires confirmation and never deletes either iCloud library") + } + } + .listRowBackground(Piperly.Colors.surface) + } + } + + @ViewBuilder + private var recoverySection: some View { + if shouldOfferGeneralRetry || (actions.showsAssetRecovery && !retryableBooks.isEmpty) { + Section("Recovery") { + if shouldOfferGeneralRetry { + Button("Try Sync Again") { + Task { await controller.retrySync() } + } + .accessibilityHint("Retries iCloud without removing local data") + } + + ForEach(actions.showsAssetRecovery ? retryableBooks : []) { book in + Button("Download \(book.title) Again") { + Task { await controller.retryBookAssets(contentIdentity: book.contentIdentity) } + } + .accessibilityLabel("Retry download for \(book.title)") + .accessibilityHint("Downloads this book from the private iCloud library") + } + } + .listRowBackground(Piperly.Colors.surface) + } + } + + private var privacySection: some View { + Section("What Uses iCloud") { + Text( + "EPUB files, book titles, reader profiles, reading state, bookmarks, saved " + + "words, and reader preferences sync through your private iCloud account " + + "and count against its storage quota." + ) + .font(Piperly.Typography.caption) + .foregroundStyle(Piperly.Colors.textSecondary) + Text( + "Piperly does not create a separate account. Turning sync off keeps local " + + "data. Deleting cloud data is a separate action and is not available " + + "on this screen." + ) + .font(Piperly.Typography.caption) + .foregroundStyle(Piperly.Colors.textSecondary) + } + .listRowBackground(Piperly.Colors.surface) + } + + private var retryableBooks: [Book] { + bookStore.books.filter { book in + controller.failedAssetIdentities.contains(book.contentIdentity) + || bookStore.assetAvailability(for: book) == .remoteOnly + || bookStore.assetAvailability(for: book) == .retryableFailure + } + } + + private var shouldOfferGeneralRetry: Bool { + actions.showsRetry + } + + private var actions: ICloudSettingsActions { + ICloudSettingsActions( + status: controller.status, + context: controller.confirmationContext, + isEnabled: controller.isEnabled + ) + } + + private func accountExplanation(_ context: SyncAccountConfirmationContext) -> String { + switch context { + case .firstEnable: + return "Piperly will fetch this iCloud account before uploading this iPad's library." + case .accountChanged: + return "The iCloud account changed. Piperly will fetch the new account before syncing anything." + case .accountChangedWithPendingWork: + return "The iCloud account changed while work was waiting to upload. Choose " + + "whether to keep that local work or discard it after Piperly fetches the new account." + } + } +} + +struct ICloudSettingsActions: Equatable { + let showsEnable: Bool + let showsDisable: Bool + let showsRetry: Bool + let showsDiscardPendingWork: Bool + let showsAssetRecovery: Bool + + init( + status: LibrarySyncStatus, + context: SyncAccountConfirmationContext?, + isEnabled: Bool + ) { + showsEnable = !isEnabled && context == nil + showsDisable = isEnabled + showsDiscardPendingWork = context == .accountChangedWithPendingWork + showsAssetRecovery = isEnabled && context == nil + switch status { + case .waitingToRetry, .blocked: + showsRetry = isEnabled + case .disabled, .idle, .syncing, .accountConfirmationRequired: + showsRetry = false + } + } +} + +enum ParentGateAccessPolicy { + static func shouldReset(when scenePhase: ScenePhase) -> Bool { + scenePhase != .active + } +} + +struct ICloudStatusPresentation: Equatable { + let title: String + let explanation: String + let symbolName: String + + init(_ status: LibrarySyncStatus) { + switch status { + case .disabled: + (title, explanation, symbolName) = ( + "Off", + "Sync is disabled. Local books and reading information stay on this iPad.", + "icloud.slash" + ) + case .idle: + (title, explanation, symbolName) = ("Up to Date", "Piperly is ready to sync changes through iCloud.", "checkmark.icloud") + case .syncing: + (title, explanation, symbolName) = ( + "Syncing", + "Piperly is sending or receiving changes.", + "arrow.triangle.2.circlepath.icloud" + ) + case .waitingToRetry(let date): + let time = date.map { " after \($0.formatted(date: .omitted, time: .shortened))" } ?? "" + (title, explanation, symbolName) = ( + "Waiting to Retry", + "iCloud is temporarily unavailable. Piperly will retry\(time).", + "clock.badge.exclamationmark" + ) + case .accountConfirmationRequired: + (title, explanation, symbolName) = ( + "Account Confirmation Needed", + "A parent must confirm the current iCloud account before syncing resumes.", + "person.crop.circle.badge.questionmark" + ) + case .blocked(let failure): + (title, explanation, symbolName) = ("Needs Attention", Self.explanation(for: failure), "exclamationmark.icloud") + } + } + + private static func explanation(for failure: SyncFailure) -> String { + switch failure { + case .retryable: + return "iCloud is temporarily unavailable. Try again." + case .accountUnavailable: + return "Sign in to iCloud in iPad Settings, then try again." + case .accountRestricted: + return "iCloud access is restricted on this iPad." + case .quotaExceeded: + return "The iCloud storage quota is full. Free space, then try again." + case .permissionDenied: + return "iCloud did not allow this sync. Check account settings, then try again." + case .invalidSchema: + return "This build cannot use the current iCloud database. Contact support before retrying." + case .missingLocalData: + return "A book file is missing or damaged. Retry that book below." + case .unknown: + return "Sync stopped safely. Your local data is unchanged. Try again." + } + } +} diff --git a/Piperly/Views/Settings/SettingsView.swift b/Piperly/Views/Settings/SettingsView.swift index 80718bf..5bc12a5 100644 --- a/Piperly/Views/Settings/SettingsView.swift +++ b/Piperly/Views/Settings/SettingsView.swift @@ -20,6 +20,7 @@ import AVFoundation struct SettingsView: View { @Environment(\.dismiss) private var dismiss @EnvironmentObject private var bookStore: BookStore + @EnvironmentObject private var iCloudSyncController: ICloudSyncController @State private var isVoiceListExpanded = false @State private var voices: [Voice] = [] @@ -41,6 +42,7 @@ struct SettingsView: View { NavigationStack { List { profilesSection + iCloudSection readingSection voicesSection } @@ -72,6 +74,39 @@ struct SettingsView: View { .presentationBackground(Piperly.Colors.background) } + private var iCloudSection: some View { + Section { + NavigationLink { + ICloudSyncSettingsView() + } label: { + HStack(spacing: 14) { + Image(systemName: "icloud.fill") + .font(.system(size: 20)) + .foregroundStyle(Piperly.Colors.accent) + .frame(width: 30) + .accessibilityHidden(true) + + VStack(alignment: .leading, spacing: 3) { + Text("iCloud Sync") + .font(.system(size: 15, weight: .medium, design: .rounded)) + .foregroundStyle(Piperly.Colors.textPrimary) + Text(ICloudStatusPresentation(iCloudSyncController.status).title) + .font(Piperly.Typography.caption) + .foregroundStyle(Piperly.Colors.textTertiary) + } + } + .padding(.vertical, 2) + } + .accessibilityLabel("iCloud Sync") + .accessibilityValue(ICloudStatusPresentation(iCloudSyncController.status).title) + .accessibilityHint("Opens parent controls for private iCloud sync") + } header: { + Text("Parent Controls") + .foregroundStyle(Piperly.Colors.textSecondary) + } + .listRowBackground(Piperly.Colors.surface) + } + private var profilesSection: some View { Section { NavigationLink { @@ -724,7 +759,7 @@ private struct DeleteProfileGateView: View { } } -private struct ParentGateView: View { +struct ParentGateView: View { let title: String let message: String let successTitle: String diff --git a/PiperlyTests/ICloudSettingsTests.swift b/PiperlyTests/ICloudSettingsTests.swift new file mode 100644 index 0000000..78222c7 --- /dev/null +++ b/PiperlyTests/ICloudSettingsTests.swift @@ -0,0 +1,101 @@ +import Testing +import SwiftUI +@testable import Piperly + +@Suite("iCloud settings presentation") +struct ICloudSettingsPresentationTests { + @Test func coversEverySyncStateWithRecoverableCopy() { + let states: [LibrarySyncStatus] = [ + .disabled, + .idle, + .syncing, + .waitingToRetry(nil), + .accountConfirmationRequired, + .blocked(.quotaExceeded), + ] + + for state in states { + let presentation = ICloudStatusPresentation(state) + #expect(!presentation.title.isEmpty) + #expect(!presentation.explanation.isEmpty) + #expect(!presentation.symbolName.isEmpty) + } + #expect(ICloudStatusPresentation(.disabled).explanation.contains("stay on this iPad")) + #expect(ICloudStatusPresentation(.blocked(.quotaExceeded)).explanation.contains("quota")) + } + + @Test func accountPolicyChoicesRemainExplicit() { + #expect(AccountTransitionPolicy.keepLocalAndUploadAfterFetch != .discardPendingChanges) + #expect(SyncAccountConfirmationContext.firstEnable != .accountChangedWithPendingWork) + } + + @Test func controlsCoverEnableDisableAccountChoiceAndRetry() { + let disabled = ICloudSettingsActions(status: .disabled, context: nil, isEnabled: false) + #expect(disabled.showsEnable) + #expect(!disabled.showsDisable) + #expect(!disabled.showsAssetRecovery) + + let enabled = ICloudSettingsActions(status: .idle, context: nil, isEnabled: true) + #expect(enabled.showsDisable) + #expect(!enabled.showsRetry) + #expect(enabled.showsAssetRecovery) + + let changedAccount = ICloudSettingsActions( + status: .accountConfirmationRequired, + context: .accountChangedWithPendingWork, + isEnabled: true + ) + #expect(changedAccount.showsDiscardPendingWork) + #expect(changedAccount.showsDisable) + + let firstEnableConfirmation = ICloudSettingsActions( + status: .accountConfirmationRequired, + context: .firstEnable, + isEnabled: false + ) + #expect(!firstEnableConfirmation.showsEnable) + #expect(!firstEnableConfirmation.showsDisable) + + let blocked = ICloudSettingsActions( + status: .blocked(.quotaExceeded), + context: nil, + isEnabled: true + ) + #expect(blocked.showsRetry) + + let failedFirstEnable = ICloudSettingsActions( + status: .blocked(.accountUnavailable), + context: nil, + isEnabled: false + ) + #expect(failedFirstEnable.showsEnable) + #expect(!failedFirstEnable.showsRetry) + #expect(!failedFirstEnable.showsAssetRecovery) + } + + @Test func parentGateRelocksWheneverTheAppLeavesTheForeground() { + #expect(!ParentGateAccessPolicy.shouldReset(when: .active)) + #expect(ParentGateAccessPolicy.shouldReset(when: .inactive)) + #expect(ParentGateAccessPolicy.shouldReset(when: .background)) + } + + @Test @MainActor func stoppedSyncLifecycleRejectsLateCallbacks() { + let token = ICloudSyncLifecycleToken() + #expect(token.isActive) + + token.invalidate() + + #expect(!token.isActive) + } + + @Test func replacementEngineRejectsOldBatchProvider() { + let oldEngineToken = CloudSyncActivityToken() + let newEngineToken = CloudSyncActivityToken() + #expect(oldEngineToken.isActive) + + oldEngineToken.invalidate() + + #expect(!oldEngineToken.isActive) + #expect(newEngineToken.isActive) + } +} diff --git a/PiperlyUITests/PiperlyUITests.swift b/PiperlyUITests/PiperlyUITests.swift index 1c00b5d..da0bdf2 100644 --- a/PiperlyUITests/PiperlyUITests.swift +++ b/PiperlyUITests/PiperlyUITests.swift @@ -5,4 +5,24 @@ final class PiperlyUITests: XCTestCase { let app = XCUIApplication() app.launch() } + + func testICloudControlsAreBehindParentGate() throws { + let app = XCUIApplication() + app.launch() + + let continueButton = app.buttons["Continue"] + if continueButton.waitForExistence(timeout: 2) { + continueButton.tap() + } + + app.buttons["Settings"].tap() + app.staticTexts["iCloud Sync"].tap() + + let parentCheck = app.staticTexts.matching( + NSPredicate(format: "label BEGINSWITH 'Parent check:'") + ).firstMatch + XCTAssertTrue(parentCheck.waitForExistence(timeout: 2)) + XCTAssertFalse(app.buttons["Enable iCloud Sync"].exists) + XCTAssertTrue(app.textFields["Parent check answer"].exists) + } } diff --git a/docs/app-store-privacy-review.md b/docs/app-store-privacy-review.md index 30e7abb..aa39daf 100644 --- a/docs/app-store-privacy-review.md +++ b/docs/app-store-privacy-review.md @@ -5,7 +5,7 @@ child-safety posture for public review. ## Audit Conclusion -Piperly can continue to declare no tracking and no collected data in +Piperly can continue to declare no tracking and no developer-collected data in `Piperly/Resources/PrivacyInfo.xcprivacy`. The app stores reading state locally and does not include external catalog @@ -15,6 +15,12 @@ UserDefaults required-reason declaration remains accurate because the app uses UserDefaults and `@AppStorage` for app-created settings and local reading metadata. +When a parent enables iCloud sync, EPUB files, book titles, reader profiles, +reading state, bookmarks, saved words, and reader preferences are sent only to +the user's private CloudKit database. They use the family's Apple iCloud +account and storage quota. Piperly does not use CloudKit sharing, user discovery, +analytics, or a developer-hosted account service. + ## Actual Data Flows ### Local-only app data @@ -40,6 +46,16 @@ metadata. - Imported EPUB files are copied into `Documents/Books`. - Extracted cover images are written into `Documents/Covers`. +### Private iCloud data + +- iCloud sync is off until a parent enables it through the parent gate. +- Synced data stays in the user's private CloudKit database. Piperly's developer + does not receive it through an analytics, account, or backend service. +- Turning sync off stops network activity and preserves local data. +- Account changes require a fresh fetch and an explicit parent choice before + pending work can be uploaded to the newly signed-in account. +- EPUB files and their related data count against the user's iCloud quota. + ### Readium and third-party dependencies - Piperly directly depends on Readium Swift Toolkit products: @@ -102,11 +118,17 @@ Use this as a publishable starting point for the public privacy policy: > preferences, and voice preferences. This information is used only to provide > the reading experience inside the app. > +> If a parent enables iCloud sync, Piperly stores EPUB files, book titles, +> reader profiles, reading state, bookmarks, saved words, and reader preferences +> in the family's private iCloud account so they can be used on the family's +> devices. This information counts against the account's iCloud storage quota. +> > Piperly does not include advertising, third-party analytics, social networking, > account creation, external catalog browsing, or in-app purchases. > -> To remove local reading data, delete books from the app or delete Piperly from -> the device. +> Turning iCloud sync off keeps reading data already stored on the device and +> does not delete cloud data. To remove local reading data, delete books from +> the app or delete Piperly from the device. ## Repo Evidence Checked diff --git a/docs/icloud-release-checklist.md b/docs/icloud-release-checklist.md new file mode 100644 index 0000000..91265c3 --- /dev/null +++ b/docs/icloud-release-checklist.md @@ -0,0 +1,87 @@ +# iCloud Release Checklist + +Complete every item before describing iCloud sync as release-ready. Simulator +and fake-based tests do not replace the physical-device checks below. + +## Apple Developer And CloudKit Setup + +- [ ] Create `iCloud.com.piperly.app` for team `7CNK4YPCQX`. +- [ ] Attach the container to app identifier `com.piperly.app`. +- [ ] Confirm the iCloud/CloudKit and remote-notification capabilities are on + the App ID, development profile, distribution profile, and Xcode target. +- [ ] Confirm the app uses only the private CloudKit database and the + `PiperlyLibrary` custom zone. +- [ ] Launch a development-signed build and create every record type and field + listed in ADR 0002 in the development environment. +- [ ] Inspect representative records and confirm record names contain hashes or + prefixed UUIDs, never titles, nicknames, or saved words. +- [ ] Add indexes only where the shipped queries require them. +- [ ] Promote the complete schema to production before TestFlight upload. +- [ ] Confirm the production schema in CloudKit Console. Production fields + cannot be renamed or removed safely after release. + +## Automated Checks + +- [ ] Run `xcodegen generate`. +- [ ] Run the full `Piperly` scheme on an iPad simulator. +- [ ] Confirm unit tests cover the parent gate, enable/disable behavior, account + policy choice, blocked/retry status copy, asset retry, and accessibility. +- [ ] Lint `Piperly/Info.plist` and `Piperly/Resources/PrivacyInfo.xcprivacy`. +- [ ] Confirm no new required-reason API was added. CloudKit itself does not + require a new entry in the privacy manifest. + +## Two Physical iPads, Same iCloud Account + +Use two physical iPads signed into the same test iCloud account. Start with +clean installs and record the app build, iPadOS versions, account, and time. + +- [ ] Enable sync through the parent gate on both devices. +- [ ] Import an EPUB on iPad A; confirm its title, cover, and readable EPUB arrive + on iPad B without relaunching either app. +- [ ] Create separate reader profiles and confirm profiles and preferences sync + while each iPad's active-profile selection remains local. +- [ ] Change progress, add bookmarks, and save words on each iPad. Confirm both + devices converge without mixing profile data. +- [ ] Import the same EPUB on both devices and confirm one book remains. +- [ ] Put iPad B offline. Read, change preferences, bookmark, and save words on + both devices. Reconnect and confirm all conflict rules from ADR 0002. +- [ ] Make a newer reading-position change on one device and confirm locator and + progression arrive together. +- [ ] Delete a book and a non-final profile; confirm cascaded data and files are + removed on the other device and do not reappear. +- [ ] Evict a local EPUB, confirm metadata remains, then redownload and verify it + opens. Exercise a failed download and the per-book retry button. +- [ ] Turn sync off. Confirm network work stops, local reading still works, and + neither local nor cloud data is deleted. Re-enable and confirm convergence. +- [ ] Relaunch during EPUB upload and download. Confirm durable retries finish + and staging files do not leak or corrupt the library. + +## Account, Quota, And Failure Recovery + +- [ ] Enable with no iCloud account and with a restricted account. Confirm clear, + recoverable copy and no upload. +- [ ] Switch accounts with no pending work. Confirm the new account is fetched + before sync resumes. +- [ ] Switch accounts with pending saves and deletes. Test both choices: keep + local work and upload after the fresh fetch, and discard previous-account + pending work. Confirm nothing reaches the wrong account. +- [ ] Switch accounts again during confirmation. Confirm the transition stops, + pending work stays quarantined, and the parent is asked again. +- [ ] Fill the test account's iCloud quota. Confirm the blocked status names the + quota problem, reading remains available, and retry works after space is freed. +- [ ] Exercise network loss, rate limiting, service unavailability, permission + failure, invalid schema, missing upload file, and corrupt download where + practical. Confirm local data remains safe and the UI offers the right retry. +- [ ] Confirm no settings action deletes the CloudKit library. Any future cloud + deletion action must have its own parent gate and separate confirmation. + +## Logs And Sign-Off + +- [ ] Capture app logs for engine start/stop, fetch, send, retry, account change, + asset verification, and blocked states. Logs must not include titles, + nicknames, saved words, locator JSON, or EPUB contents. +- [ ] Compare app logs with CloudKit Console activity and confirm push + notifications are an optimization, not the only fetch path. +- [ ] Save the two-iPad test date, testers, device/iPadOS versions, build number, + production-schema confirmation, failures found, and retest results in the + release record. diff --git a/docs/testflight-release-checklist.md b/docs/testflight-release-checklist.md index 116665b..57e2d80 100644 --- a/docs/testflight-release-checklist.md +++ b/docs/testflight-release-checklist.md @@ -17,6 +17,8 @@ signing account details in the repository. - App icon: single universal 1024x1024 icon with no alpha channel - Privacy manifest: declares no tracking, no collected data, and UserDefaults required-reason API use +- Private CloudKit container: `iCloud.com.piperly.app`; complete the setup and + physical-device matrix in `docs/icloud-release-checklist.md` Do not change the version or build number unless App Store Connect rejects the upload for a duplicate build number or the archive should use a new release @@ -72,6 +74,8 @@ Core flows: - Bookmarks add/remove with stickers and reappear in the bookmark list. - Saved words appear in the Words tab and re-speak when tapped. - Reader themes and font sizes apply live. +- Parent-gated iCloud controls enable, disable, report account/quota problems, + and retry without deleting local or cloud data. Phase 1 fix verification (behavior-only, no unit coverage):