react-native-cloud-sync 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +360 -0
- package/app.plugin.js +3 -0
- package/ios/CloudSyncError.swift +144 -0
- package/ios/CloudSyncImpl.swift +1263 -0
- package/ios/RNCloudSync.h +25 -0
- package/ios/RNCloudSync.mm +477 -0
- package/jest-mock.js +136 -0
- package/lib/commonjs/config.js +85 -0
- package/lib/commonjs/config.js.map +1 -0
- package/lib/commonjs/errors.js +244 -0
- package/lib/commonjs/errors.js.map +1 -0
- package/lib/commonjs/hooks.js +257 -0
- package/lib/commonjs/hooks.js.map +1 -0
- package/lib/commonjs/index.js +244 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/internal/autoFlush.js +65 -0
- package/lib/commonjs/internal/autoFlush.js.map +1 -0
- package/lib/commonjs/internal/base64.js +58 -0
- package/lib/commonjs/internal/base64.js.map +1 -0
- package/lib/commonjs/internal/bytes.js +32 -0
- package/lib/commonjs/internal/bytes.js.map +1 -0
- package/lib/commonjs/internal/cloudKitRest.js +527 -0
- package/lib/commonjs/internal/cloudKitRest.js.map +1 -0
- package/lib/commonjs/internal/enums.js +23 -0
- package/lib/commonjs/internal/enums.js.map +1 -0
- package/lib/commonjs/internal/googleDriveRest.js +624 -0
- package/lib/commonjs/internal/googleDriveRest.js.map +1 -0
- package/lib/commonjs/internal/keys.js +139 -0
- package/lib/commonjs/internal/keys.js.map +1 -0
- package/lib/commonjs/internal/logger.js +29 -0
- package/lib/commonjs/internal/logger.js.map +1 -0
- package/lib/commonjs/internal/nativeModule.js +125 -0
- package/lib/commonjs/internal/nativeModule.js.map +1 -0
- package/lib/commonjs/internal/timeout.js +72 -0
- package/lib/commonjs/internal/timeout.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/providers/cloudKit.js +398 -0
- package/lib/commonjs/providers/cloudKit.js.map +1 -0
- package/lib/commonjs/providers/cloudKitBackup.js +86 -0
- package/lib/commonjs/providers/cloudKitBackup.js.map +1 -0
- package/lib/commonjs/providers/cloudKitEncrypted.js +150 -0
- package/lib/commonjs/providers/cloudKitEncrypted.js.map +1 -0
- package/lib/commonjs/providers/googleDrive.js +219 -0
- package/lib/commonjs/providers/googleDrive.js.map +1 -0
- package/lib/commonjs/providers/googleDriveFiles.js +68 -0
- package/lib/commonjs/providers/googleDriveFiles.js.map +1 -0
- package/lib/commonjs/providers/icloudDocuments.js +121 -0
- package/lib/commonjs/providers/icloudDocuments.js.map +1 -0
- package/lib/commonjs/providers/icloudKV.js +171 -0
- package/lib/commonjs/providers/icloudKV.js.map +1 -0
- package/lib/commonjs/providers/icloudKV.web.js +42 -0
- package/lib/commonjs/providers/icloudKV.web.js.map +1 -0
- package/lib/commonjs/providers/memory.js +201 -0
- package/lib/commonjs/providers/memory.js.map +1 -0
- package/lib/commonjs/resolvers.js +128 -0
- package/lib/commonjs/resolvers.js.map +1 -0
- package/lib/commonjs/specs/NativeRNCloudSync.js +14 -0
- package/lib/commonjs/specs/NativeRNCloudSync.js.map +1 -0
- package/lib/commonjs/store.js +1064 -0
- package/lib/commonjs/store.js.map +1 -0
- package/lib/commonjs/testing.js +32 -0
- package/lib/commonjs/testing.js.map +1 -0
- package/lib/commonjs/types.js +86 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/module/config.js +72 -0
- package/lib/module/config.js.map +1 -0
- package/lib/module/errors.js +231 -0
- package/lib/module/errors.js.map +1 -0
- package/lib/module/hooks.js +250 -0
- package/lib/module/hooks.js.map +1 -0
- package/lib/module/index.js +46 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/internal/autoFlush.js +62 -0
- package/lib/module/internal/autoFlush.js.map +1 -0
- package/lib/module/internal/base64.js +53 -0
- package/lib/module/internal/base64.js.map +1 -0
- package/lib/module/internal/bytes.js +28 -0
- package/lib/module/internal/bytes.js.map +1 -0
- package/lib/module/internal/cloudKitRest.js +518 -0
- package/lib/module/internal/cloudKitRest.js.map +1 -0
- package/lib/module/internal/enums.js +18 -0
- package/lib/module/internal/enums.js.map +1 -0
- package/lib/module/internal/googleDriveRest.js +620 -0
- package/lib/module/internal/googleDriveRest.js.map +1 -0
- package/lib/module/internal/keys.js +134 -0
- package/lib/module/internal/keys.js.map +1 -0
- package/lib/module/internal/logger.js +23 -0
- package/lib/module/internal/logger.js.map +1 -0
- package/lib/module/internal/nativeModule.js +117 -0
- package/lib/module/internal/nativeModule.js.map +1 -0
- package/lib/module/internal/timeout.js +67 -0
- package/lib/module/internal/timeout.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/providers/cloudKit.js +392 -0
- package/lib/module/providers/cloudKit.js.map +1 -0
- package/lib/module/providers/cloudKitBackup.js +82 -0
- package/lib/module/providers/cloudKitBackup.js.map +1 -0
- package/lib/module/providers/cloudKitEncrypted.js +146 -0
- package/lib/module/providers/cloudKitEncrypted.js.map +1 -0
- package/lib/module/providers/googleDrive.js +214 -0
- package/lib/module/providers/googleDrive.js.map +1 -0
- package/lib/module/providers/googleDriveFiles.js +64 -0
- package/lib/module/providers/googleDriveFiles.js.map +1 -0
- package/lib/module/providers/icloudDocuments.js +117 -0
- package/lib/module/providers/icloudDocuments.js.map +1 -0
- package/lib/module/providers/icloudKV.js +165 -0
- package/lib/module/providers/icloudKV.js.map +1 -0
- package/lib/module/providers/icloudKV.web.js +36 -0
- package/lib/module/providers/icloudKV.web.js.map +1 -0
- package/lib/module/providers/memory.js +197 -0
- package/lib/module/providers/memory.js.map +1 -0
- package/lib/module/resolvers.js +120 -0
- package/lib/module/resolvers.js.map +1 -0
- package/lib/module/specs/NativeRNCloudSync.js +12 -0
- package/lib/module/specs/NativeRNCloudSync.js.map +1 -0
- package/lib/module/store.js +1061 -0
- package/lib/module/store.js.map +1 -0
- package/lib/module/testing.js +17 -0
- package/lib/module/testing.js.map +1 -0
- package/lib/module/types.js +82 -0
- package/lib/module/types.js.map +1 -0
- package/lib/typescript/commonjs/config.d.ts +33 -0
- package/lib/typescript/commonjs/config.d.ts.map +1 -0
- package/lib/typescript/commonjs/errors.d.ts +140 -0
- package/lib/typescript/commonjs/errors.d.ts.map +1 -0
- package/lib/typescript/commonjs/hooks.d.ts +109 -0
- package/lib/typescript/commonjs/hooks.d.ts.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +37 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/internal/autoFlush.d.ts +45 -0
- package/lib/typescript/commonjs/internal/autoFlush.d.ts.map +1 -0
- package/lib/typescript/commonjs/internal/base64.d.ts +12 -0
- package/lib/typescript/commonjs/internal/base64.d.ts.map +1 -0
- package/lib/typescript/commonjs/internal/bytes.d.ts +12 -0
- package/lib/typescript/commonjs/internal/bytes.d.ts.map +1 -0
- package/lib/typescript/commonjs/internal/cloudKitRest.d.ts +149 -0
- package/lib/typescript/commonjs/internal/cloudKitRest.d.ts.map +1 -0
- package/lib/typescript/commonjs/internal/enums.d.ts +10 -0
- package/lib/typescript/commonjs/internal/enums.d.ts.map +1 -0
- package/lib/typescript/commonjs/internal/googleDriveRest.d.ts +232 -0
- package/lib/typescript/commonjs/internal/googleDriveRest.d.ts.map +1 -0
- package/lib/typescript/commonjs/internal/keys.d.ts +28 -0
- package/lib/typescript/commonjs/internal/keys.d.ts.map +1 -0
- package/lib/typescript/commonjs/internal/logger.d.ts +10 -0
- package/lib/typescript/commonjs/internal/logger.d.ts.map +1 -0
- package/lib/typescript/commonjs/internal/nativeModule.d.ts +29 -0
- package/lib/typescript/commonjs/internal/nativeModule.d.ts.map +1 -0
- package/lib/typescript/commonjs/internal/timeout.d.ts +36 -0
- package/lib/typescript/commonjs/internal/timeout.d.ts.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/providers/cloudKit.d.ts +86 -0
- package/lib/typescript/commonjs/providers/cloudKit.d.ts.map +1 -0
- package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts +65 -0
- package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts.map +1 -0
- package/lib/typescript/commonjs/providers/cloudKitEncrypted.d.ts +37 -0
- package/lib/typescript/commonjs/providers/cloudKitEncrypted.d.ts.map +1 -0
- package/lib/typescript/commonjs/providers/googleDrive.d.ts +35 -0
- package/lib/typescript/commonjs/providers/googleDrive.d.ts.map +1 -0
- package/lib/typescript/commonjs/providers/googleDriveFiles.d.ts +59 -0
- package/lib/typescript/commonjs/providers/googleDriveFiles.d.ts.map +1 -0
- package/lib/typescript/commonjs/providers/icloudDocuments.d.ts +101 -0
- package/lib/typescript/commonjs/providers/icloudDocuments.d.ts.map +1 -0
- package/lib/typescript/commonjs/providers/icloudKV.d.ts +26 -0
- package/lib/typescript/commonjs/providers/icloudKV.d.ts.map +1 -0
- package/lib/typescript/commonjs/providers/icloudKV.web.d.ts +12 -0
- package/lib/typescript/commonjs/providers/icloudKV.web.d.ts.map +1 -0
- package/lib/typescript/commonjs/providers/memory.d.ts +90 -0
- package/lib/typescript/commonjs/providers/memory.d.ts.map +1 -0
- package/lib/typescript/commonjs/resolvers.d.ts +60 -0
- package/lib/typescript/commonjs/resolvers.d.ts.map +1 -0
- package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts +133 -0
- package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts.map +1 -0
- package/lib/typescript/commonjs/store.d.ts +118 -0
- package/lib/typescript/commonjs/store.d.ts.map +1 -0
- package/lib/typescript/commonjs/testing.d.ts +16 -0
- package/lib/typescript/commonjs/testing.d.ts.map +1 -0
- package/lib/typescript/commonjs/types.d.ts +367 -0
- package/lib/typescript/commonjs/types.d.ts.map +1 -0
- package/lib/typescript/module/config.d.ts +33 -0
- package/lib/typescript/module/config.d.ts.map +1 -0
- package/lib/typescript/module/errors.d.ts +140 -0
- package/lib/typescript/module/errors.d.ts.map +1 -0
- package/lib/typescript/module/hooks.d.ts +109 -0
- package/lib/typescript/module/hooks.d.ts.map +1 -0
- package/lib/typescript/module/index.d.ts +37 -0
- package/lib/typescript/module/index.d.ts.map +1 -0
- package/lib/typescript/module/internal/autoFlush.d.ts +45 -0
- package/lib/typescript/module/internal/autoFlush.d.ts.map +1 -0
- package/lib/typescript/module/internal/base64.d.ts +12 -0
- package/lib/typescript/module/internal/base64.d.ts.map +1 -0
- package/lib/typescript/module/internal/bytes.d.ts +12 -0
- package/lib/typescript/module/internal/bytes.d.ts.map +1 -0
- package/lib/typescript/module/internal/cloudKitRest.d.ts +149 -0
- package/lib/typescript/module/internal/cloudKitRest.d.ts.map +1 -0
- package/lib/typescript/module/internal/enums.d.ts +10 -0
- package/lib/typescript/module/internal/enums.d.ts.map +1 -0
- package/lib/typescript/module/internal/googleDriveRest.d.ts +232 -0
- package/lib/typescript/module/internal/googleDriveRest.d.ts.map +1 -0
- package/lib/typescript/module/internal/keys.d.ts +28 -0
- package/lib/typescript/module/internal/keys.d.ts.map +1 -0
- package/lib/typescript/module/internal/logger.d.ts +10 -0
- package/lib/typescript/module/internal/logger.d.ts.map +1 -0
- package/lib/typescript/module/internal/nativeModule.d.ts +29 -0
- package/lib/typescript/module/internal/nativeModule.d.ts.map +1 -0
- package/lib/typescript/module/internal/timeout.d.ts +36 -0
- package/lib/typescript/module/internal/timeout.d.ts.map +1 -0
- package/lib/typescript/module/package.json +1 -0
- package/lib/typescript/module/providers/cloudKit.d.ts +86 -0
- package/lib/typescript/module/providers/cloudKit.d.ts.map +1 -0
- package/lib/typescript/module/providers/cloudKitBackup.d.ts +65 -0
- package/lib/typescript/module/providers/cloudKitBackup.d.ts.map +1 -0
- package/lib/typescript/module/providers/cloudKitEncrypted.d.ts +37 -0
- package/lib/typescript/module/providers/cloudKitEncrypted.d.ts.map +1 -0
- package/lib/typescript/module/providers/googleDrive.d.ts +35 -0
- package/lib/typescript/module/providers/googleDrive.d.ts.map +1 -0
- package/lib/typescript/module/providers/googleDriveFiles.d.ts +59 -0
- package/lib/typescript/module/providers/googleDriveFiles.d.ts.map +1 -0
- package/lib/typescript/module/providers/icloudDocuments.d.ts +101 -0
- package/lib/typescript/module/providers/icloudDocuments.d.ts.map +1 -0
- package/lib/typescript/module/providers/icloudKV.d.ts +26 -0
- package/lib/typescript/module/providers/icloudKV.d.ts.map +1 -0
- package/lib/typescript/module/providers/icloudKV.web.d.ts +12 -0
- package/lib/typescript/module/providers/icloudKV.web.d.ts.map +1 -0
- package/lib/typescript/module/providers/memory.d.ts +90 -0
- package/lib/typescript/module/providers/memory.d.ts.map +1 -0
- package/lib/typescript/module/resolvers.d.ts +60 -0
- package/lib/typescript/module/resolvers.d.ts.map +1 -0
- package/lib/typescript/module/specs/NativeRNCloudSync.d.ts +133 -0
- package/lib/typescript/module/specs/NativeRNCloudSync.d.ts.map +1 -0
- package/lib/typescript/module/store.d.ts +118 -0
- package/lib/typescript/module/store.d.ts.map +1 -0
- package/lib/typescript/module/testing.d.ts +16 -0
- package/lib/typescript/module/testing.d.ts.map +1 -0
- package/lib/typescript/module/types.d.ts +367 -0
- package/lib/typescript/module/types.d.ts.map +1 -0
- package/package.json +186 -0
- package/plugin/build/index.d.ts +45 -0
- package/plugin/build/index.js +93 -0
- package/react-native-cloud-sync.podspec +48 -0
- package/src/config.ts +94 -0
- package/src/errors.ts +263 -0
- package/src/hooks.ts +337 -0
- package/src/index.ts +113 -0
- package/src/internal/autoFlush.ts +87 -0
- package/src/internal/base64.ts +63 -0
- package/src/internal/bytes.ts +28 -0
- package/src/internal/cloudKitRest.ts +654 -0
- package/src/internal/enums.ts +35 -0
- package/src/internal/googleDriveRest.ts +765 -0
- package/src/internal/keys.ts +160 -0
- package/src/internal/logger.ts +23 -0
- package/src/internal/nativeModule.ts +149 -0
- package/src/internal/timeout.ts +83 -0
- package/src/providers/cloudKit.ts +510 -0
- package/src/providers/cloudKitBackup.ts +124 -0
- package/src/providers/cloudKitEncrypted.ts +175 -0
- package/src/providers/googleDrive.ts +251 -0
- package/src/providers/googleDriveFiles.ts +117 -0
- package/src/providers/icloudDocuments.ts +175 -0
- package/src/providers/icloudKV.ts +206 -0
- package/src/providers/icloudKV.web.ts +41 -0
- package/src/providers/memory.ts +302 -0
- package/src/resolvers.ts +133 -0
- package/src/specs/NativeRNCloudSync.ts +184 -0
- package/src/store.ts +1288 -0
- package/src/testing.ts +22 -0
- package/src/types.ts +426 -0
|
@@ -0,0 +1,1263 @@
|
|
|
1
|
+
import CloudKit
|
|
2
|
+
import Foundation
|
|
3
|
+
|
|
4
|
+
/// All CloudKit and NSUbiquitousKeyValueStore logic.
|
|
5
|
+
///
|
|
6
|
+
/// The ObjC++ bridge (`RNCloudSync.mm`) is deliberately thin - it only
|
|
7
|
+
/// adapts between the two React Native architectures and forwards here. Keeping
|
|
8
|
+
/// the real work in Swift is what makes CloudKit's async API tolerable; the
|
|
9
|
+
/// same logic in Objective-C is a completion-block pyramid.
|
|
10
|
+
@objc public class CloudSyncImpl: NSObject {
|
|
11
|
+
@objc public static let shared = CloudSyncImpl()
|
|
12
|
+
|
|
13
|
+
static let recordTypeDefault = "KVBlob"
|
|
14
|
+
static let valueField = "value"
|
|
15
|
+
|
|
16
|
+
/// Where an asset's byte count is stashed alongside it, so a download can
|
|
17
|
+
/// learn the total size before the transfer starts. `CKAsset` itself
|
|
18
|
+
/// exposes no size until its bytes have already landed locally.
|
|
19
|
+
static func sizeField(_ fieldName: String) -> String { "\(fieldName)__size" }
|
|
20
|
+
|
|
21
|
+
/// CloudKit's documented per-record ceiling, excluding assets.
|
|
22
|
+
static let maxRecordBytes = 1024 * 1024
|
|
23
|
+
|
|
24
|
+
private var logsEnabled = false
|
|
25
|
+
|
|
26
|
+
/// Emits (eventName, payload) to whichever architecture is listening. The
|
|
27
|
+
/// bridge installs this; until it does, events are buffered (see below).
|
|
28
|
+
///
|
|
29
|
+
/// `@objc` is required. Swift does not expose members to Objective-C
|
|
30
|
+
/// automatically just because the class is `@objc` and inherits NSObject,
|
|
31
|
+
/// so without it the bridge fails to compile with "property 'emit' not
|
|
32
|
+
/// found on object of type 'CloudSyncImpl *'".
|
|
33
|
+
@objc public var emit: ((String, [String: Any]) -> Void)?
|
|
34
|
+
|
|
35
|
+
/// Opaque identity of the bridge instance that installed `emit`.
|
|
36
|
+
///
|
|
37
|
+
/// React Native holds two module instances briefly across a reload: the
|
|
38
|
+
/// replacement installs its callback, and only then does the outgoing one
|
|
39
|
+
/// dealloc. Without an identity check that dealloc tore down the *new*
|
|
40
|
+
/// instance's callback and removed its notification observers, so remote
|
|
41
|
+
/// change and account events stopped firing until the next reload.
|
|
42
|
+
///
|
|
43
|
+
/// A raw pointer rather than a reference on purpose: `strong` would keep the
|
|
44
|
+
/// bridge module alive forever behind this singleton, and `weak` is already
|
|
45
|
+
/// nil by the time that module's `dealloc` runs - which is precisely where
|
|
46
|
+
/// the comparison has to happen. It is only ever compared, never
|
|
47
|
+
/// dereferenced.
|
|
48
|
+
@objc public var emitOwner: UnsafeMutableRawPointer?
|
|
49
|
+
|
|
50
|
+
private let kvStore = NSUbiquitousKeyValueStore.default
|
|
51
|
+
|
|
52
|
+
/// Resolved once. `CKContainer(identifier:)` is not free, and the previous
|
|
53
|
+
/// in-app implementation this replaces rebuilt it on every single call.
|
|
54
|
+
private lazy var container: CKContainer? = {
|
|
55
|
+
guard let identifier = Self.resolveContainerIdentifier() else { return nil }
|
|
56
|
+
return CKContainer(identifier: identifier)
|
|
57
|
+
}()
|
|
58
|
+
|
|
59
|
+
private var database: CKDatabase? { container?.privateCloudDatabase }
|
|
60
|
+
|
|
61
|
+
// MARK: - Configuration
|
|
62
|
+
|
|
63
|
+
/// The container id declared in the bundle's entitlement listing, if it is
|
|
64
|
+
/// readable at all. `nil` means "could not confirm", never "definitely
|
|
65
|
+
/// absent" - entitlements live in the code signature, and the API that reads
|
|
66
|
+
/// those (`SecTaskCopyValueForEntitlement`) is not public on iOS.
|
|
67
|
+
static func declaredContainerIdentifier() -> String? {
|
|
68
|
+
guard let ids = Bundle.main.object(
|
|
69
|
+
forInfoDictionaryKey: "com.apple.developer.icloud-container-identifiers"
|
|
70
|
+
) as? [String] else { return nil }
|
|
71
|
+
return ids.first
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/// Reads the container id straight out of the app's entitlements, so apps do
|
|
75
|
+
/// not have to repeat it in JavaScript and cannot get the two out of sync.
|
|
76
|
+
static func resolveContainerIdentifier() -> String? {
|
|
77
|
+
if let declared = declaredContainerIdentifier() { return declared }
|
|
78
|
+
// Entitlements are not in Info.plist on a device build; fall back to the
|
|
79
|
+
// conventional `iCloud.<bundle id>` form.
|
|
80
|
+
guard let bundleId = Bundle.main.bundleIdentifier else { return nil }
|
|
81
|
+
return "iCloud.\(bundleId)"
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
@objc public func getConstants() -> [String: Any] {
|
|
85
|
+
return [
|
|
86
|
+
"containerIdentifier": Self.resolveContainerIdentifier() ?? "",
|
|
87
|
+
// Derived from the DECLARED identifier, not the resolved one.
|
|
88
|
+
// `resolveContainerIdentifier` falls back to `iCloud.<bundle id>`
|
|
89
|
+
// whenever the declaration is unreadable, so deriving this from it
|
|
90
|
+
// made the constant `true` for every app that has a bundle id -
|
|
91
|
+
// including one with no iCloud capability at all, which is exactly
|
|
92
|
+
// the case a caller reads this to detect. It is a confirmation, not
|
|
93
|
+
// a guarantee: false means "not confirmed here", and the async
|
|
94
|
+
// account-status path is the authoritative check.
|
|
95
|
+
"hasICloudEntitlement": Self.declaredContainerIdentifier() != nil,
|
|
96
|
+
]
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
@objc public func setLogsEnabled(_ enabled: Bool) {
|
|
100
|
+
logsEnabled = enabled
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private func log(_ message: String) {
|
|
104
|
+
guard logsEnabled else { return }
|
|
105
|
+
NSLog("[RNCloudSync] %@", message)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// MARK: - Observers
|
|
109
|
+
|
|
110
|
+
/// Starts observing the two notifications that every library in this space
|
|
111
|
+
/// either ignores or crashes on.
|
|
112
|
+
@objc public func startObserving() {
|
|
113
|
+
NotificationCenter.default.addObserver(
|
|
114
|
+
self,
|
|
115
|
+
selector: #selector(kvStoreDidChange(_:)),
|
|
116
|
+
name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
|
|
117
|
+
object: kvStore
|
|
118
|
+
)
|
|
119
|
+
NotificationCenter.default.addObserver(
|
|
120
|
+
self,
|
|
121
|
+
selector: #selector(identityDidChange(_:)),
|
|
122
|
+
name: .NSUbiquityIdentityDidChange,
|
|
123
|
+
object: nil
|
|
124
|
+
)
|
|
125
|
+
NotificationCenter.default.addObserver(
|
|
126
|
+
self,
|
|
127
|
+
selector: #selector(ckAccountDidChange(_:)),
|
|
128
|
+
name: .CKAccountChanged,
|
|
129
|
+
object: nil
|
|
130
|
+
)
|
|
131
|
+
// Pull down anything already waiting so a cold start sees remote data.
|
|
132
|
+
kvStore.synchronize()
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
@objc public func stopObserving() {
|
|
136
|
+
NotificationCenter.default.removeObserver(self)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
@objc private func kvStoreDidChange(_ note: Notification) {
|
|
140
|
+
let userInfo = note.userInfo ?? [:]
|
|
141
|
+
let keys = userInfo[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String] ?? []
|
|
142
|
+
let rawReason = userInfo[NSUbiquitousKeyValueStoreChangeReasonKey] as? Int
|
|
143
|
+
|
|
144
|
+
let reason: String
|
|
145
|
+
switch rawReason {
|
|
146
|
+
case NSUbiquitousKeyValueStoreServerChange: reason = "serverChange"
|
|
147
|
+
case NSUbiquitousKeyValueStoreInitialSyncChange: reason = "initialSync"
|
|
148
|
+
case NSUbiquitousKeyValueStoreQuotaViolationChange: reason = "quotaViolation"
|
|
149
|
+
case NSUbiquitousKeyValueStoreAccountChange: reason = "accountChange"
|
|
150
|
+
default: reason = "unknown"
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
log("kv changed externally: \(reason), \(keys.count) key(s)")
|
|
154
|
+
emit?("remoteChange", ["keys": keys, "reason": reason, "provider": "icloudKV"])
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
@objc private func identityDidChange(_ note: Notification) {
|
|
158
|
+
// The event nobody handles. A different Apple ID is now signed in, so
|
|
159
|
+
// any user-scoped state the app cached belongs to the previous user.
|
|
160
|
+
log("iCloud identity changed")
|
|
161
|
+
accountStatusString { status in
|
|
162
|
+
self.emit?("accountChange", [
|
|
163
|
+
"status": status,
|
|
164
|
+
"identityChanged": true,
|
|
165
|
+
"provider": "icloudKV",
|
|
166
|
+
])
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
@objc private func ckAccountDidChange(_ note: Notification) {
|
|
171
|
+
accountStatusString { status in
|
|
172
|
+
self.emit?("accountChange", [
|
|
173
|
+
"status": status,
|
|
174
|
+
"identityChanged": false,
|
|
175
|
+
"provider": "cloudKit",
|
|
176
|
+
])
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// MARK: - Account
|
|
181
|
+
|
|
182
|
+
private func accountStatusString(_ completion: @escaping (String) -> Void) {
|
|
183
|
+
guard let container = container else {
|
|
184
|
+
completion("couldNotDetermine")
|
|
185
|
+
return
|
|
186
|
+
}
|
|
187
|
+
container.accountStatus { status, _ in
|
|
188
|
+
switch status {
|
|
189
|
+
case .available: completion("available")
|
|
190
|
+
case .noAccount: completion("noAccount")
|
|
191
|
+
case .restricted: completion("restricted")
|
|
192
|
+
case .temporarilyUnavailable: completion("temporarilyUnavailable")
|
|
193
|
+
case .couldNotDetermine: completion("couldNotDetermine")
|
|
194
|
+
@unknown default: completion("couldNotDetermine")
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
@objc public func getAccountStatus(
|
|
200
|
+
resolve: @escaping (Any?) -> Void,
|
|
201
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
202
|
+
) {
|
|
203
|
+
accountStatusString { resolve($0) }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
@objc public func isAvailable(
|
|
207
|
+
resolve: @escaping (Any?) -> Void,
|
|
208
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
209
|
+
) {
|
|
210
|
+
accountStatusString { resolve($0 == "available") }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// MARK: - Key-value store
|
|
214
|
+
|
|
215
|
+
@objc public func kvGetItem(
|
|
216
|
+
_ key: String,
|
|
217
|
+
resolve: @escaping (Any?) -> Void,
|
|
218
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
219
|
+
) {
|
|
220
|
+
// `nil` here genuinely means absent - NSUbiquitousKeyValueStore has no
|
|
221
|
+
// failure mode for a read - so returning it is not the silent-failure
|
|
222
|
+
// anti-pattern this package is built to avoid.
|
|
223
|
+
resolve(kvStore.string(forKey: key))
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/// Apple's three documented ceilings for `NSUbiquitousKeyValueStore`.
|
|
227
|
+
///
|
|
228
|
+
/// All three are enforced before the write, not discovered after it. The
|
|
229
|
+
/// per-key one is the obvious one; the other two are the ones that actually
|
|
230
|
+
/// bite in practice, and neither produces an error at the call site - the
|
|
231
|
+
/// store simply stops accepting data and reports a
|
|
232
|
+
/// `NSUbiquitousKeyValueStoreQuotaViolationChange` notification later, by
|
|
233
|
+
/// which point the caller has long since been told the write succeeded.
|
|
234
|
+
static let kvMaxBytesPerKey = 1024 * 1024
|
|
235
|
+
static let kvMaxTotalBytes = 1024 * 1024
|
|
236
|
+
static let kvMaxKeys = 1024
|
|
237
|
+
|
|
238
|
+
/// UTF-8 size of everything currently in the store, and how many keys.
|
|
239
|
+
///
|
|
240
|
+
/// Only string and data values are measured; the store also accepts numbers
|
|
241
|
+
/// and booleans, whose contribution is negligible next to a payload and
|
|
242
|
+
/// which have no meaningful byte length to ask for.
|
|
243
|
+
private func kvUsage(excluding key: String?) -> (bytes: Int, keys: Int) {
|
|
244
|
+
var bytes = 0
|
|
245
|
+
let all = kvStore.dictionaryRepresentation
|
|
246
|
+
for (existingKey, existingValue) in all {
|
|
247
|
+
if existingKey == key { continue }
|
|
248
|
+
if let text = existingValue as? String {
|
|
249
|
+
bytes += text.lengthOfBytes(using: .utf8)
|
|
250
|
+
} else if let data = existingValue as? Data {
|
|
251
|
+
bytes += data.count
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return (bytes, all.count)
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
@objc public func kvSetItem(
|
|
258
|
+
_ key: String,
|
|
259
|
+
value: String,
|
|
260
|
+
resolve: @escaping (Any?) -> Void,
|
|
261
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
262
|
+
) {
|
|
263
|
+
let bytes = value.lengthOfBytes(using: .utf8)
|
|
264
|
+
// Apple's per-key ceiling is 1 MB. Enforce it here with a typed error
|
|
265
|
+
// rather than letting the write vanish server-side with no signal.
|
|
266
|
+
if bytes > Self.kvMaxBytesPerKey {
|
|
267
|
+
let error = CloudSyncError.coded(
|
|
268
|
+
code: CloudSyncErrorCode.payloadTooLarge,
|
|
269
|
+
message: "Value is \(bytes) bytes; the iCloud key-value store allows "
|
|
270
|
+
+ "\(Self.kvMaxBytesPerKey) per key.",
|
|
271
|
+
info: ["limitBytes": Self.kvMaxBytesPerKey, "actualBytes": bytes]
|
|
272
|
+
)
|
|
273
|
+
reject(error.code, error.message, error.asNSError)
|
|
274
|
+
return
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
let isNewKey = kvStore.object(forKey: key) == nil
|
|
278
|
+
let usage = kvUsage(excluding: key)
|
|
279
|
+
|
|
280
|
+
// The 1 MB *total* is the limit that actually bites: a handful of large
|
|
281
|
+
// values silently starves every other key, and the only signal is a
|
|
282
|
+
// quota-violation notification that arrives long after the write was
|
|
283
|
+
// reported as successful.
|
|
284
|
+
let projected = usage.bytes + bytes
|
|
285
|
+
if projected > Self.kvMaxTotalBytes {
|
|
286
|
+
let error = CloudSyncError.coded(
|
|
287
|
+
code: CloudSyncErrorCode.quotaExceeded,
|
|
288
|
+
message: "This write would put the iCloud key-value store at \(projected) bytes, "
|
|
289
|
+
+ "over its \(Self.kvMaxTotalBytes)-byte total. Route larger values to "
|
|
290
|
+
+ "CloudKit or Drive - the store facade's tiering does this for you.",
|
|
291
|
+
info: ["limitBytes": Self.kvMaxTotalBytes, "actualBytes": projected]
|
|
292
|
+
)
|
|
293
|
+
reject(error.code, error.message, error.asNSError)
|
|
294
|
+
return
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if isNewKey && usage.keys >= Self.kvMaxKeys {
|
|
298
|
+
let error = CloudSyncError.coded(
|
|
299
|
+
code: CloudSyncErrorCode.quotaExceeded,
|
|
300
|
+
message: "The iCloud key-value store already holds \(usage.keys) keys, its "
|
|
301
|
+
+ "documented maximum of \(Self.kvMaxKeys).",
|
|
302
|
+
info: ["limitBytes": Self.kvMaxKeys, "actualBytes": usage.keys + 1]
|
|
303
|
+
)
|
|
304
|
+
reject(error.code, error.message, error.asNSError)
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
kvStore.set(value, forKey: key)
|
|
309
|
+
// Schedules an upload; it does NOT confirm one. Callers are told this in
|
|
310
|
+
// the JS docs so nobody reads a resolved promise as "stored in iCloud".
|
|
311
|
+
kvStore.synchronize()
|
|
312
|
+
resolve(nil)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
@objc public func kvRemoveItem(
|
|
316
|
+
_ key: String,
|
|
317
|
+
resolve: @escaping (Any?) -> Void,
|
|
318
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
319
|
+
) {
|
|
320
|
+
kvStore.removeObject(forKey: key)
|
|
321
|
+
kvStore.synchronize()
|
|
322
|
+
resolve(nil)
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
@objc public func kvGetAllKeys(
|
|
326
|
+
resolve: @escaping (Any?) -> Void,
|
|
327
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
328
|
+
) {
|
|
329
|
+
resolve(Array(kvStore.dictionaryRepresentation.keys))
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/// Every key and value in one call.
|
|
333
|
+
///
|
|
334
|
+
/// `dictionaryRepresentation` is already in memory, so this is one bridge
|
|
335
|
+
/// hop where `kvGetAllKeys` + N `kvGetItem` calls would be N+1. Non-string
|
|
336
|
+
/// values are skipped rather than coerced: the store accepts numbers, dates
|
|
337
|
+
/// and data, and stringifying those would hand back something that does not
|
|
338
|
+
/// round-trip through `kvSetItem`.
|
|
339
|
+
@objc public func kvGetAllItems(
|
|
340
|
+
resolve: @escaping (Any?) -> Void,
|
|
341
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
342
|
+
) {
|
|
343
|
+
var items: [String: String] = [:]
|
|
344
|
+
for (key, value) in kvStore.dictionaryRepresentation {
|
|
345
|
+
if let text = value as? String { items[key] = text }
|
|
346
|
+
}
|
|
347
|
+
resolve(items)
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
@objc public func kvSync(
|
|
351
|
+
resolve: @escaping (Any?) -> Void,
|
|
352
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
353
|
+
) {
|
|
354
|
+
resolve(kvStore.synchronize())
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/// How full the key-value store is, against its documented ceilings.
|
|
358
|
+
///
|
|
359
|
+
/// Apple exposes no usage API, so this is measured from
|
|
360
|
+
/// `dictionaryRepresentation` - which is a local plist, not a network call,
|
|
361
|
+
/// so it is cheap enough to read on demand. Without it an app can only find
|
|
362
|
+
/// out it is near the 1 MB total by hitting it, and hitting it is silent.
|
|
363
|
+
@objc public func kvGetUsage(
|
|
364
|
+
resolve: @escaping (Any?) -> Void,
|
|
365
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
366
|
+
) {
|
|
367
|
+
let usage = kvUsage(excluding: nil)
|
|
368
|
+
resolve([
|
|
369
|
+
"usedBytes": usage.bytes,
|
|
370
|
+
"totalBytes": Self.kvMaxTotalBytes,
|
|
371
|
+
"keyCount": usage.keys,
|
|
372
|
+
"maxKeys": Self.kvMaxKeys,
|
|
373
|
+
])
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// MARK: - CloudKit records
|
|
377
|
+
|
|
378
|
+
private func requireDatabase() throws -> CKDatabase {
|
|
379
|
+
guard let database = database else {
|
|
380
|
+
throw CloudSyncError.coded(
|
|
381
|
+
code: CloudSyncErrorCode.containerMisconfigured,
|
|
382
|
+
message: "No iCloud container is configured. Add the iCloud capability and a "
|
|
383
|
+
+ "CloudKit container to the app target's entitlements.",
|
|
384
|
+
info: [:]
|
|
385
|
+
)
|
|
386
|
+
}
|
|
387
|
+
return database
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
private func recordID(_ recordName: String, _ zoneName: String?) -> CKRecord.ID {
|
|
391
|
+
guard let zoneName = zoneName else { return CKRecord.ID(recordName: recordName) }
|
|
392
|
+
let zoneID = CKRecordZone.ID(zoneName: zoneName, ownerName: CKCurrentUserDefaultName)
|
|
393
|
+
return CKRecord.ID(recordName: recordName, zoneID: zoneID)
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/// Reads the value field, from the encrypted or the plain side of the record.
|
|
397
|
+
///
|
|
398
|
+
/// A field is one or the other, never both: CloudKit records encryption in
|
|
399
|
+
/// the schema, so a field written through `encryptedValues` is invisible to
|
|
400
|
+
/// the plain subscript and vice versa. Reading the wrong side returns nil,
|
|
401
|
+
/// which would look exactly like a missing record - hence the flag rather
|
|
402
|
+
/// than trying both and hoping.
|
|
403
|
+
private static func readValue(_ record: CKRecord?, encrypted: Bool) -> String? {
|
|
404
|
+
guard let record = record else { return nil }
|
|
405
|
+
return encrypted
|
|
406
|
+
? record.encryptedValues[Self.valueField] as? String
|
|
407
|
+
: record[Self.valueField] as? String
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
@objc public func ckGetRecord(
|
|
411
|
+
_ recordType: String,
|
|
412
|
+
recordName: String,
|
|
413
|
+
zoneName: String?,
|
|
414
|
+
encrypted: Bool,
|
|
415
|
+
resolve: @escaping (Any?) -> Void,
|
|
416
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
417
|
+
) {
|
|
418
|
+
do {
|
|
419
|
+
let database = try requireDatabase()
|
|
420
|
+
database.fetch(withRecordID: recordID(recordName, zoneName)) { record, error in
|
|
421
|
+
if let error = error {
|
|
422
|
+
// A missing record is a normal outcome, not a failure - but
|
|
423
|
+
// it must be distinguished from every other error, which is
|
|
424
|
+
// exactly what a blanket `catch { return nil }` destroys.
|
|
425
|
+
if let ckError = error as? CKError, ckError.code == .unknownItem {
|
|
426
|
+
resolve(nil)
|
|
427
|
+
return
|
|
428
|
+
}
|
|
429
|
+
let mapped = CloudSyncError.from(error)
|
|
430
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
431
|
+
return
|
|
432
|
+
}
|
|
433
|
+
resolve(Self.readValue(record, encrypted: encrypted))
|
|
434
|
+
}
|
|
435
|
+
} catch {
|
|
436
|
+
let mapped = CloudSyncError.from(error)
|
|
437
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/// - Parameter encrypted: write through `CKRecord.encryptedValues`, so the
|
|
442
|
+
/// value is end-to-end encrypted by CloudKit itself. The key lives in the
|
|
443
|
+
/// user's iCloud Keychain and never reaches Apple's servers, which also
|
|
444
|
+
/// means no server-side path - including CloudKit Web Services, and so
|
|
445
|
+
/// this package's Android and web support - can ever read it back.
|
|
446
|
+
@objc public func ckSaveRecord(
|
|
447
|
+
_ recordType: String,
|
|
448
|
+
recordName: String,
|
|
449
|
+
value: String,
|
|
450
|
+
zoneName: String?,
|
|
451
|
+
encrypted: Bool,
|
|
452
|
+
resolve: @escaping (Any?) -> Void,
|
|
453
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
454
|
+
) {
|
|
455
|
+
let bytes = value.lengthOfBytes(using: .utf8)
|
|
456
|
+
if bytes > Self.maxRecordBytes {
|
|
457
|
+
let error = CloudSyncError.coded(
|
|
458
|
+
code: CloudSyncErrorCode.payloadTooLarge,
|
|
459
|
+
message: "Value is \(bytes) bytes; CloudKit records are limited to \(Self.maxRecordBytes). "
|
|
460
|
+
+ "Use the store facade with tiering enabled to route large values to a CKAsset.",
|
|
461
|
+
info: ["limitBytes": Self.maxRecordBytes, "actualBytes": bytes]
|
|
462
|
+
)
|
|
463
|
+
reject(error.code, error.message, error.asNSError)
|
|
464
|
+
return
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
do {
|
|
468
|
+
let database = try requireDatabase()
|
|
469
|
+
let id = recordID(recordName, zoneName)
|
|
470
|
+
let record = CKRecord(recordType: recordType, recordID: id)
|
|
471
|
+
if encrypted {
|
|
472
|
+
record.encryptedValues[Self.valueField] = value as CKRecordValue
|
|
473
|
+
} else {
|
|
474
|
+
record[Self.valueField] = value as CKRecordValue
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
let operation = CKModifyRecordsOperation(recordsToSave: [record], recordIDsToDelete: nil)
|
|
478
|
+
// Last-write-wins, matching the REST client so both platforms
|
|
479
|
+
// resolve concurrent writes the same way. `.ifServerRecordUnchanged`
|
|
480
|
+
// would fail routine two-device writes on a change-tag conflict.
|
|
481
|
+
operation.savePolicy = .changedKeys
|
|
482
|
+
|
|
483
|
+
operation.modifyRecordsResultBlock = { result in
|
|
484
|
+
// Inspecting this result is the entire point. Discarding it -
|
|
485
|
+
// which both cryptoc's module and jacobp100's library did - turns
|
|
486
|
+
// every failed write into a reported success.
|
|
487
|
+
switch result {
|
|
488
|
+
case .success:
|
|
489
|
+
resolve(nil)
|
|
490
|
+
case let .failure(error):
|
|
491
|
+
let mapped = CloudSyncError.from(error)
|
|
492
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
database.add(operation)
|
|
496
|
+
} catch {
|
|
497
|
+
let mapped = CloudSyncError.from(error)
|
|
498
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
@objc public func ckDeleteRecord(
|
|
503
|
+
_ recordName: String,
|
|
504
|
+
zoneName: String?,
|
|
505
|
+
resolve: @escaping (Any?) -> Void,
|
|
506
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
507
|
+
) {
|
|
508
|
+
do {
|
|
509
|
+
let database = try requireDatabase()
|
|
510
|
+
database.delete(withRecordID: recordID(recordName, zoneName)) { _, error in
|
|
511
|
+
if let error = error {
|
|
512
|
+
// Already gone is the desired end state.
|
|
513
|
+
if let ckError = error as? CKError, ckError.code == .unknownItem {
|
|
514
|
+
resolve(true)
|
|
515
|
+
return
|
|
516
|
+
}
|
|
517
|
+
let mapped = CloudSyncError.from(error)
|
|
518
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
519
|
+
return
|
|
520
|
+
}
|
|
521
|
+
resolve(true)
|
|
522
|
+
}
|
|
523
|
+
} catch {
|
|
524
|
+
let mapped = CloudSyncError.from(error)
|
|
525
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
@objc public func ckQueryRecordNames(
|
|
530
|
+
_ recordType: String,
|
|
531
|
+
zoneName: String?,
|
|
532
|
+
resolve: @escaping (Any?) -> Void,
|
|
533
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
534
|
+
) {
|
|
535
|
+
do {
|
|
536
|
+
let database = try requireDatabase()
|
|
537
|
+
let zoneID = zoneName.map {
|
|
538
|
+
CKRecordZone.ID(zoneName: $0, ownerName: CKCurrentUserDefaultName)
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
var names: [String] = []
|
|
542
|
+
|
|
543
|
+
// CKQueryOperation returns one page of results and hands back a
|
|
544
|
+
// cursor for the rest. Resolving on the first page silently
|
|
545
|
+
// truncated getAllKeys(), and migrate() is built on getAllKeys() -
|
|
546
|
+
// so it surfaced as a migration that quietly copied part of the
|
|
547
|
+
// data and reported success. Follow the cursor to exhaustion.
|
|
548
|
+
func run(_ operation: CKQueryOperation) {
|
|
549
|
+
operation.zoneID = zoneID
|
|
550
|
+
operation.desiredKeys = []
|
|
551
|
+
operation.recordMatchedBlock = { recordID, result in
|
|
552
|
+
if case .success = result { names.append(recordID.recordName) }
|
|
553
|
+
}
|
|
554
|
+
operation.queryResultBlock = { result in
|
|
555
|
+
switch result {
|
|
556
|
+
case let .success(cursor):
|
|
557
|
+
guard let cursor = cursor else {
|
|
558
|
+
resolve(names)
|
|
559
|
+
return
|
|
560
|
+
}
|
|
561
|
+
run(CKQueryOperation(cursor: cursor))
|
|
562
|
+
case let .failure(error):
|
|
563
|
+
let mapped = CloudSyncError.from(error)
|
|
564
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
database.add(operation)
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
let query = CKQuery(recordType: recordType, predicate: NSPredicate(value: true))
|
|
571
|
+
run(CKQueryOperation(query: query))
|
|
572
|
+
} catch {
|
|
573
|
+
let mapped = CloudSyncError.from(error)
|
|
574
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// MARK: - Zones
|
|
579
|
+
|
|
580
|
+
@objc public func ckCreateZone(
|
|
581
|
+
_ zoneName: String,
|
|
582
|
+
resolve: @escaping (Any?) -> Void,
|
|
583
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
584
|
+
) {
|
|
585
|
+
do {
|
|
586
|
+
let database = try requireDatabase()
|
|
587
|
+
let zone = CKRecordZone(zoneName: zoneName)
|
|
588
|
+
let operation = CKModifyRecordZonesOperation(recordZonesToSave: [zone], recordZoneIDsToDelete: nil)
|
|
589
|
+
operation.modifyRecordZonesResultBlock = { result in
|
|
590
|
+
switch result {
|
|
591
|
+
case .success:
|
|
592
|
+
resolve(nil)
|
|
593
|
+
case let .failure(error):
|
|
594
|
+
let mapped = CloudSyncError.from(error)
|
|
595
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
database.add(operation)
|
|
599
|
+
} catch {
|
|
600
|
+
let mapped = CloudSyncError.from(error)
|
|
601
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
@objc public func ckDeleteZone(
|
|
606
|
+
_ zoneName: String,
|
|
607
|
+
resolve: @escaping (Any?) -> Void,
|
|
608
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
609
|
+
) {
|
|
610
|
+
do {
|
|
611
|
+
let database = try requireDatabase()
|
|
612
|
+
let zoneID = CKRecordZone.ID(zoneName: zoneName, ownerName: CKCurrentUserDefaultName)
|
|
613
|
+
let operation = CKModifyRecordZonesOperation(recordZonesToSave: nil, recordZoneIDsToDelete: [zoneID])
|
|
614
|
+
operation.modifyRecordZonesResultBlock = { result in
|
|
615
|
+
switch result {
|
|
616
|
+
case .success:
|
|
617
|
+
resolve(nil)
|
|
618
|
+
case let .failure(error):
|
|
619
|
+
let mapped = CloudSyncError.from(error)
|
|
620
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
database.add(operation)
|
|
624
|
+
} catch {
|
|
625
|
+
let mapped = CloudSyncError.from(error)
|
|
626
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// MARK: - Assets
|
|
631
|
+
|
|
632
|
+
/// In-flight asset transfers, keyed by record+field, so one can be
|
|
633
|
+
/// cancelled by name.
|
|
634
|
+
///
|
|
635
|
+
/// A `CKOperation` is cancellable, but only if someone kept a reference to
|
|
636
|
+
/// it. Without this the `ERR_CANCELLED` code in the shared error vocabulary
|
|
637
|
+
/// had no way of ever being produced, and a user who started a 500 MB
|
|
638
|
+
/// backup by mistake had to wait it out or kill the app.
|
|
639
|
+
private var activeAssetOperations: [String: CKOperation] = [:]
|
|
640
|
+
private let assetOperationLock = NSLock()
|
|
641
|
+
|
|
642
|
+
private static func transferKey(_ recordName: String, _ fieldName: String) -> String {
|
|
643
|
+
return "\(recordName)\u{0}\(fieldName)"
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
private func trackOperation(_ operation: CKOperation, recordName: String, fieldName: String) {
|
|
647
|
+
assetOperationLock.lock()
|
|
648
|
+
activeAssetOperations[Self.transferKey(recordName, fieldName)] = operation
|
|
649
|
+
assetOperationLock.unlock()
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
private func untrackOperation(recordName: String, fieldName: String) {
|
|
653
|
+
assetOperationLock.lock()
|
|
654
|
+
activeAssetOperations.removeValue(forKey: Self.transferKey(recordName, fieldName))
|
|
655
|
+
assetOperationLock.unlock()
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/// Cancels an in-flight `ckSaveAsset`/`ckFetchAsset`.
|
|
659
|
+
///
|
|
660
|
+
/// Resolves true when there was something to cancel. The cancelled
|
|
661
|
+
/// operation's own promise rejects with `ERR_CANCELLED`, since CloudKit
|
|
662
|
+
/// surfaces the cancellation as `CKError.operationCancelled`, which the
|
|
663
|
+
/// error mapper already recognises.
|
|
664
|
+
@objc public func ckCancelAsset(
|
|
665
|
+
_ recordName: String,
|
|
666
|
+
fieldName: String,
|
|
667
|
+
resolve: @escaping (Any?) -> Void,
|
|
668
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
669
|
+
) {
|
|
670
|
+
assetOperationLock.lock()
|
|
671
|
+
let operation = activeAssetOperations.removeValue(forKey: Self.transferKey(recordName, fieldName))
|
|
672
|
+
assetOperationLock.unlock()
|
|
673
|
+
|
|
674
|
+
guard let operation = operation else {
|
|
675
|
+
resolve(false)
|
|
676
|
+
return
|
|
677
|
+
}
|
|
678
|
+
operation.cancel()
|
|
679
|
+
resolve(true)
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/// Uploads a local file as a CKAsset field.
|
|
683
|
+
///
|
|
684
|
+
/// This is what makes values above the 1 MB record ceiling storable at all.
|
|
685
|
+
/// No library surveyed does this: `react-native-icloud-kit` cannot store
|
|
686
|
+
/// binary data (its field type is `string | number | null`), and
|
|
687
|
+
/// react-native-cloud-storage left binary support open for 15 months, during
|
|
688
|
+
/// which a user reported running out of memory base64-encoding files above
|
|
689
|
+
/// 20 MB by hand.
|
|
690
|
+
@objc public func ckSaveAsset(
|
|
691
|
+
_ recordType: String,
|
|
692
|
+
recordName: String,
|
|
693
|
+
fieldName: String,
|
|
694
|
+
fileUri: String,
|
|
695
|
+
zoneName: String?,
|
|
696
|
+
resolve: @escaping (Any?) -> Void,
|
|
697
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
698
|
+
) {
|
|
699
|
+
do {
|
|
700
|
+
let database = try requireDatabase()
|
|
701
|
+
let fileURL = Self.fileURL(from: fileUri)
|
|
702
|
+
|
|
703
|
+
guard FileManager.default.fileExists(atPath: fileURL.path) else {
|
|
704
|
+
let error = CloudSyncError.coded(
|
|
705
|
+
code: CloudSyncErrorCode.unknown,
|
|
706
|
+
message: "No file at \(fileURL.path)",
|
|
707
|
+
info: [:]
|
|
708
|
+
)
|
|
709
|
+
reject(error.code, error.message, error.asNSError)
|
|
710
|
+
return
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
let id = recordID(recordName, zoneName)
|
|
714
|
+
let record = CKRecord(recordType: recordType, recordID: id)
|
|
715
|
+
record[fieldName] = CKAsset(fileURL: fileURL)
|
|
716
|
+
|
|
717
|
+
// Sized once, not per callback - the progress block fires often.
|
|
718
|
+
let attributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path)
|
|
719
|
+
let totalBytes = (attributes?[.size] as? NSNumber)?.intValue ?? 0
|
|
720
|
+
|
|
721
|
+
// Stored alongside the asset so `ckFetchAsset` can learn the size
|
|
722
|
+
// before it starts downloading, and report real progress from the
|
|
723
|
+
// first callback instead of only once the transfer completes -
|
|
724
|
+
// CKAsset itself exposes no size until its bytes have landed.
|
|
725
|
+
record[Self.sizeField(fieldName)] = totalBytes as CKRecordValue
|
|
726
|
+
|
|
727
|
+
let operation = CKModifyRecordsOperation(recordsToSave: [record], recordIDsToDelete: nil)
|
|
728
|
+
operation.savePolicy = .changedKeys
|
|
729
|
+
|
|
730
|
+
// Progress is per-record; forward it so callers can drive a bar
|
|
731
|
+
// instead of guessing. react-native-cloud-storage reports a single
|
|
732
|
+
// global number with no file identity, which cannot be attributed
|
|
733
|
+
// when more than one upload is in flight.
|
|
734
|
+
operation.perRecordProgressBlock = { [weak self] _, progress in
|
|
735
|
+
self?.emit?("assetProgress", [
|
|
736
|
+
"recordName": recordName,
|
|
737
|
+
"fieldName": fieldName,
|
|
738
|
+
"bytesTransferred": Int(progress * Double(totalBytes)),
|
|
739
|
+
"bytesTotal": totalBytes,
|
|
740
|
+
])
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
operation.modifyRecordsResultBlock = { [weak self] result in
|
|
744
|
+
self?.untrackOperation(recordName: recordName, fieldName: fieldName)
|
|
745
|
+
switch result {
|
|
746
|
+
case .success:
|
|
747
|
+
resolve(nil)
|
|
748
|
+
case let .failure(error):
|
|
749
|
+
// A cancelled operation arrives here as
|
|
750
|
+
// CKError.operationCancelled, which the mapper turns into
|
|
751
|
+
// ERR_CANCELLED - so `ckCancelAsset` needs no special case.
|
|
752
|
+
let mapped = CloudSyncError.from(error)
|
|
753
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
trackOperation(operation, recordName: recordName, fieldName: fieldName)
|
|
757
|
+
database.add(operation)
|
|
758
|
+
} catch {
|
|
759
|
+
let mapped = CloudSyncError.from(error)
|
|
760
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/// Downloads a CKAsset field and resolves the local file path it landed at,
|
|
765
|
+
/// or nil when the record or field does not exist.
|
|
766
|
+
///
|
|
767
|
+
/// Uses `CKFetchRecordsOperation` rather than `database.fetch(withRecordID:)`
|
|
768
|
+
/// so the download reports progress the same way `ckSaveAsset` does - a
|
|
769
|
+
/// plain completion-handler fetch gives no callback until the whole asset
|
|
770
|
+
/// (which may be hundreds of MB) has already landed on disk. It first makes
|
|
771
|
+
/// a cheap metadata-only request for the size field `ckSaveAsset` stashes
|
|
772
|
+
/// next to the asset, so progress is reported in real bytes from the very
|
|
773
|
+
/// first callback rather than jumping from 0 to 100% at the end - `CKAsset`
|
|
774
|
+
/// itself exposes no size until its bytes have already landed.
|
|
775
|
+
/// - Parameter destinationUri: where to put the downloaded bytes. Pass nil
|
|
776
|
+
/// for a temporary path this module chooses.
|
|
777
|
+
///
|
|
778
|
+
/// Worth passing for anything the user is going to keep or hand to a
|
|
779
|
+
/// share sheet: the default lands in `NSTemporaryDirectory`, which iOS
|
|
780
|
+
/// may reclaim at any time, under a name the caller did not choose. That
|
|
781
|
+
/// is fine for "restore straight back into the app" and wrong for
|
|
782
|
+
/// "export my data", which is the case that needs a real path.
|
|
783
|
+
@objc public func ckFetchAsset(
|
|
784
|
+
_ recordName: String,
|
|
785
|
+
fieldName: String,
|
|
786
|
+
zoneName: String?,
|
|
787
|
+
destinationUri: String?,
|
|
788
|
+
resolve: @escaping (Any?) -> Void,
|
|
789
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
790
|
+
) {
|
|
791
|
+
do {
|
|
792
|
+
let database = try requireDatabase()
|
|
793
|
+
let id = recordID(recordName, zoneName)
|
|
794
|
+
|
|
795
|
+
fetchKnownSize(database: database, id: id, fieldName: fieldName) { [weak self] knownSize in
|
|
796
|
+
self?.fetchAsset(
|
|
797
|
+
database: database, id: id, recordName: recordName, fieldName: fieldName,
|
|
798
|
+
knownSize: knownSize, destinationUri: destinationUri,
|
|
799
|
+
resolve: resolve, reject: reject
|
|
800
|
+
)
|
|
801
|
+
}
|
|
802
|
+
} catch {
|
|
803
|
+
let mapped = CloudSyncError.from(error)
|
|
804
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/// Best-effort lookup of the size `ckSaveAsset` stored alongside the asset.
|
|
809
|
+
/// Never fails the caller - a missing size (an asset saved before this
|
|
810
|
+
/// field existed, or any other error) just means progress falls back to
|
|
811
|
+
/// reporting 0 until the transfer completes.
|
|
812
|
+
private func fetchKnownSize(
|
|
813
|
+
database: CKDatabase,
|
|
814
|
+
id: CKRecord.ID,
|
|
815
|
+
fieldName: String,
|
|
816
|
+
completion: @escaping (Int) -> Void
|
|
817
|
+
) {
|
|
818
|
+
let operation = CKFetchRecordsOperation(recordIDs: [id])
|
|
819
|
+
operation.desiredKeys = [Self.sizeField(fieldName)]
|
|
820
|
+
operation.perRecordResultBlock = { _, result in
|
|
821
|
+
guard case let .success(record) = result,
|
|
822
|
+
let size = record[Self.sizeField(fieldName)] as? Int else {
|
|
823
|
+
completion(0)
|
|
824
|
+
return
|
|
825
|
+
}
|
|
826
|
+
completion(size)
|
|
827
|
+
}
|
|
828
|
+
database.add(operation)
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
private func fetchAsset(
|
|
832
|
+
database: CKDatabase,
|
|
833
|
+
id: CKRecord.ID,
|
|
834
|
+
recordName: String,
|
|
835
|
+
fieldName: String,
|
|
836
|
+
knownSize: Int,
|
|
837
|
+
destinationUri: String?,
|
|
838
|
+
resolve: @escaping (Any?) -> Void,
|
|
839
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
840
|
+
) {
|
|
841
|
+
let operation = CKFetchRecordsOperation(recordIDs: [id])
|
|
842
|
+
var totalBytes = knownSize
|
|
843
|
+
|
|
844
|
+
operation.perRecordProgressBlock = { [weak self] _, progress in
|
|
845
|
+
guard let self = self, progress > 0 else { return }
|
|
846
|
+
self.emit?("assetProgress", [
|
|
847
|
+
"recordName": recordName,
|
|
848
|
+
"fieldName": fieldName,
|
|
849
|
+
"bytesTransferred": Int(progress * Double(totalBytes)),
|
|
850
|
+
"bytesTotal": totalBytes,
|
|
851
|
+
])
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
operation.perRecordResultBlock = { [weak self] _, result in
|
|
855
|
+
switch result {
|
|
856
|
+
case let .success(record):
|
|
857
|
+
guard let asset = record[fieldName] as? CKAsset,
|
|
858
|
+
let url = asset.fileURL else {
|
|
859
|
+
resolve(nil)
|
|
860
|
+
return
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
if totalBytes == 0 {
|
|
864
|
+
let attributes = try? FileManager.default.attributesOfItem(atPath: url.path)
|
|
865
|
+
totalBytes = (attributes?[.size] as? NSNumber)?.intValue ?? 0
|
|
866
|
+
}
|
|
867
|
+
self?.emit?("assetProgress", [
|
|
868
|
+
"recordName": recordName,
|
|
869
|
+
"fieldName": fieldName,
|
|
870
|
+
"bytesTransferred": totalBytes,
|
|
871
|
+
"bytesTotal": totalBytes,
|
|
872
|
+
])
|
|
873
|
+
|
|
874
|
+
// CloudKit stores the download in a temporary location it
|
|
875
|
+
// may reclaim, so copy it somewhere the caller controls
|
|
876
|
+
// before handing back a path.
|
|
877
|
+
let destination = destinationUri.map { Self.fileURL(from: $0) }
|
|
878
|
+
?? FileManager.default.temporaryDirectory
|
|
879
|
+
.appendingPathComponent("rncs-\(recordName)-\(fieldName)")
|
|
880
|
+
do {
|
|
881
|
+
// Create the parent directory when the caller named a path
|
|
882
|
+
// inside one that does not exist yet - a copy into a missing
|
|
883
|
+
// directory fails, and making them create it first would be
|
|
884
|
+
// a pointless extra step in every export flow.
|
|
885
|
+
let parent = destination.deletingLastPathComponent()
|
|
886
|
+
if !FileManager.default.fileExists(atPath: parent.path) {
|
|
887
|
+
try FileManager.default.createDirectory(
|
|
888
|
+
at: parent, withIntermediateDirectories: true
|
|
889
|
+
)
|
|
890
|
+
}
|
|
891
|
+
if FileManager.default.fileExists(atPath: destination.path) {
|
|
892
|
+
try FileManager.default.removeItem(at: destination)
|
|
893
|
+
}
|
|
894
|
+
try FileManager.default.copyItem(at: url, to: destination)
|
|
895
|
+
resolve(destination.absoluteString)
|
|
896
|
+
} catch {
|
|
897
|
+
let mapped = CloudSyncError.from(error)
|
|
898
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
899
|
+
}
|
|
900
|
+
case let .failure(error):
|
|
901
|
+
if let ckError = error as? CKError, ckError.code == .unknownItem {
|
|
902
|
+
resolve(nil)
|
|
903
|
+
return
|
|
904
|
+
}
|
|
905
|
+
let mapped = CloudSyncError.from(error)
|
|
906
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
operation.fetchRecordsResultBlock = { [weak self] result in
|
|
911
|
+
self?.untrackOperation(recordName: recordName, fieldName: fieldName)
|
|
912
|
+
if case let .failure(error) = result {
|
|
913
|
+
// A per-record failure already resolved/rejected above; this
|
|
914
|
+
// only fires for operation-level failures (e.g. the record
|
|
915
|
+
// simply not existing surfaces here rather than per-record
|
|
916
|
+
// on some CloudKit versions), so guard against double-resolving.
|
|
917
|
+
if let ckError = error as? CKError, ckError.code == .unknownItem {
|
|
918
|
+
resolve(nil)
|
|
919
|
+
return
|
|
920
|
+
}
|
|
921
|
+
let mapped = CloudSyncError.from(error)
|
|
922
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
trackOperation(operation, recordName: recordName, fieldName: fieldName)
|
|
927
|
+
database.add(operation)
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
/// Accepts both `file://` URLs and bare paths, since callers pass whichever
|
|
931
|
+
/// their file-system library produced.
|
|
932
|
+
static func fileURL(from uri: String) -> URL {
|
|
933
|
+
if uri.hasPrefix("file://"), let url = URL(string: uri) { return url }
|
|
934
|
+
return URL(fileURLWithPath: uri)
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// MARK: - iCloud Drive documents
|
|
938
|
+
//
|
|
939
|
+
// The ubiquity container's `Documents` directory: real files, in the user's
|
|
940
|
+
// own iCloud Drive, visible in Files.app when the app declares
|
|
941
|
+
// `NSUbiquitousContainers` with `NSUbiquitousContainerIsDocumentScopePublic`.
|
|
942
|
+
//
|
|
943
|
+
// Distinct from everything else in this file, and worth being clear about
|
|
944
|
+
// why both exist. A `CKAsset` lives in the app's private CloudKit database:
|
|
945
|
+
// the user cannot see it, open it, or hand it to another app. That is right
|
|
946
|
+
// for an internal backup blob and wrong for an export the user asked for.
|
|
947
|
+
// "Save my file where I can find it" is the single most common iCloud
|
|
948
|
+
// request in mobile apps and no `CKRecord` API can answer it.
|
|
949
|
+
|
|
950
|
+
/// The container root. Blocking - Apple documents this as slow enough that
|
|
951
|
+
/// it must not be called on the main thread, so every caller here hops to a
|
|
952
|
+
/// background queue first.
|
|
953
|
+
private func ubiquityContainerURL() -> URL? {
|
|
954
|
+
return FileManager.default.url(
|
|
955
|
+
forUbiquityContainerIdentifier: Self.resolveContainerIdentifier()
|
|
956
|
+
)
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/// The user-visible subdirectory. Only `Documents` is ever exposed in
|
|
960
|
+
/// Files.app; anything written beside it stays hidden from the user, which
|
|
961
|
+
/// would defeat the point of this API.
|
|
962
|
+
private func documentsURL() throws -> URL {
|
|
963
|
+
guard let container = ubiquityContainerURL() else {
|
|
964
|
+
throw CloudSyncError.coded(
|
|
965
|
+
code: CloudSyncErrorCode.containerMisconfigured,
|
|
966
|
+
message: "No iCloud Drive container is available. Check the iCloud capability, "
|
|
967
|
+
+ "the iCloud Documents service, and that the user is signed in.",
|
|
968
|
+
info: [:]
|
|
969
|
+
)
|
|
970
|
+
}
|
|
971
|
+
let documents = container.appendingPathComponent("Documents", isDirectory: true)
|
|
972
|
+
if !FileManager.default.fileExists(atPath: documents.path) {
|
|
973
|
+
try FileManager.default.createDirectory(
|
|
974
|
+
at: documents, withIntermediateDirectories: true
|
|
975
|
+
)
|
|
976
|
+
}
|
|
977
|
+
return documents
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/// True when the device has a usable iCloud Drive container right now.
|
|
981
|
+
@objc public func docIsAvailable(
|
|
982
|
+
resolve: @escaping (Any?) -> Void,
|
|
983
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
984
|
+
) {
|
|
985
|
+
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
|
986
|
+
resolve(self?.ubiquityContainerURL() != nil)
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/// Copies a local file into iCloud Drive under `name`, replacing whatever
|
|
991
|
+
/// was there, and resolves the resulting iCloud path.
|
|
992
|
+
///
|
|
993
|
+
/// Upload happens in the background, managed by the system: once the file is
|
|
994
|
+
/// in the container, iOS syncs it whether or not the app is running. So a
|
|
995
|
+
/// resolved promise means "handed to iCloud", not "in the cloud" - the same
|
|
996
|
+
/// distinction `kvSync` carries, and callers are told so in the JS docs.
|
|
997
|
+
@objc public func docSave(
|
|
998
|
+
_ fileUri: String,
|
|
999
|
+
name: String,
|
|
1000
|
+
resolve: @escaping (Any?) -> Void,
|
|
1001
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
1002
|
+
) {
|
|
1003
|
+
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
|
1004
|
+
guard let self = self else { return }
|
|
1005
|
+
do {
|
|
1006
|
+
let source = Self.fileURL(from: fileUri)
|
|
1007
|
+
guard FileManager.default.fileExists(atPath: source.path) else {
|
|
1008
|
+
throw CloudSyncError.coded(
|
|
1009
|
+
code: CloudSyncErrorCode.unknown,
|
|
1010
|
+
message: "No file at \(source.path)",
|
|
1011
|
+
info: [:]
|
|
1012
|
+
)
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
let destination = try self.documentsURL().appendingPathComponent(name)
|
|
1016
|
+
|
|
1017
|
+
// Coordinated, because iCloud Drive files are shared with the
|
|
1018
|
+
// system daemon and with other processes. An uncoordinated write
|
|
1019
|
+
// can be interleaved with a sync and produce a corrupt file.
|
|
1020
|
+
var coordinationError: NSError?
|
|
1021
|
+
var writeError: Error?
|
|
1022
|
+
NSFileCoordinator().coordinate(
|
|
1023
|
+
writingItemAt: destination,
|
|
1024
|
+
options: .forReplacing,
|
|
1025
|
+
error: &coordinationError
|
|
1026
|
+
) { url in
|
|
1027
|
+
do {
|
|
1028
|
+
if FileManager.default.fileExists(atPath: url.path) {
|
|
1029
|
+
try FileManager.default.removeItem(at: url)
|
|
1030
|
+
}
|
|
1031
|
+
try FileManager.default.copyItem(at: source, to: url)
|
|
1032
|
+
} catch {
|
|
1033
|
+
writeError = error
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
if let error = coordinationError ?? writeError { throw error }
|
|
1038
|
+
resolve(destination.absoluteString)
|
|
1039
|
+
} catch {
|
|
1040
|
+
let mapped = CloudSyncError.from(error)
|
|
1041
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/// Ensures `name` is downloaded locally and resolves its path, or nil when
|
|
1047
|
+
/// there is no such file.
|
|
1048
|
+
///
|
|
1049
|
+
/// A file in iCloud Drive may exist as a placeholder with no local bytes -
|
|
1050
|
+
/// the user has it, this device does not. Reading it without downloading
|
|
1051
|
+
/// first yields an empty or missing file, which is the trap this method
|
|
1052
|
+
/// exists to close: it asks for the download, then waits for the status to
|
|
1053
|
+
/// become `.current` before answering.
|
|
1054
|
+
@objc public func docFetch(
|
|
1055
|
+
_ name: String,
|
|
1056
|
+
destinationUri: String?,
|
|
1057
|
+
timeoutMs: NSNumber,
|
|
1058
|
+
resolve: @escaping (Any?) -> Void,
|
|
1059
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
1060
|
+
) {
|
|
1061
|
+
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
|
1062
|
+
guard let self = self else { return }
|
|
1063
|
+
do {
|
|
1064
|
+
let source = try self.documentsURL().appendingPathComponent(name)
|
|
1065
|
+
|
|
1066
|
+
guard FileManager.default.fileExists(atPath: source.path)
|
|
1067
|
+
|| self.placeholderExists(for: source) else {
|
|
1068
|
+
resolve(nil)
|
|
1069
|
+
return
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
try FileManager.default.startDownloadingUbiquitousItem(at: source)
|
|
1073
|
+
|
|
1074
|
+
let deadline = Date().addingTimeInterval(timeoutMs.doubleValue / 1000)
|
|
1075
|
+
while !self.isDownloaded(source) {
|
|
1076
|
+
if Date() >= deadline {
|
|
1077
|
+
throw CloudSyncError.coded(
|
|
1078
|
+
code: CloudSyncErrorCode.timeout,
|
|
1079
|
+
message: "'\(name)' did not finish downloading from iCloud Drive in "
|
|
1080
|
+
+ "\(timeoutMs.intValue)ms. It is still downloading in the "
|
|
1081
|
+
+ "background; try again shortly.",
|
|
1082
|
+
info: [:]
|
|
1083
|
+
)
|
|
1084
|
+
}
|
|
1085
|
+
// Polled rather than driven by NSMetadataQuery: a query needs
|
|
1086
|
+
// a live run loop, and this method is deliberately callable
|
|
1087
|
+
// from a background queue. The cost is that progress is not
|
|
1088
|
+
// reported byte by byte - see the JS docs, which say so
|
|
1089
|
+
// rather than inventing a number.
|
|
1090
|
+
Thread.sleep(forTimeInterval: 0.25)
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
guard let destinationUri = destinationUri else {
|
|
1094
|
+
resolve(source.absoluteString)
|
|
1095
|
+
return
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
// Copy out of the container when the caller named a destination,
|
|
1099
|
+
// so they get a file the system will not later evict.
|
|
1100
|
+
let destination = Self.fileURL(from: destinationUri)
|
|
1101
|
+
if FileManager.default.fileExists(atPath: destination.path) {
|
|
1102
|
+
try FileManager.default.removeItem(at: destination)
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
var coordinationError: NSError?
|
|
1106
|
+
var copyError: Error?
|
|
1107
|
+
NSFileCoordinator().coordinate(
|
|
1108
|
+
readingItemAt: source, options: [], error: &coordinationError
|
|
1109
|
+
) { url in
|
|
1110
|
+
do {
|
|
1111
|
+
try FileManager.default.copyItem(at: url, to: destination)
|
|
1112
|
+
} catch {
|
|
1113
|
+
copyError = error
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
if let error = coordinationError ?? copyError { throw error }
|
|
1117
|
+
|
|
1118
|
+
resolve(destination.absoluteString)
|
|
1119
|
+
} catch {
|
|
1120
|
+
let mapped = CloudSyncError.from(error)
|
|
1121
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/// Whether the local copy is current, i.e. safe to read.
|
|
1127
|
+
private func isDownloaded(_ url: URL) -> Bool {
|
|
1128
|
+
let values = try? url.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey])
|
|
1129
|
+
guard let status = values?.ubiquitousItemDownloadingStatus else {
|
|
1130
|
+
// Not a ubiquitous item at all - a plain local file, already usable.
|
|
1131
|
+
return FileManager.default.fileExists(atPath: url.path)
|
|
1132
|
+
}
|
|
1133
|
+
return status == .current
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
/// A not-yet-downloaded item is on disk as a hidden `.name.icloud` stub, so
|
|
1137
|
+
/// "the file does not exist" and "the file exists but is not here yet" have
|
|
1138
|
+
/// to be told apart before reporting an absence.
|
|
1139
|
+
private func placeholderExists(for url: URL) -> Bool {
|
|
1140
|
+
let placeholder = url
|
|
1141
|
+
.deletingLastPathComponent()
|
|
1142
|
+
.appendingPathComponent(".\(url.lastPathComponent).icloud")
|
|
1143
|
+
return FileManager.default.fileExists(atPath: placeholder.path)
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
/// Everything in the app's iCloud Drive folder, including items that exist
|
|
1147
|
+
/// in the account but have no local copy on this device yet.
|
|
1148
|
+
@objc public func docList(
|
|
1149
|
+
resolve: @escaping (Any?) -> Void,
|
|
1150
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
1151
|
+
) {
|
|
1152
|
+
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
|
1153
|
+
guard let self = self else { return }
|
|
1154
|
+
do {
|
|
1155
|
+
let documents = try self.documentsURL()
|
|
1156
|
+
let entries = try FileManager.default.contentsOfDirectory(
|
|
1157
|
+
at: documents,
|
|
1158
|
+
includingPropertiesForKeys: [
|
|
1159
|
+
.fileSizeKey,
|
|
1160
|
+
.ubiquitousItemDownloadingStatusKey,
|
|
1161
|
+
.ubiquitousItemIsDownloadingKey,
|
|
1162
|
+
],
|
|
1163
|
+
options: []
|
|
1164
|
+
)
|
|
1165
|
+
|
|
1166
|
+
var seen = Set<String>()
|
|
1167
|
+
var result: [[String: Any]] = []
|
|
1168
|
+
|
|
1169
|
+
for url in entries {
|
|
1170
|
+
// Fold the hidden placeholder back onto the name it stands
|
|
1171
|
+
// for, so a caller sees one entry per file rather than two
|
|
1172
|
+
// and never sees a `.icloud` name it cannot ask for.
|
|
1173
|
+
let name = Self.displayName(for: url)
|
|
1174
|
+
if seen.contains(name) { continue }
|
|
1175
|
+
seen.insert(name)
|
|
1176
|
+
|
|
1177
|
+
let values = try? url.resourceValues(forKeys: [
|
|
1178
|
+
.fileSizeKey,
|
|
1179
|
+
.ubiquitousItemDownloadingStatusKey,
|
|
1180
|
+
.ubiquitousItemIsDownloadingKey,
|
|
1181
|
+
])
|
|
1182
|
+
let status = values?.ubiquitousItemDownloadingStatus
|
|
1183
|
+
result.append([
|
|
1184
|
+
"name": name,
|
|
1185
|
+
"sizeBytes": values?.fileSize ?? 0,
|
|
1186
|
+
"isDownloaded": status == nil || status == .current,
|
|
1187
|
+
"isDownloading": values?.ubiquitousItemIsDownloading ?? false,
|
|
1188
|
+
])
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
resolve(result)
|
|
1192
|
+
} catch {
|
|
1193
|
+
let mapped = CloudSyncError.from(error)
|
|
1194
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
/// `.Report.pdf.icloud` -> `Report.pdf`; anything else unchanged.
|
|
1200
|
+
static func displayName(for url: URL) -> String {
|
|
1201
|
+
let last = url.lastPathComponent
|
|
1202
|
+
guard last.hasPrefix("."), last.hasSuffix(".icloud") else { return last }
|
|
1203
|
+
return String(last.dropFirst().dropLast(".icloud".count))
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
/// Deletes a file from iCloud Drive, on every device.
|
|
1207
|
+
@objc public func docRemove(
|
|
1208
|
+
_ name: String,
|
|
1209
|
+
resolve: @escaping (Any?) -> Void,
|
|
1210
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
1211
|
+
) {
|
|
1212
|
+
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
|
1213
|
+
guard let self = self else { return }
|
|
1214
|
+
do {
|
|
1215
|
+
let target = try self.documentsURL().appendingPathComponent(name)
|
|
1216
|
+
guard FileManager.default.fileExists(atPath: target.path)
|
|
1217
|
+
|| self.placeholderExists(for: target) else {
|
|
1218
|
+
// Already gone is the end state the caller asked for.
|
|
1219
|
+
resolve(false)
|
|
1220
|
+
return
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
var coordinationError: NSError?
|
|
1224
|
+
var removeError: Error?
|
|
1225
|
+
NSFileCoordinator().coordinate(
|
|
1226
|
+
writingItemAt: target, options: .forDeleting, error: &coordinationError
|
|
1227
|
+
) { url in
|
|
1228
|
+
do {
|
|
1229
|
+
try FileManager.default.removeItem(at: url)
|
|
1230
|
+
} catch {
|
|
1231
|
+
removeError = error
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
if let error = coordinationError ?? removeError { throw error }
|
|
1235
|
+
|
|
1236
|
+
resolve(true)
|
|
1237
|
+
} catch {
|
|
1238
|
+
let mapped = CloudSyncError.from(error)
|
|
1239
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
@objc public func ckListZones(
|
|
1245
|
+
resolve: @escaping (Any?) -> Void,
|
|
1246
|
+
reject: @escaping (String, String, NSError?) -> Void
|
|
1247
|
+
) {
|
|
1248
|
+
do {
|
|
1249
|
+
let database = try requireDatabase()
|
|
1250
|
+
database.fetchAllRecordZones { zones, error in
|
|
1251
|
+
if let error = error {
|
|
1252
|
+
let mapped = CloudSyncError.from(error)
|
|
1253
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
1254
|
+
return
|
|
1255
|
+
}
|
|
1256
|
+
resolve((zones ?? []).map { $0.zoneID.zoneName })
|
|
1257
|
+
}
|
|
1258
|
+
} catch {
|
|
1259
|
+
let mapped = CloudSyncError.from(error)
|
|
1260
|
+
reject(mapped.code, mapped.message, mapped.asNSError)
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
}
|