Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / ICloudBackup.swift

Raw 2.6 KB on 8f75dd7d901e2186ca9d9e1cf2f061105c02ae42
1import Foundation
2
3enum ICloudBackup {
4 enum UploadStatus: Equatable, Sendable {
5 case waiting, uploaded, unavailable, excluded, failed(String)
6 }
7
8 static var drive: URL {
9 FileManager.default.homeDirectoryForCurrentUser
10 .appending(path: "Library/Mobile Documents/com~apple~CloudDocs", directoryHint: .isDirectory)
11 }
12
13 static func uploadStatus(of url: URL) -> UploadStatus? {
14 let root = drive.resolvingSymlinksInPath().standardizedFileURL.pathComponents
15 let path = url.resolvingSymlinksInPath().standardizedFileURL.pathComponents
16 let metadata = try? url.resourceValues(forKeys: [.isUbiquitousItemKey, .ubiquitousItemIsUploadedKey,
17 .ubiquitousItemIsExcludedFromSyncKey, .ubiquitousItemUploadingErrorKey])
18 return uploadStatus(inDrive: path.starts(with: root), available: metadata != nil,
19 ubiquitous: metadata?.isUbiquitousItem == true,
20 uploaded: metadata?.ubiquitousItemIsUploaded == true,
21 excluded: metadata?.ubiquitousItemIsExcludedFromSync == true,
22 error: metadata?.ubiquitousItemUploadingError?.localizedDescription)
23 }
24
25 static func uploadStatus(inDrive: Bool, available: Bool, ubiquitous: Bool, uploaded: Bool,
26 excluded: Bool, error: String?) -> UploadStatus? {
27 guard inDrive || ubiquitous else { return nil }
28 guard available else { return .unavailable }
29 if excluded { return .excluded }
30 if let error { return .failed(error) }
31 return ubiquitous && uploaded ? .uploaded : .waiting
32 }
33
34 static func downloadIfNeeded(_ url: URL) async throws {
35 let keys: Set<URLResourceKey> = [.ubiquitousItemDownloadingStatusKey, .ubiquitousItemDownloadingErrorKey]
36 guard (try? url.resourceValues(forKeys: keys).ubiquitousItemDownloadingStatus) == .notDownloaded else { return }
37 try FileManager.default.startDownloadingUbiquitousItem(at: url)
38 let deadline = ContinuousClock.now + .seconds(90)
39 while ContinuousClock.now < deadline {
40 try Task.checkCancellation()
41 let freshURL = URL(fileURLWithPath: url.path)
42 let status = try freshURL.resourceValues(forKeys: keys)
43 if let error = status.ubiquitousItemDownloadingError { throw error }
44 if status.ubiquitousItemDownloadingStatus == .current { return }
45 try await Task.sleep(for: .seconds(1))
46 }
47 throw WorkspaceError("iCloud hasn’t finished downloading this backup. Check its status in Finder and try again.")
48 }
49}