1import UIKit
2
3/// Lists the conflict versions iCloud Drive keeps beside a section file, as it keeps another
4/// device's commit that lost; the library merges each into the file. None while the file is a
5/// copy iCloud has yet to replace with a newer one, which a version must not be retired against.
6private let listVersions: sb_versions = { path, found, context in
7 guard let path, let found else { return }
8 let url = URL(fileURLWithPath: String(cString: path))
9 let status = try? url.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey])
10 if let status = status?.ubiquitousItemDownloadingStatus, status != .current { return }
11 for version in NSFileVersion.unresolvedConflictVersionsOfItem(at: url) ?? [] {
12 version.url.path.withCString { id in
13 guard let device = version.localizedNameOfSavingComputer else { return found(context, id, nil) }
14 device.withCString { found(context, id, $0) }
15 }
16 }
17}
18
19/// Resolves and removes a version the library merged, first keeping it beside the file as
20/// “Name (Device).one” when it is another section. A version already gone, as another device
21/// resolved it, is done.
22private let retireVersion: sb_retire = { path, id, keep in
23 guard let path, let id else { return false }
24 let url = URL(fileURLWithPath: String(cString: path))
25 let named = String(cString: id)
26 guard let version = NSFileVersion.unresolvedConflictVersionsOfItem(at: url)?.first(where: { $0.url.path == named })
27 else { return true }
28 var retired = false
29 var error: NSError?
30 NSFileCoordinator().coordinate(writingItemAt: url, options: .forMerging, error: &error) { url in
31 if keep {
32 let device = version.localizedNameOfSavingComputer ?? "another device"
33 let stem = url.deletingPathExtension().lastPathComponent
34 let folder = url.deletingLastPathComponent()
35 let kept = (1...).lazy.map { n in
36 folder.appendingPathComponent(n == 1 ? "\(stem) (\(device)).one" : "\(stem) (\(device) \(n)).one")
37 }.first { !FileManager.default.fileExists(atPath: $0.path) }
38 guard let kept, (try? FileManager.default.copyItem(at: version.url, to: kept)) != nil else { return }
39 }
40 version.isResolved = true
41 retired = (try? version.remove()) != nil
42 }
43 return retired
44}
45
46/// Snowbound's folder in iCloud Drive: its container's Documents, which Files shows as iCloud
47/// Drive's Snowbound folder.
48enum ICloud {
49 /// Sent on the main thread when the folder was looked up again.
50 static let changed = Notification.Name("ICloudChanged")
51 private static let identifier = "iCloud.net.paperclover.snowbound"
52
53 /// The folder, once looked up; nil while iCloud Drive is off, signed out, or the app lacks
54 /// the container.
55 private(set) static var documents: URL?
56
57 /// Tooling launched the app, naming a `SNOWBOUND_` variable such as `SNOWBOUND_SCRIPT`: it
58 /// reaches no account's iCloud, only the folder `SNOWBOUND_ICLOUD` names.
59 private static let automated = ProcessInfo.processInfo.environment.keys.contains { $0.hasPrefix("SNOWBOUND_") }
60
61 /// Whether iCloud is signed in with iCloud Drive on, container or not.
62 static var signedIn: Bool { FileManager.default.ubiquityIdentityToken != nil }
63
64 /// Has the library merge conflict versions and this device's uploads iCloud Drive lost,
65 /// follows the account, and hears of notebooks another device adds or removes; call once
66 /// at launch.
67 static func start() {
68 sb_set_versions(listVersions, retireVersion, UIDevice.current.name)
69 if automated { return lookUp() }
70 NotificationCenter.default.addObserver(
71 forName: .NSUbiquityIdentityDidChange, object: nil, queue: .main
72 ) { _ in lookUp() }
73 lookUp()
74 query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
75 query.predicate = NSPredicate(format: "%K LIKE '*'", NSMetadataItemFSNameKey)
76 for name in [Notification.Name.NSMetadataQueryDidFinishGathering, .NSMetadataQueryDidUpdate] {
77 NotificationCenter.default.addObserver(forName: name, object: query, queue: .main) { _ in
78 if Notebooks.inCloudChanged { NotificationCenter.default.post(name: changed, object: nil) }
79 }
80 }
81 query.start()
82 }
83
84 /// Reports what iCloud Drive syncs of the container, as files come from other devices.
85 private static let query = NSMetadataQuery()
86
87 /// Looks the folder up off the main thread, as asking iCloud can take a while.
88 static func lookUp() {
89 background({ () -> URL? in
90 #if DEBUG
91 // A simulator signs into no account; `SNOWBOUND_ICLOUD` names a folder standing in.
92 if let folder = ProcessInfo.processInfo.environment["SNOWBOUND_ICLOUD"] {
93 return URL(fileURLWithPath: folder, isDirectory: true)
94 }
95 #endif
96 guard !automated,
97 let container = FileManager.default.url(forUbiquityContainerIdentifier: identifier)?
98 .appendingPathComponent("Documents", isDirectory: true)
99 else { return nil }
100 try? FileManager.default.createDirectory(at: container, withIntermediateDirectories: true)
101 return container
102 }) { found in
103 documents = found
104 NotificationCenter.default.post(name: changed, object: nil)
105 }
106 }
107
108}