import Foundation /// Pulls every source into the local store, then pushes a snapshot to iCloud for the iPhone. /// A failing source is skipped and reported; it never blocks the others (same rule as the old ga4_pull.py). public struct Refresher: Sendable { public struct Report: Sendable, Codable { public var updated: [String] = [] public var failed: [String: String] = [:] /// Sources that aren't set up, with what they need. public var skipped: [String: String] = [:] public var points = 0 } let store: WorkspaceStore let ga = GoogleAnalytics() let asc = AppStoreConnect() let ratings = AppStoreRatings() let gsc = SearchConsole() let bing = BingWebmaster() let socials = Socials() let todos = OpenTalonTodos() let cloud: SnapshotSync? public init(store: WorkspaceStore, cloud: SnapshotSync? = nil) { self.store = store; self.cloud = cloud } /// Every event Graphley counts per day. public static let defaultEvents = GoogleAnalytics.trackedEvents /// 180 days so the 90-day range can compare against the 90 days before it. public func refreshAll(days: Int = 180) async -> Report { var report = Report() let ws = (try? store.load()) ?? Workspace() func record(_ name: String, _ work: () async throws -> [DataPoint]) async { do { let pts = try await work() try store.merge(pts); report.updated.append(name); report.points += pts.count } catch { report.failed[name] = error.localizedDescription } } // Google Analytics: every site and section in parallel. if GoogleAuth.isConfigured { struct SiteResult: Sendable { var name: String; var points: [DataPoint]; var error: String? } let views = GA4SiteView.views(for: ws.sites) let client = ga let results = await withTaskGroup(of: SiteResult.self, returning: [SiteResult].self) { group in for view in views { group.addTask { do { return SiteResult(name: view.site.name, points: try await client.pull(view, days: days)) } catch { return SiteResult(name: view.site.name, points: [], error: error.localizedDescription) } } } var all: [SiteResult] = [] for await r in group { all.append(r) } return all } for r in results { if let e = r.error { report.failed[r.name] = e; continue } do { try store.merge(r.points); report.updated.append(r.name); report.points += r.points.count } catch { report.failed[r.name] = error.localizedDescription } } } else if !ws.sites.isEmpty { report.skipped["Google Analytics"] = "Sign in with Google or save a service account key in Sources & keys." } // App Store Connect sales: re-pull the last 3 days (Apple revises them) and any older gap. let listed = ws.apps.filter(\.hasAppStoreListing) if !listed.isEmpty { if asc.isConfigured { await record("App Store downloads") { let have = Set(((try? store.points()) ?? []).filter { $0.metric == .appDownloads && $0.breakdown == nil }.map(\.day)) let wanted = DayKey.lastDays(days).enumerated().filter { $0.offset >= days - 3 || !have.contains($0.element) }.map(\.element) return try await asc.daily(apps: listed, days: wanted) } } else { report.skipped["App Store downloads"] = "Add an App Store Connect key (Sales and Reports) in Sources & keys." } } // Ratings and reviews, every storefront; new apps by the same developer are added. let seed = ws.apps.filter { $0.id.allSatisfy(\.isNumber) }.map(\.id) if !seed.isEmpty { do { let known = Dictionary((ws.reviews ?? []).map { ($0.id, $0.firstSeen) }, uniquingKeysWith: { a, _ in a }) let result = try await ratings.pull(seed: seed, firstSeen: known) try store.merge(result.points); report.points += result.points.count var freshCount = 0 try store.update { w in var all = Dictionary((w.reviews ?? []).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) var fresh: [Review] = [] for r in result.reviews where !r.id.isEmpty { if all[r.id] == nil { fresh.append(r) } all[r.id] = r } freshCount = fresh.count w.reviews = all.values.sorted { $0.date > $1.date } // Name every app by its newest App Store name, so renames merge; add new apps by the developer. for (id, name) in result.names { if let i = w.apps.firstIndex(where: { $0.id == id }) { w.apps[i].name = name } else { w.apps.append(StoreApp(id: id, name: name)) } } let sent = Set(w.todoKeys ?? []) let waiting = (w.pendingTodos ?? []) + fresh.map(OpenTalonTodos.todo) w.pendingTodos = Dictionary(waiting.filter { !sent.contains($0.key) }.map { ($0.key, $0) }, uniquingKeysWith: { a, _ in a }) .values.sorted { $0.key < $1.key } } report.updated.append("App Store ratings and reviews" + (freshCount == 0 ? "" : " (\(freshCount) new)")) } catch { report.failed["App Store ratings and reviews"] = error.localizedDescription } } // New reviews → OpenTalon to-dos. let pending = ((try? store.load()) ?? ws).pendingTodos ?? [] if !pending.isEmpty { if OpenTalonTodos.isConfigured { do { let sent = try await todos.send(pending) try store.update { w in w.todoKeys = (w.todoKeys ?? []) + sent w.pendingTodos = (w.pendingTodos ?? []).filter { !sent.contains($0.key) } } report.updated.append("OpenTalon review to-dos (\(sent.count))") } catch { report.failed["OpenTalon review to-dos"] = error.localizedDescription + " (kept for the next refresh)" } } else { report.skipped["OpenTalon review to-dos"] = "\(pending.count) waiting. Save OpenTalon's connection with set_source_key." } } // Search Console and Bing, per site. let searchable = ws.sites.filter { !$0.archived } if SearchConsole.isConfigured { for site in searchable where site.searchConsoleProperty != nil { await record("Search Console: \(site.name)") { try await gsc.pull(site: site) } } } else { report.skipped["Search Console"] = "Save a Google service account key and add it as a Restricted user on each Search Console property." } if BingWebmaster.isConfigured { for site in searchable where site.bingSiteURL != nil { await record("Bing: \(site.name)") { try await bing.pull(site: site) } } } else { report.skipped["Bing Webmaster Tools"] = "Save the Bing API key (Bing Webmaster Tools → Settings → API access) with set_source_key." } // Followers and YouTube videos. if !ws.socials.isEmpty { let result = await socials.pull(accounts: ws.socials) do { try store.merge(result.points); report.points += result.points.count try store.update { w in var all = Dictionary((w.videos ?? []).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a }) for v in result.videos { var merged = v if let old = all[v.id] { merged.published = v.published ?? old.published if v.kind == "video", old.kind != "video" { merged.kind = old.kind } } all[v.id] = merged } w.videos = all.values.sorted { ($0.published ?? "") > ($1.published ?? "") } } } catch { report.failed["Followers"] = error.localizedDescription } report.updated += result.updated.map { "Followers: \($0)" } for (k, v) in result.failed { report.failed["Followers: \(k)"] = v } } if ws.settings.shareWithIPhone, let cloud { do { try await cloud.push(try store.snapshot()); _ = try? store.update { $0.settings.lastSharedAt = .now } } catch { report.failed["iCloud sync"] = error.localizedDescription } } _ = try? store.update { $0.settings.lastRefreshAt = .now } return report } }