CloudDrive.swift (3988B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 4 /// The app's folder in the user's iCloud Drive ("Sub Rascasse" in the Files app), where backups go. Everything 5 /// here blocks: call it off the main thread. 6 enum CloudDrive { 7 static let containerIdentifier = "iCloud.org.schurger.subrascasse" 8 9 /// False for a build without the iCloud entitlements (see `CardsICloudBackup` in project.yml). 10 static var isBuiltIn: Bool { testFolder != nil || Bundle.main.object(forInfoDictionaryKey: "CardsICloudBackup") as? Bool == true } 11 12 /// "-backupFolder path": a plain folder stands in for iCloud Drive (the simulator has no iCloud account). 13 private static let testFolder: URL? = { 14 let arguments = ProcessInfo.processInfo.arguments 15 guard let index = arguments.firstIndex(of: "-backupFolder"), index + 1 < arguments.count else { return nil } 16 return URL(fileURLWithPath: arguments[index + 1], isDirectory: true) 17 }() 18 19 /// A folder of the app's iCloud Drive, created if needed; nil without an iCloud account or with iCloud Drive 20 /// turned off for the app. 21 static func folder(_ name: String) -> URL? { 22 let files = FileManager.default 23 if let testFolder { 24 let folder = testFolder.appendingPathComponent(name, isDirectory: true) 25 try? files.createDirectory(at: folder, withIntermediateDirectories: true) 26 return folder 27 } 28 guard isBuiltIn, files.ubiquityIdentityToken != nil, 29 let container = files.url(forUbiquityContainerIdentifier: containerIdentifier) else { return nil } 30 let folder = container.appendingPathComponent("Documents", isDirectory: true).appendingPathComponent(name, isDirectory: true) 31 do { 32 try files.createDirectory(at: folder, withIntermediateDirectories: true) 33 } catch { 34 return nil 35 } 36 return folder 37 } 38 39 /// The files of a folder, including those that are in iCloud but not downloaded yet (listed as ".name.icloud"). 40 static func names(in folder: URL) -> [String] { 41 ((try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []).map { name in 42 name.hasPrefix(".") && name.hasSuffix(".icloud") ? String(name.dropFirst().dropLast(7)) : name 43 } 44 } 45 46 /// Asks iCloud for a file that is not on the device yet, and waits a little for it. 47 static func download(_ url: URL) { 48 let files = FileManager.default 49 let placeholder = url.deletingLastPathComponent().appendingPathComponent("." + url.lastPathComponent + ".icloud") 50 guard files.fileExists(atPath: placeholder.path) || isNotDownloaded(url) else { return } 51 try? files.startDownloadingUbiquitousItem(at: url) 52 for _ in 0..<40 { 53 if files.fileExists(atPath: url.path), !isNotDownloaded(url) { return } 54 Thread.sleep(forTimeInterval: 0.25) 55 } 56 } 57 58 static func isNotDownloaded(_ url: URL) -> Bool { 59 guard let status = try? url.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey]).ubiquitousItemDownloadingStatus else { return false } 60 return status == .notDownloaded 61 } 62 63 static func coordinatedRead(_ url: URL) -> Data? { 64 var data: Data? 65 var error: NSError? 66 NSFileCoordinator().coordinate(readingItemAt: url, options: [], error: &error) { data = try? Data(contentsOf: $0) } 67 return data 68 } 69 70 static func coordinatedWrite(_ data: Data, to url: URL) { 71 var error: NSError? 72 NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &error) { try? data.write(to: $0, options: .atomic) } 73 } 74 75 static func coordinatedRemove(_ url: URL) { 76 guard FileManager.default.fileExists(atPath: url.path) else { return } 77 var error: NSError? 78 NSFileCoordinator().coordinate(writingItemAt: url, options: .forDeleting, error: &error) { try? FileManager.default.removeItem(at: $0) } 79 } 80 }