Graphley / app · graphley.ai / Apps / Mac / SourcesView.swift
| 1 | import SwiftUI |
| 2 | import CryptoKit |
| 3 | import UniformTypeIdentifiers |
| 4 | import AnalyticsKit |
| 5 | import AnalyticsUI |
| 6 | |
| 7 | /// Sources & keys: connect Google Analytics and App Store Connect without an agent (design/DESIGN.md 3.2). |
| 8 | /// Keys go to the Keychain only, never into the workspace or iCloud data. |
| 9 | struct SourcesView: View { |
| 10 | @Environment(AppModel.self) private var model |
| 11 | |
| 12 | var body: some View { |
| 13 | VStack(alignment: .leading, spacing: 16) { |
| 14 | ScreenHeading("Sources & keys", subtitle: "Where your numbers come from. Keys stay in your Keychain; your iPhone only gets the numbers.") |
| 15 | GoogleCard() |
| 16 | AppStoreCard() |
| 17 | HStack(spacing: 10) { |
| 18 | Text("App Store ratings").font(Tide.rowTitle).foregroundStyle(Tide.ink) |
| 19 | Text("Public, no key needed").font(Tide.secondary).foregroundStyle(Tide.muted) |
| 20 | Spacer() |
| 21 | StatusPill("On", .ok) |
| 22 | } |
| 23 | .padding(.horizontal, 16) |
| 24 | if !model.failures.isEmpty { ProblemsCard() } |
| 25 | } |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | // MARK: Google Analytics |
| 30 | |
| 31 | struct GoogleCard: View { |
| 32 | @Environment(AppModel.self) private var model |
| 33 | @State private var signingIn = false |
| 34 | @State private var error: String? |
| 35 | @State private var confirmSignOut = false |
| 36 | @State private var choosingSites = false |
| 37 | @State private var importingServiceAccount = false |
| 38 | |
| 39 | var body: some View { |
| 40 | let _ = model.keysVersion |
| 41 | let serviceAccount = GoogleServiceAccountKey.savedEmail |
| 42 | let signedIn = Keychain.has(.googleRefreshToken) |
| 43 | let expired = model.failures.values.contains { $0.contains("invalid_grant") || $0.contains("Sign in to Google") } |
| 44 | TideCard("Google Analytics", icon: "chart.bar.xaxis", padding: 20) { |
| 45 | if signingIn { StatusPill("Checking…", .info) } |
| 46 | else if expired { StatusPill("Sign in again", .error) } |
| 47 | else if serviceAccount != nil || signedIn { StatusPill("Connected", .ok) } |
| 48 | else { StatusPill("Not connected", .neutral) } |
| 49 | } content: { |
| 50 | if let serviceAccount { |
| 51 | para("Connected with the service account \(serviceAccount). \(tracked)") |
| 52 | HStack(spacing: 8) { |
| 53 | Button("Choose Sites…") { choosingSites = true }.buttonStyle(.tide(.secondary)) |
| 54 | Button("Remove Key") { confirmSignOut = true }.buttonStyle(.tide(.quietDestructive)) |
| 55 | } |
| 56 | } else if signingIn { |
| 57 | para("Finish signing in in your browser, then come back here.") |
| 58 | Button {} label: { Label("Waiting for your browser…", systemImage: "hourglass") }.buttonStyle(.tide(.primary)).disabled(true) |
| 59 | } else if expired { |
| 60 | para("Google ended this sign-in, so your sites stopped updating. Sign in again to pick up where you left off.") |
| 61 | Button("Sign In Again…") { signIn() }.buttonStyle(.tide(.primary)) |
| 62 | } else if signedIn { |
| 63 | para("Signed in with read-only access. \(tracked)") |
| 64 | HStack(spacing: 8) { |
| 65 | Button("Choose Sites…") { choosingSites = true }.buttonStyle(.tide(.secondary)) |
| 66 | Button("Sign Out") { confirmSignOut = true }.buttonStyle(.tide(.quietDestructive)) |
| 67 | } |
| 68 | } else { |
| 69 | para("Sign in with Google to read visitors, sessions and page views for your sites. Graphley only asks for read-only access.") |
| 70 | HStack(spacing: 8) { |
| 71 | Button("Sign In with Google…") { signIn() }.buttonStyle(.tide(.primary)) |
| 72 | Button("Use a Service Account Key…") { importingServiceAccount = true }.buttonStyle(.tide(.quiet)) |
| 73 | } |
| 74 | } |
| 75 | if let error { |
| 76 | Label(error, systemImage: "exclamationmark.circle.fill").font(Tide.caption).foregroundStyle(Tide.downText) |
| 77 | } |
| 78 | } |
| 79 | .confirmationDialog(serviceAccount != nil ? "Remove the service account key?" : "Sign out of Google?", isPresented: $confirmSignOut) { |
| 80 | Button(serviceAccount != nil ? "Remove Key" : "Sign Out", role: .destructive) { |
| 81 | if serviceAccount != nil { GoogleServiceAccountKey.remove() } else { Keychain.remove(.googleRefreshToken) } |
| 82 | model.keysChanged() |
| 83 | } |
| 84 | Button("Cancel", role: .cancel) {} |
| 85 | } message: { |
| 86 | Text("Graphley will stop updating your sites. The numbers you already have stay.") |
| 87 | } |
| 88 | .sheet(isPresented: $choosingSites) { ChooseSitesSheet() } |
| 89 | .fileImporter(isPresented: $importingServiceAccount, allowedContentTypes: [.json]) { result in |
| 90 | error = nil |
| 91 | do { |
| 92 | let url = try result.get() |
| 93 | let ok = url.startAccessingSecurityScopedResource(); defer { if ok { url.stopAccessingSecurityScopedResource() } } |
| 94 | try GoogleServiceAccountKey.save(json: String(contentsOf: url, encoding: .utf8)) |
| 95 | model.keysChanged() |
| 96 | choosingSites = true |
| 97 | } catch { |
| 98 | self.error = "That file isn't a Google service account key. Download a JSON key from Google Cloud › IAM › Service accounts › Keys." |
| 99 | } |
| 100 | } |
| 101 | .onAppear { if model.wantsSitePicker { model.wantsSitePicker = false; choosingSites = true } } |
| 102 | } |
| 103 | |
| 104 | var tracked: String { |
| 105 | let n = model.sites.count |
| 106 | return n == 0 ? "No sites tracked yet." : "\(n) \(n == 1 ? "site" : "sites") tracked." |
| 107 | } |
| 108 | |
| 109 | func para(_ text: String) -> some View { |
| 110 | Text(text).font(Tide.text).foregroundStyle(Tide.ink2).fixedSize(horizontal: false, vertical: true) |
| 111 | } |
| 112 | |
| 113 | func signIn() { |
| 114 | signingIn = true; error = nil |
| 115 | Task { |
| 116 | do { |
| 117 | try await GoogleSignIn().run() |
| 118 | model.keysChanged() |
| 119 | if model.sites.isEmpty { choosingSites = true } |
| 120 | } catch { |
| 121 | self.error = "Sign-in didn't finish. Try again, and choose Allow when Google asks." |
| 122 | } |
| 123 | signingIn = false |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | /// Pick which GA4 properties to track. New ones become sites; unchecked ones are archived (history kept). |
| 129 | struct ChooseSitesSheet: View { |
| 130 | @Environment(AppModel.self) private var model |
| 131 | @Environment(\.dismiss) private var dismiss |
| 132 | @State private var properties: [GoogleAnalytics.Property] = [] |
| 133 | @State private var chosen: Set<String> = [] |
| 134 | @State private var loading = true |
| 135 | @State private var error: String? |
| 136 | |
| 137 | var body: some View { |
| 138 | VStack(alignment: .leading, spacing: 14) { |
| 139 | VStack(alignment: .leading, spacing: 4) { |
| 140 | Text("Choose sites to track").font(Tide.sans(17, .semibold)).foregroundStyle(Tide.ink) |
| 141 | Text("These are the Google Analytics properties your account can read.").font(Tide.secondary).foregroundStyle(Tide.muted) |
| 142 | } |
| 143 | Group { |
| 144 | if loading { |
| 145 | HStack { ProgressView().controlSize(.small); Text("Finding your properties…").font(Tide.secondary).foregroundStyle(Tide.muted) } |
| 146 | .frame(maxWidth: .infinity, minHeight: 120) |
| 147 | } else if let error { |
| 148 | Text(error).font(Tide.secondary).foregroundStyle(Tide.downText).frame(maxWidth: .infinity, minHeight: 120, alignment: .leading) |
| 149 | } else if properties.isEmpty { |
| 150 | Text("This Google account can't read any Google Analytics properties yet.").font(Tide.secondary).foregroundStyle(Tide.muted) |
| 151 | .frame(maxWidth: .infinity, minHeight: 120, alignment: .leading) |
| 152 | } else { |
| 153 | ScrollView { |
| 154 | VStack(spacing: 0) { |
| 155 | ForEach(Array(properties.enumerated()), id: \.element.id) { i, p in |
| 156 | if i > 0 { RowDivider() } |
| 157 | PropertyRow(property: p, isOn: Binding(get: { chosen.contains(p.id) }, |
| 158 | set: { if $0 { chosen.insert(p.id) } else { chosen.remove(p.id) } })) |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | .frame(maxHeight: 360) |
| 163 | } |
| 164 | } |
| 165 | HStack { |
| 166 | Spacer() |
| 167 | Button("Cancel") { dismiss() }.buttonStyle(.tide(.quiet)).keyboardShortcut(.cancelAction) |
| 168 | Button(saveTitle) { save() }.buttonStyle(.tide(.primary)).keyboardShortcut(.defaultAction).disabled(loading || error != nil) |
| 169 | } |
| 170 | } |
| 171 | .padding(20) |
| 172 | .frame(width: 520) |
| 173 | .background(Tide.surface) |
| 174 | .task { await load() } |
| 175 | } |
| 176 | |
| 177 | var current: Set<String> { Set(model.sites.compactMap(\.ga4PropertyID)) } |
| 178 | var saveTitle: String { chosen == current ? "Save" : "Track \(chosen.count) \(chosen.count == 1 ? "Site" : "Sites")" } |
| 179 | |
| 180 | func load() async { |
| 181 | do { |
| 182 | properties = try await GoogleAnalytics().properties().sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } |
| 183 | chosen = current |
| 184 | } catch { |
| 185 | self.error = "Couldn't reach Google. Check your internet connection and try again." |
| 186 | } |
| 187 | loading = false |
| 188 | } |
| 189 | |
| 190 | func save() { |
| 191 | let byID = Dictionary(properties.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) |
| 192 | _ = try? model.store.update { ws in |
| 193 | for i in ws.sites.indices { |
| 194 | guard let pid = ws.sites[i].ga4PropertyID, byID[pid] != nil else { continue } |
| 195 | ws.sites[i].archived = !chosen.contains(pid) |
| 196 | } |
| 197 | for pid in chosen where !ws.sites.contains(where: { $0.ga4PropertyID == pid }) { |
| 198 | guard let p = byID[pid] else { continue } |
| 199 | let used = Set(ws.sites.filter { !$0.archived }.map(\.colorIndex)) |
| 200 | let color = (0..<7).first { !used.contains($0) } ?? ws.sites.count % 7 |
| 201 | ws.sites.append(Site(id: Self.slug(p.name, taken: Set(ws.sites.map(\.id))), name: p.name, ga4PropertyID: pid, colorIndex: color)) |
| 202 | } |
| 203 | } |
| 204 | model.reload() |
| 205 | dismiss() |
| 206 | Task { await model.refresh() } |
| 207 | } |
| 208 | |
| 209 | static func slug(_ s: String, taken: Set<String>) -> String { |
| 210 | let base = s.lowercased().map { $0.isLetter || $0.isNumber ? String($0) : "-" }.joined().split(separator: "-").joined(separator: "-") |
| 211 | var candidate = base.isEmpty ? "site" : base, n = 2 |
| 212 | while taken.contains(candidate) { candidate = "\(base)-\(n)"; n += 1 } |
| 213 | return candidate |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | struct PropertyRow: View { |
| 218 | let property: GoogleAnalytics.Property |
| 219 | @Binding var isOn: Bool |
| 220 | var body: some View { |
| 221 | Button { isOn.toggle() } label: { |
| 222 | HStack(spacing: 12) { |
| 223 | ZStack { |
| 224 | RoundedRectangle(cornerRadius: 4).fill(isOn ? Tide.fill : Tide.surface) |
| 225 | RoundedRectangle(cornerRadius: 4).strokeBorder(isOn ? Tide.fill : Tide.control) |
| 226 | if isOn { Image(systemName: "checkmark").font(.system(size: 10, weight: .bold)).foregroundStyle(Tide.accentInk) } |
| 227 | } |
| 228 | .frame(width: 16, height: 16) |
| 229 | VStack(alignment: .leading, spacing: 2) { |
| 230 | Text(property.name).font(Tide.rowTitle).foregroundStyle(Tide.ink) |
| 231 | Text("Property \(property.id) · \(property.account)").font(Tide.code).foregroundStyle(Tide.muted) |
| 232 | } |
| 233 | Spacer() |
| 234 | } |
| 235 | .padding(.vertical, 8).contentShape(Rectangle()) |
| 236 | } |
| 237 | .buttonStyle(.plain) |
| 238 | .accessibilityAddTraits(isOn ? .isSelected : []) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | // MARK: App Store Connect |
| 243 | |
| 244 | struct AppStoreCard: View { |
| 245 | @Environment(AppModel.self) private var model |
| 246 | @Environment(\.openURL) private var openURL |
| 247 | @State private var replacing = false |
| 248 | @State private var keyID = "" |
| 249 | @State private var issuerID = "" |
| 250 | @State private var vendor = "" |
| 251 | @State private var key: KeyFile? |
| 252 | @State private var keyIDHelp = "10 letters and numbers." |
| 253 | @State private var showErrors = false |
| 254 | @State private var saving = false |
| 255 | @State private var failure: String? |
| 256 | @State private var justSaved = false |
| 257 | @State private var confirmRemove = false |
| 258 | @State private var agentOpen = false |
| 259 | |
| 260 | struct KeyFile: Equatable { var name: String; var path: String; var pem: String } |
| 261 | |
| 262 | var body: some View { |
| 263 | let _ = model.keysVersion |
| 264 | let saved = AppStoreConnect.Credentials.saved |
| 265 | let showForm = saved == nil || replacing |
| 266 | TideCard("App Store Connect", icon: "arrow.down.app", padding: 20) { |
| 267 | if saving { StatusPill("Checking…", .info) } |
| 268 | else if failure != nil { StatusPill("Key not accepted", .error) } |
| 269 | else if saved != nil { StatusPill("Key saved", .ok) } |
| 270 | else { StatusPill("Not set up", .neutral) } |
| 271 | } content: { |
| 272 | if showForm { form(replacing: saved != nil) } else if let saved { savedView(saved) } |
| 273 | } |
| 274 | .confirmationDialog("Remove the App Store Connect key?", isPresented: $confirmRemove) { |
| 275 | Button("Remove Key", role: .destructive) { AppStoreConnect.Credentials.remove(); justSaved = false; model.keysChanged() } |
| 276 | Button("Cancel", role: .cancel) {} |
| 277 | } message: { |
| 278 | Text("Graphley will stop updating App Store downloads. The numbers you already have stay.") |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | // Saved state: the IDs (not secret) and what to do next. The private key is never shown. |
| 283 | @ViewBuilder func savedView(_ c: AppStoreConnect.Credentials) -> some View { |
| 284 | Text("Key ID \(c.keyID) · Issuer \(c.issuerID.prefix(8))…\(c.issuerID.suffix(4)) · Vendor \(c.vendorNumber)") |
| 285 | .font(Tide.code).foregroundStyle(Tide.ink2).textSelection(.enabled) |
| 286 | if justSaved { |
| 287 | HStack(spacing: 10) { |
| 288 | Text("The key works. Downloads show up after the next refresh.").font(Tide.caption).foregroundStyle(Tide.up) |
| 289 | Button("Refresh Now") { Task { await model.refresh() } }.buttonStyle(.tide(.secondary, size: .small)).disabled(model.refreshing) |
| 290 | } |
| 291 | } else if model.workspace.apps.isEmpty { |
| 292 | HStack(spacing: 10) { |
| 293 | Text("No apps added yet. Ask your agent to add them:").font(Tide.caption).foregroundStyle(Tide.muted) |
| 294 | PromptChip("Add my App Store apps to Graphley and refresh.") |
| 295 | } |
| 296 | } else if let at = model.workspace.settings.lastRefreshAt, model.failures["App Store downloads"] == nil { |
| 297 | Text("Updated downloads for \(model.workspace.apps.count) \(model.workspace.apps.count == 1 ? "app" : "apps") \(RefreshTime.describe(at)).") |
| 298 | .font(Tide.caption).foregroundStyle(Tide.muted) |
| 299 | } |
| 300 | HStack(spacing: 8) { |
| 301 | Button("Replace Key…") { |
| 302 | keyID = c.keyID; issuerID = c.issuerID; vendor = c.vendorNumber; key = nil |
| 303 | failure = nil; showErrors = false; replacing = true |
| 304 | } |
| 305 | .buttonStyle(.tide(.secondary)) |
| 306 | Button("Remove Key") { confirmRemove = true }.buttonStyle(.tide(.quietDestructive)) |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | @ViewBuilder func form(replacing: Bool) -> some View { |
| 311 | HStack(spacing: 4) { |
| 312 | Text("Add an App Store Connect API key with the Sales and Reports role, so Graphley can read daily downloads.") |
| 313 | .font(Tide.text).foregroundStyle(Tide.ink2).fixedSize(horizontal: false, vertical: true) |
| 314 | } |
| 315 | Button { |
| 316 | openURL(URL(string: "https://developer.apple.com/documentation/appstoreconnectapi/creating-api-keys-for-app-store-connect-api")!) |
| 317 | } label: { HStack(spacing: 4) { Text("How to create a key"); Image(systemName: "arrow.up.right").font(.system(size: 10, weight: .semibold)) } } |
| 318 | .buttonStyle(.tide(.quiet, size: .small)).padding(.leading, -10).padding(.top, -6) |
| 319 | |
| 320 | ViewThatFits(in: .horizontal) { |
| 321 | HStack(alignment: .top, spacing: 16) { keyIDField.frame(width: 240); vendorField.frame(width: 240); Spacer(minLength: 0) } |
| 322 | VStack(alignment: .leading, spacing: 14) { keyIDField; vendorField } |
| 323 | } |
| 324 | TideField("Issuer ID", text: $issuerID, placeholder: "57246542-96fe-1a63-e053-0824d011072a", |
| 325 | help: "Above the list of keys in Users and Access › Integrations.", error: err(issuerError), monospaced: true) |
| 326 | VStack(alignment: .leading, spacing: 6) { |
| 327 | Text("Private key").font(Tide.fieldLabel).foregroundStyle(Tide.ink) |
| 328 | FileDropWell(file: $key, error: showErrors && key == nil ? "Choose the AuthKey_….p8 file you downloaded from App Store Connect." : nil) { file in |
| 329 | if keyID.isEmpty, let match = file.name.firstMatch(of: /AuthKey_([A-Z0-9]{10})\.p8/) { |
| 330 | keyID = String(match.1); keyIDHelp = "Filled in from the file name." |
| 331 | } |
| 332 | } |
| 333 | Text("Apple lets you download this file only once, so keep the original somewhere safe. Graphley keeps a copy in your Keychain.") |
| 334 | .font(Tide.caption).foregroundStyle(Tide.muted).fixedSize(horizontal: false, vertical: true) |
| 335 | } |
| 336 | if let failure { |
| 337 | Label(failure, systemImage: "exclamationmark.circle.fill").font(Tide.secondary).foregroundStyle(Tide.downText) |
| 338 | .fixedSize(horizontal: false, vertical: true) |
| 339 | } |
| 340 | HStack(spacing: 8) { |
| 341 | Spacer() |
| 342 | if replacing { Button("Cancel") { self.replacing = false; failure = nil }.buttonStyle(.tide(.quiet)) } |
| 343 | Button { save() } label: { |
| 344 | if saving { Label("Checking with Apple…", systemImage: "hourglass") } else { Text("Save Key") } |
| 345 | } |
| 346 | .buttonStyle(.tide(.primary)) |
| 347 | .disabled(saving) |
| 348 | } |
| 349 | RowDivider() |
| 350 | TideDisclosure("Or let your agent do it", isOpen: $agentOpen) { |
| 351 | Text("Paste this into Claude Code, Codex or another agent connected to Graphley. It includes what you've typed above.") |
| 352 | .font(Tide.secondary).foregroundStyle(Tide.muted).fixedSize(horizontal: false, vertical: true) |
| 353 | CopyBlock(agentPrompt(replacing: replacing), wraps: true) |
| 354 | ToggleRow("Let agents set keys", |
| 355 | detail: model.workspace.settings.agentsCanSetKeys ? "On. Turn it off again after your agent saves the key." : "Off. Your agent can't save keys until you turn this on.", |
| 356 | isOn: Binding(get: { model.workspace.settings.agentsCanSetKeys }, set: { v in model.updateSettings { $0.agentsCanSetKeys = v } })) |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | var keyIDField: some View { |
| 361 | TideField("Key ID", text: Binding(get: { keyID }, set: { keyID = $0.uppercased().trimmingCharacters(in: .whitespacesAndNewlines) }), |
| 362 | placeholder: "2X9R4HXF34", help: keyIDHelp, error: err(keyIDError), monospaced: true) |
| 363 | } |
| 364 | var vendorField: some View { |
| 365 | TideField("Vendor number", text: Binding(get: { vendor }, set: { vendor = $0.trimmingCharacters(in: .whitespacesAndNewlines) }), |
| 366 | placeholder: "85123456", help: "Payments and Financial Reports, top left.", error: err(vendorError), monospaced: true) |
| 367 | } |
| 368 | |
| 369 | func err(_ message: String?) -> String? { showErrors ? message : nil } |
| 370 | var keyIDError: String? { keyID.wholeMatch(of: /[A-Z0-9]{10}/) == nil ? "Key IDs are 10 letters and numbers, like 2X9R4HXF34." : nil } |
| 371 | var issuerError: String? { |
| 372 | let t = issuerID.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() |
| 373 | return t.wholeMatch(of: /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/) == nil ? "Issuer IDs look like 57246542-96fe-1a63-e053-0824d011072a." : nil |
| 374 | } |
| 375 | var vendorError: String? { vendor.isEmpty || !vendor.allSatisfy(\.isNumber) ? "Vendor numbers are digits only, like 85123456." : nil } |
| 376 | |
| 377 | func agentPrompt(replacing: Bool) -> String { |
| 378 | let path = key?.path ?? "the AuthKey_….p8 file in my Downloads folder" |
| 379 | var lines = [ |
| 380 | "Save my App Store Connect API key in Graphley with its set_app_store_key tool.", |
| 381 | "Key ID: \(keyID.isEmpty ? "<your key ID>" : keyID)", |
| 382 | "Issuer ID: \(issuerID.isEmpty ? "<your issuer ID>" : issuerID.trimmingCharacters(in: .whitespaces).lowercased())", |
| 383 | "Vendor number: \(vendor.isEmpty ? "<your vendor number>" : vendor)", |
| 384 | "The private key is \(path). The tool reads it from the GRAPHLEY_ASC_PRIVATE_KEY environment variable of Graphley's MCP server, so restart that server with the variable set to the file's contents. Don't show the key's contents in our chat." |
| 385 | ] |
| 386 | if replacing { lines.append("Replace the key that's already saved.") } |
| 387 | return lines.joined(separator: "\n") |
| 388 | } |
| 389 | |
| 390 | func save() { |
| 391 | showErrors = true; failure = nil |
| 392 | guard keyIDError == nil, issuerError == nil, vendorError == nil, let key else { return } |
| 393 | let creds = AppStoreConnect.Credentials(keyID: keyID, issuerID: issuerID.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(), |
| 394 | vendorNumber: vendor, privateKey: key.pem) |
| 395 | saving = true |
| 396 | Task { |
| 397 | do { |
| 398 | try await AppStoreConnect().check(creds) |
| 399 | try creds.save() |
| 400 | self.key = nil; replacing = false; showErrors = false; justSaved = true |
| 401 | model.keysChanged() |
| 402 | } catch { |
| 403 | failure = Self.message(for: error) |
| 404 | } |
| 405 | saving = false |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | static func message(for error: Error) -> String { |
| 410 | if case AnalyticsError.http(let code, let body) = error { |
| 411 | if body.localizedCaseInsensitiveContains("vendor") { return "Apple doesn't recognize this vendor number. You'll find it in Payments and Financial Reports." } |
| 412 | if code == 401 { return "Apple didn't accept this key. Check the Key ID and Issuer ID, and make sure the .p8 file belongs to this key." } |
| 413 | if code == 403 { return "This key can't read sales reports. Create a key with the Sales and Reports role (Finance or Admin also work)." } |
| 414 | } |
| 415 | if error is URLError { return "Couldn't reach Apple. Check your internet connection and try again." } |
| 416 | if error is CryptoKitError || "\(error)".contains("CryptoKit") { return "That file isn't an App Store Connect key. Choose the AuthKey_….p8 file you downloaded from App Store Connect." } |
| 417 | return "Apple didn't accept this key. Check the four values and try again." |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | /// Dashed well for the .p8: drop a file or choose one. Shows the file name, never its contents. |
| 422 | struct FileDropWell: View { |
| 423 | @Binding var file: AppStoreCard.KeyFile? |
| 424 | var error: String? |
| 425 | var onLoad: (AppStoreCard.KeyFile) -> Void |
| 426 | @State private var targeted = false |
| 427 | @State private var choosing = false |
| 428 | @State private var readError: String? |
| 429 | |
| 430 | static let p8 = UTType(filenameExtension: "p8", conformingTo: .data) ?? .data |
| 431 | |
| 432 | var body: some View { |
| 433 | let shownError = readError ?? error |
| 434 | VStack(alignment: .leading, spacing: 6) { |
| 435 | Group { |
| 436 | if let file { |
| 437 | HStack(spacing: 10) { |
| 438 | Image(systemName: "doc.fill").font(.system(size: 16)).foregroundStyle(Tide.accent) |
| 439 | VStack(alignment: .leading, spacing: 2) { |
| 440 | Text(file.name).font(Tide.figure(13)).foregroundStyle(Tide.ink) |
| 441 | Text("Ready to save. It goes to your Keychain.").font(Tide.caption).foregroundStyle(Tide.muted) |
| 442 | } |
| 443 | Spacer() |
| 444 | Button("Replace…") { choosing = true }.buttonStyle(.tide(.quiet, size: .small)) |
| 445 | Button { self.file = nil } label: { Label("Remove file", systemImage: "xmark") }.buttonStyle(.tideIcon).help("Remove file") |
| 446 | } |
| 447 | .padding(.horizontal, 14) |
| 448 | } else { |
| 449 | HStack(spacing: 8) { |
| 450 | Image(systemName: "key.horizontal").font(.system(size: 18)).foregroundStyle(Tide.muted) |
| 451 | Text(targeted ? "Release to add the key" : "Drop your .p8 key file here, or").font(Tide.sans(13)).foregroundStyle(Tide.ink2) |
| 452 | if !targeted { Button("Choose File…") { choosing = true }.buttonStyle(.tide(.quiet, size: .small)) } |
| 453 | } |
| 454 | .frame(maxWidth: .infinity) |
| 455 | } |
| 456 | } |
| 457 | .frame(maxWidth: .infinity, minHeight: 76) |
| 458 | .background(targeted ? Tide.accentTint : file != nil ? Tide.surface : Tide.ground, in: RoundedRectangle(cornerRadius: 10)) |
| 459 | .overlay { |
| 460 | RoundedRectangle(cornerRadius: 10).strokeBorder( |
| 461 | shownError != nil ? Tide.down : targeted ? Tide.accent : file != nil ? Tide.line : Tide.line2, |
| 462 | style: StrokeStyle(lineWidth: file != nil && shownError == nil ? 1 : 1.5, dash: file == nil && !targeted && shownError == nil ? [5, 4] : [])) |
| 463 | } |
| 464 | .onDrop(of: [.fileURL], isTargeted: $targeted) { providers in |
| 465 | guard let provider = providers.first else { return false } |
| 466 | _ = provider.loadObject(ofClass: URL.self) { url, _ in |
| 467 | guard let url else { return } |
| 468 | Task { @MainActor in load(url) } |
| 469 | } |
| 470 | return true |
| 471 | } |
| 472 | .fileImporter(isPresented: $choosing, allowedContentTypes: [Self.p8, .data]) { result in |
| 473 | if let url = try? result.get() { load(url) } |
| 474 | } |
| 475 | .accessibilityElement(children: .contain) |
| 476 | .accessibilityLabel("Choose .p8 key file") |
| 477 | if let shownError { |
| 478 | Label(shownError, systemImage: "exclamationmark.circle.fill").font(Tide.caption).foregroundStyle(Tide.downText) |
| 479 | .fixedSize(horizontal: false, vertical: true) |
| 480 | } |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | func load(_ url: URL) { |
| 485 | let scoped = url.startAccessingSecurityScopedResource(); defer { if scoped { url.stopAccessingSecurityScopedResource() } } |
| 486 | guard let data = try? Data(contentsOf: url), data.count < 4096, |
| 487 | let pem = String(data: data, encoding: .utf8), pem.contains("-----BEGIN \("")PRIVATE KEY-----"), |
| 488 | AppStoreConnect.Credentials.isValidPrivateKey(pem) else { |
| 489 | readError = "That file isn't an App Store Connect key. Choose the AuthKey_….p8 file you downloaded from App Store Connect." |
| 490 | return |
| 491 | } |
| 492 | readError = nil |
| 493 | let f = AppStoreCard.KeyFile(name: url.lastPathComponent, path: (url.path as NSString).abbreviatingWithTildeInPath, pem: pem) |
| 494 | file = f |
| 495 | onLoad(f) |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | // MARK: Problems |
| 500 | |
| 501 | /// Plain-language refresh problems, each with the button that fixes it. The raw error is under Details. |
| 502 | struct ProblemsCard: View { |
| 503 | @Environment(AppModel.self) private var model |
| 504 | @State private var details = false |
| 505 | |
| 506 | var body: some View { |
| 507 | let failures = model.failures.sorted { $0.key < $1.key } |
| 508 | TideCard("Last refresh needs attention", padding: 20) { StatusPill("Needs attention", .attention) } content: { |
| 509 | VStack(alignment: .leading, spacing: 0) { |
| 510 | ForEach(Array(failures.enumerated()), id: \.element.key) { i, f in |
| 511 | if i > 0 { RowDivider() } |
| 512 | let explained = Self.explain(source: f.key, error: f.value) |
| 513 | let message = explained.0, action = explained.1 |
| 514 | HStack(alignment: .center, spacing: 12) { |
| 515 | VStack(alignment: .leading, spacing: 2) { |
| 516 | Text(f.key).font(Tide.rowTitle).foregroundStyle(Tide.ink) |
| 517 | Text(message).font(Tide.secondary).foregroundStyle(Tide.ink2).fixedSize(horizontal: false, vertical: true) |
| 518 | } |
| 519 | Spacer() |
| 520 | if let action { |
| 521 | Button(action) { Task { await model.refresh() } }.buttonStyle(.tide(.secondary, size: .small)).disabled(model.refreshing) |
| 522 | } |
| 523 | } |
| 524 | .padding(.vertical, 10) |
| 525 | } |
| 526 | } |
| 527 | TideDisclosure("Details", isOpen: $details) { |
| 528 | CopyBlock(failures.map { "\($0.key): \($0.value)" }.joined(separator: "\n"), wraps: true) |
| 529 | } |
| 530 | Text("Graphley refreshes every day at \(SettingsView.hourLabel(model.workspace.settings.refreshHour)). Change the time in Settings.") |
| 531 | .font(Tide.caption).foregroundStyle(Tide.muted) |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | static func explain(source: String, error: String) -> (String, String?) { |
| 536 | let e = error.lowercased() |
| 537 | let apple = source.hasPrefix("App Store") |
| 538 | if source == "iCloud sync" { return ("Couldn't share with your iPhone. Make sure this Mac is signed in to iCloud.", nil) } |
| 539 | if e.contains("invalid_grant") || e.contains("sign in to google") { return ("Google sign-in has ended. Sign in again above.", nil) } |
| 540 | if e.contains("(401)") && apple { return ("Apple didn't accept the App Store Connect key. Replace it above.", nil) } |
| 541 | if e.contains("(403)") && apple { return ("The App Store Connect key can't read sales reports.", nil) } |
| 542 | if e.contains("(403)") { return ("This Google account can't read this property anymore.", nil) } |
| 543 | if e.contains("(429)") || e.contains("(5") { return ("\(apple ? "Apple" : "Google") was busy. Graphley will try again at the next refresh.", "Retry") } |
| 544 | if e.contains("offline") || e.contains("timed out") || e.contains("network") || e.contains("internet") { |
| 545 | return ("Couldn't reach \(apple ? "Apple" : "Google"). Check your internet connection.", "Retry") |
| 546 | } |
| 547 | return ("Something went wrong reading \(source). Graphley will try again at the next refresh.", "Retry") |
| 548 | } |
| 549 | } |