|
| 1 | +import Foundation |
| 2 | +import React |
| 3 | + |
| 4 | +@objc(ICloudBackupModule) |
| 5 | +class ICloudBackupModule: NSObject { |
| 6 | + @objc static func requiresMainQueueSetup() -> Bool { |
| 7 | + return false |
| 8 | + } |
| 9 | + |
| 10 | + /// Resolves the app's iCloud Drive container Documents directory, creating |
| 11 | + /// it if needed. Resolves null when iCloud is unavailable (signed out, iCloud |
| 12 | + /// Drive disabled, or missing entitlement) - callers treat that as "backup |
| 13 | + /// unavailable", never as an error. |
| 14 | + @objc |
| 15 | + func getContainerPath(_ resolver: @escaping RCTPromiseResolveBlock, |
| 16 | + rejecter: @escaping RCTPromiseRejectBlock) { |
| 17 | + DispatchQueue.global(qos: .utility).async { |
| 18 | + guard let containerUrl = FileManager.default.url(forUbiquityContainerIdentifier: nil) else { |
| 19 | + resolver(NSNull()) |
| 20 | + return |
| 21 | + } |
| 22 | + let documentsUrl = containerUrl.appendingPathComponent("Documents", isDirectory: true) |
| 23 | + do { |
| 24 | + try FileManager.default.createDirectory( |
| 25 | + at: documentsUrl, |
| 26 | + withIntermediateDirectories: true |
| 27 | + ) |
| 28 | + } catch { |
| 29 | + rejecter("E_CONTAINER_DIR", "Could not create iCloud Documents directory", error) |
| 30 | + return |
| 31 | + } |
| 32 | + resolver(documentsUrl.path) |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + /// File operations below use FileManager because expo-file-system refuses |
| 37 | + /// paths outside the app sandbox scopes - which includes the ubiquity |
| 38 | + /// container. All backup-side I/O must therefore go through this module. |
| 39 | + |
| 40 | + @objc |
| 41 | + func copyItem(_ from: String, to: String, |
| 42 | + resolver: @escaping RCTPromiseResolveBlock, |
| 43 | + rejecter: @escaping RCTPromiseRejectBlock) { |
| 44 | + DispatchQueue.global(qos: .utility).async { |
| 45 | + let fromUrl = URL(fileURLWithPath: Self.plainPath(from)) |
| 46 | + let toUrl = URL(fileURLWithPath: Self.plainPath(to)) |
| 47 | + do { |
| 48 | + try FileManager.default.createDirectory( |
| 49 | + at: toUrl.deletingLastPathComponent(), |
| 50 | + withIntermediateDirectories: true |
| 51 | + ) |
| 52 | + if FileManager.default.fileExists(atPath: toUrl.path) { |
| 53 | + try FileManager.default.removeItem(at: toUrl) |
| 54 | + } |
| 55 | + try FileManager.default.copyItem(at: fromUrl, to: toUrl) |
| 56 | + resolver(true) |
| 57 | + } catch { |
| 58 | + rejecter("E_COPY", "Copy failed: \(fromUrl.lastPathComponent)", error) |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + @objc |
| 64 | + func writeFileAtomic(_ path: String, contents: String, |
| 65 | + resolver: @escaping RCTPromiseResolveBlock, |
| 66 | + rejecter: @escaping RCTPromiseRejectBlock) { |
| 67 | + DispatchQueue.global(qos: .utility).async { |
| 68 | + let url = URL(fileURLWithPath: Self.plainPath(path)) |
| 69 | + do { |
| 70 | + try FileManager.default.createDirectory( |
| 71 | + at: url.deletingLastPathComponent(), |
| 72 | + withIntermediateDirectories: true |
| 73 | + ) |
| 74 | + try contents.write(to: url, atomically: true, encoding: .utf8) |
| 75 | + resolver(true) |
| 76 | + } catch { |
| 77 | + rejecter("E_WRITE", "Write failed: \(url.lastPathComponent)", error) |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + @objc |
| 83 | + func readFileAsString(_ path: String, |
| 84 | + resolver: @escaping RCTPromiseResolveBlock, |
| 85 | + rejecter: @escaping RCTPromiseRejectBlock) { |
| 86 | + DispatchQueue.global(qos: .utility).async { |
| 87 | + let url = URL(fileURLWithPath: Self.plainPath(path)) |
| 88 | + guard FileManager.default.fileExists(atPath: url.path) else { |
| 89 | + resolver(NSNull()) |
| 90 | + return |
| 91 | + } |
| 92 | + do { |
| 93 | + resolver(try String(contentsOf: url, encoding: .utf8)) |
| 94 | + } catch { |
| 95 | + rejecter("E_READ", "Read failed: \(url.lastPathComponent)", error) |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + @objc |
| 101 | + func deleteItem(_ path: String, |
| 102 | + resolver: @escaping RCTPromiseResolveBlock, |
| 103 | + rejecter: @escaping RCTPromiseRejectBlock) { |
| 104 | + DispatchQueue.global(qos: .utility).async { |
| 105 | + let url = URL(fileURLWithPath: Self.plainPath(path)) |
| 106 | + do { |
| 107 | + if FileManager.default.fileExists(atPath: url.path) { |
| 108 | + try FileManager.default.removeItem(at: url) |
| 109 | + } |
| 110 | + resolver(true) |
| 111 | + } catch { |
| 112 | + rejecter("E_DELETE", "Delete failed: \(url.lastPathComponent)", error) |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + /// Lists every regular file under `dir` recursively. Returns |
| 118 | + /// [{ rel, size, mtimeMs }] with `rel` relative to `dir`. |
| 119 | + @objc |
| 120 | + func listFilesRecursive(_ dir: String, |
| 121 | + resolver: @escaping RCTPromiseResolveBlock, |
| 122 | + rejecter: @escaping RCTPromiseRejectBlock) { |
| 123 | + DispatchQueue.global(qos: .utility).async { |
| 124 | + let baseUrl = URL(fileURLWithPath: Self.plainPath(dir)) |
| 125 | + guard FileManager.default.fileExists(atPath: baseUrl.path) else { |
| 126 | + resolver([]) |
| 127 | + return |
| 128 | + } |
| 129 | + guard let enumerator = FileManager.default.enumerator( |
| 130 | + at: baseUrl, |
| 131 | + includingPropertiesForKeys: [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey] |
| 132 | + ) else { |
| 133 | + resolver([]) |
| 134 | + return |
| 135 | + } |
| 136 | + var out: [[String: Any]] = [] |
| 137 | + let basePath = baseUrl.path.hasSuffix("/") ? baseUrl.path : baseUrl.path + "/" |
| 138 | + for case let fileUrl as URL in enumerator { |
| 139 | + guard let values = try? fileUrl.resourceValues( |
| 140 | + forKeys: [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey] |
| 141 | + ), values.isRegularFile == true else { continue } |
| 142 | + guard fileUrl.path.hasPrefix(basePath) else { continue } |
| 143 | + let rel = String(fileUrl.path.dropFirst(basePath.count)) |
| 144 | + let mtimeMs = (values.contentModificationDate?.timeIntervalSince1970 ?? 0) * 1000 |
| 145 | + out.append([ |
| 146 | + "rel": rel, |
| 147 | + "size": values.fileSize ?? 0, |
| 148 | + "mtimeMs": Int(mtimeMs.rounded()), |
| 149 | + ]) |
| 150 | + } |
| 151 | + resolver(out) |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + private static func plainPath(_ path: String) -> String { |
| 156 | + if path.hasPrefix("file://"), let url = URL(string: path) { |
| 157 | + return url.path |
| 158 | + } |
| 159 | + return path |
| 160 | + } |
| 161 | + |
| 162 | + /// Ensures a file in the ubiquity container is downloaded locally (iCloud |
| 163 | + /// may have evicted it). Resolves true when the file is readable, false when |
| 164 | + /// the download did not complete within the timeout. |
| 165 | + @objc |
| 166 | + func ensureDownloaded(_ path: String, |
| 167 | + timeoutMs: NSNumber, |
| 168 | + resolver: @escaping RCTPromiseResolveBlock, |
| 169 | + rejecter: @escaping RCTPromiseRejectBlock) { |
| 170 | + DispatchQueue.global(qos: .utility).async { |
| 171 | + let url = URL(fileURLWithPath: Self.plainPath(path)) |
| 172 | + let fileManager = FileManager.default |
| 173 | + |
| 174 | + if fileManager.fileExists(atPath: url.path) { |
| 175 | + resolver(true) |
| 176 | + return |
| 177 | + } |
| 178 | + |
| 179 | + // A not-yet-downloaded ubiquitous file appears as ".<name>.icloud". |
| 180 | + let placeholderName = ".\(url.lastPathComponent).icloud" |
| 181 | + let placeholderUrl = url.deletingLastPathComponent().appendingPathComponent(placeholderName) |
| 182 | + guard fileManager.fileExists(atPath: placeholderUrl.path) else { |
| 183 | + resolver(false) |
| 184 | + return |
| 185 | + } |
| 186 | + |
| 187 | + do { |
| 188 | + try fileManager.startDownloadingUbiquitousItem(at: url) |
| 189 | + } catch { |
| 190 | + rejecter("E_DOWNLOAD_START", "Could not start iCloud download for \(url.lastPathComponent)", error) |
| 191 | + return |
| 192 | + } |
| 193 | + |
| 194 | + let deadline = Date().addingTimeInterval(timeoutMs.doubleValue / 1000.0) |
| 195 | + while Date() < deadline { |
| 196 | + if fileManager.fileExists(atPath: url.path) { |
| 197 | + resolver(true) |
| 198 | + return |
| 199 | + } |
| 200 | + Thread.sleep(forTimeInterval: 0.2) |
| 201 | + } |
| 202 | + resolver(false) |
| 203 | + } |
| 204 | + } |
| 205 | +} |
0 commit comments