Cards.swift (13036B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import Observation 4 import UIKit 5 6 /// A certification card: who issued it, what for, its number, and a photo of each side. 7 struct CertificationCard: Codable, Identifiable, Equatable { 8 var id = UUID() 9 var agency = "" 10 var title = "" 11 var number = "" 12 /// Day the certification was issued, "yyyy-MM-dd"; empty when unknown. 13 var issued = "" 14 var notes = "" 15 var hasFront = false 16 var hasBack = false 17 /// Last change, for merging the copy on this iPhone with the one in iCloud: the most recent one wins. 18 var modified = Date() 19 /// A deleted card stays in the file, so that the deletion reaches the other copy too. 20 var deleted = false 21 22 enum Side: String, CaseIterable { case front, back } 23 24 func has(_ side: Side) -> Bool { side == .front ? hasFront : hasBack } 25 func fileName(_ side: Side) -> String { "\(id.uuidString)-\(side.rawValue).jpg" } 26 27 var issuedDate: Date? { 28 get { Self.dayFormat.date(from: issued) } 29 set { issued = newValue.map { Self.dayFormat.string(from: $0) } ?? "" } 30 } 31 32 private static let dayFormat: DateFormatter = { 33 let format = DateFormatter() 34 format.calendar = Calendar(identifier: .gregorian) 35 format.locale = Locale(identifier: "en_US_POSIX") 36 format.timeZone = TimeZone(identifier: "UTC") 37 format.dateFormat = "yyyy-MM-dd" 38 return format 39 }() 40 } 41 42 /// The cards live on the iPhone (Application Support/Cards: `cards.json` and one JPEG per side) and are copied 43 /// to the app's iCloud Drive folder whenever they change. At launch and when the app comes back, both copies are 44 /// merged, so a new iPhone gets the cards back and a card edited elsewhere arrives here. 45 @MainActor 46 @Observable 47 final class CardStore { 48 enum Backup: Equatable { 49 case unknown 50 /// This build has no iCloud folder (see `CardsICloudBackup` in project.yml). 51 case notBuiltIn 52 /// No iCloud account, or iCloud Drive turned off for the app. 53 case unavailable 54 case working 55 case done(Date) 56 case failed(String) 57 } 58 59 private(set) var all: [CertificationCard] = [] 60 private(set) var backup = Backup.unknown 61 /// Bumped when a photo changes, so that the views showing it read it again. 62 private(set) var photoVersion = 0 63 64 var cards: [CertificationCard] { 65 all.filter { !$0.deleted }.sorted { 66 ($0.issued, $0.agency, $0.title) < ($1.issued, $1.agency, $1.title) 67 } 68 } 69 70 @ObservationIgnored private let local: URL 71 @ObservationIgnored private var syncing = false 72 @ObservationIgnored private var syncAgain = false 73 74 private nonisolated static let indexName = "cards.json" 75 76 init(directory: URL? = nil) { 77 let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] 78 local = directory ?? base.appendingPathComponent("Cards", isDirectory: true) 79 try? FileManager.default.createDirectory(at: local, withIntermediateDirectories: true) 80 all = Self.read(local.appendingPathComponent(Self.indexName)) 81 } 82 83 /// Made-up cards in a scratch folder, for screenshots ("-demoCards"); nothing goes to iCloud. 84 static func demo() -> CardStore { 85 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("demo-cards-\(UUID().uuidString)", isDirectory: true) 86 let store = CardStore(directory: directory) 87 let samples: [(String, String, String, String, UIColor)] = [ 88 ("Open Water Diver", "Example Diving Agency", "OW-104 552", "2018-03-10", .systemTeal), 89 ("Advanced Open Water Diver", "Example Diving Agency", "AOW-221 907", "2019-07-21", .systemIndigo), 90 ("Nitrox", "Example Diving Agency", "NX-330 118", "2020-02-08", .systemGreen), 91 ] 92 for (title, agency, number, issued, color) in samples { 93 var card = CertificationCard() 94 card.title = title 95 card.agency = agency 96 card.number = number 97 card.issued = issued 98 for side in CertificationCard.Side.allCases { 99 let size = CGSize(width: 860, height: 540) 100 let image = UIGraphicsImageRenderer(size: size).image { context in 101 (side == .front ? color : UIColor.secondarySystemBackground).setFill() 102 context.fill(CGRect(origin: .zero, size: size)) 103 let ink = side == .front ? UIColor.white : UIColor.label 104 (side == .front ? title : "Sample diver\n" + number).draw( 105 in: CGRect(x: 48, y: 48, width: 760, height: 300), 106 withAttributes: [.font: UIFont.systemFont(ofSize: 54, weight: .bold), .foregroundColor: ink]) 107 agency.draw(at: CGPoint(x: 48, y: 440), withAttributes: [.font: UIFont.systemFont(ofSize: 34), .foregroundColor: ink]) 108 } 109 store.setPhoto(image, of: card, side: side) 110 } 111 card.hasFront = true 112 card.hasBack = true 113 store.save(card) 114 } 115 return store 116 } 117 118 // MARK: Editing 119 120 func card(id: UUID) -> CertificationCard? { all.first { $0.id == id && !$0.deleted } } 121 122 /// Adds the card, or replaces the one with the same identifier. 123 func save(_ card: CertificationCard) { 124 var card = card 125 card.modified = Date() 126 if let index = all.firstIndex(where: { $0.id == card.id }) { all[index] = card } else { all.append(card) } 127 persist() 128 } 129 130 func delete(_ card: CertificationCard) { 131 guard let index = all.firstIndex(where: { $0.id == card.id }) else { return } 132 all[index].deleted = true 133 all[index].hasFront = false 134 all[index].hasBack = false 135 all[index].modified = Date() 136 for side in CertificationCard.Side.allCases { 137 try? FileManager.default.removeItem(at: local.appendingPathComponent(card.fileName(side))) 138 } 139 persist() 140 } 141 142 /// Stores the photo of one side (scaled down, JPEG); nil removes it. The card itself is saved by the caller. 143 func setPhoto(_ image: UIImage?, of card: CertificationCard, side: CertificationCard.Side) { 144 let url = local.appendingPathComponent(card.fileName(side)) 145 if let image, let data = Self.scaled(image, longestSide: 2000).jpegData(compressionQuality: 0.8) { 146 try? data.write(to: url, options: .atomic) 147 } else { 148 try? FileManager.default.removeItem(at: url) 149 } 150 photoVersion += 1 151 } 152 153 func photo(of card: CertificationCard, side: CertificationCard.Side) -> UIImage? { 154 guard card.has(side) else { return nil } 155 return UIImage(contentsOfFile: local.appendingPathComponent(card.fileName(side)).path) 156 } 157 158 private func persist() { 159 Self.write(all, to: local.appendingPathComponent(Self.indexName)) 160 sync() 161 } 162 163 private static func scaled(_ image: UIImage, longestSide: CGFloat) -> UIImage { 164 let longest = max(image.size.width, image.size.height) 165 guard longest > longestSide else { return image } 166 let ratio = longestSide / longest 167 let size = CGSize(width: (image.size.width * ratio).rounded(), height: (image.size.height * ratio).rounded()) 168 let format = UIGraphicsImageRendererFormat.default() 169 format.scale = 1 170 return UIGraphicsImageRenderer(size: size, format: format).image { _ in image.draw(in: CGRect(origin: .zero, size: size)) } 171 } 172 173 // MARK: Files 174 175 nonisolated private static func read(_ url: URL) -> [CertificationCard] { 176 guard let data = try? Data(contentsOf: url) else { return [] } 177 let decoder = JSONDecoder() 178 decoder.dateDecodingStrategy = .iso8601 179 return (try? decoder.decode([CertificationCard].self, from: data)) ?? [] 180 } 181 182 nonisolated private static func write(_ cards: [CertificationCard], to url: URL) { 183 let encoder = JSONEncoder() 184 encoder.dateEncodingStrategy = .iso8601 185 encoder.outputFormatting = [.prettyPrinted, .sortedKeys] 186 guard let data = try? encoder.encode(cards) else { return } 187 try? data.write(to: url, options: .atomic) 188 } 189 190 // MARK: iCloud 191 192 /// Merges this iPhone's cards with the copy in iCloud Drive, both ways. Safe to call at any time. 193 func sync() { 194 guard !LaunchOptions.flag("-demoCards"), CloudDrive.isBuiltIn else { 195 backup = .notBuiltIn 196 return 197 } 198 if syncing { 199 syncAgain = true 200 return 201 } 202 syncing = true 203 if backup == .unknown || backup == .unavailable { backup = .working } 204 let local = local 205 Task.detached(priority: .utility) { 206 let outcome = Self.merge(local: local) 207 await MainActor.run { 208 self.syncing = false 209 switch outcome { 210 case .unavailable: self.backup = .unavailable 211 case .failed(let message): self.backup = .failed(message) 212 case .merged(let cards, let photosChanged): 213 if cards != self.all { 214 // Changes made here while the merge ran are kept: the next pass sends them. 215 let merged = Self.newest(self.all, cards) 216 self.all = merged 217 Self.write(merged, to: local.appendingPathComponent(Self.indexName)) 218 } 219 if photosChanged { self.photoVersion += 1 } 220 self.backup = .done(Date()) 221 } 222 if self.syncAgain { 223 self.syncAgain = false 224 self.sync() 225 } 226 } 227 } 228 } 229 230 private enum Outcome { 231 case unavailable 232 case failed(String) 233 case merged([CertificationCard], photosChanged: Bool) 234 } 235 236 /// For each card, the most recently modified of the two copies. 237 nonisolated private static func newest(_ a: [CertificationCard], _ b: [CertificationCard]) -> [CertificationCard] { 238 var byID = [UUID: CertificationCard]() 239 for card in a + b { 240 if let other = byID[card.id], other.modified >= card.modified { continue } 241 byID[card.id] = card 242 } 243 return byID.values.sorted { $0.id.uuidString < $1.id.uuidString } 244 } 245 246 nonisolated private static func merge(local: URL) -> Outcome { 247 let files = FileManager.default 248 // Asking for the container can take a while the first time: never on the main thread. 249 guard let remote = CloudDrive.folder("Cards") else { return .unavailable } 250 // On a new iPhone the files are in iCloud but not downloaded yet: ask for them and give them a moment. 251 let remoteIndex = remote.appendingPathComponent(indexName) 252 CloudDrive.download(remoteIndex) 253 let mine = read(local.appendingPathComponent(indexName)) 254 let theirs = CloudDrive.coordinatedRead(remoteIndex).map { data -> [CertificationCard] in 255 let decoder = JSONDecoder() 256 decoder.dateDecodingStrategy = .iso8601 257 return (try? decoder.decode([CertificationCard].self, from: data)) ?? [] 258 } ?? [] 259 let merged = newest(mine, theirs) 260 var photosChanged = false 261 262 for card in merged { 263 let fromRemote = theirs.first { $0.id == card.id } == card && mine.first { $0.id == card.id } != card 264 for side in CertificationCard.Side.allCases { 265 let here = local.appendingPathComponent(card.fileName(side)) 266 let there = remote.appendingPathComponent(card.fileName(side)) 267 if !card.has(side) { 268 if files.fileExists(atPath: here.path) { 269 try? files.removeItem(at: here) 270 photosChanged = true 271 } 272 CloudDrive.coordinatedRemove(there) 273 } else if fromRemote || !files.fileExists(atPath: here.path) { 274 // The copy in iCloud is the newer one (or the only one): bring its photo here. 275 CloudDrive.download(there) 276 if let data = CloudDrive.coordinatedRead(there) { 277 try? data.write(to: here, options: .atomic) 278 photosChanged = true 279 } 280 } else if let data = try? Data(contentsOf: here), CloudDrive.coordinatedRead(there) != data { 281 CloudDrive.coordinatedWrite(data, to: there) 282 } 283 } 284 } 285 if merged != theirs { 286 let encoder = JSONEncoder() 287 encoder.dateEncodingStrategy = .iso8601 288 encoder.outputFormatting = [.prettyPrinted, .sortedKeys] 289 if let data = try? encoder.encode(merged) { CloudDrive.coordinatedWrite(data, to: remoteIndex) } 290 } 291 return .merged(merged, photosChanged: photosChanged) 292 } 293 }