Branchwell

Graphley / app · graphley.ai / Sources / AnalyticsKit / Refresher.swift

1import Foundation
2
3/// Pulls every source into the local store, then pushes a snapshot to iCloud for the iPhone.
4/// A failing source is skipped and reported; it never blocks the others (same rule as the old ga4_pull.py).
5public struct Refresher: Sendable {
6 public struct Report: Sendable, Codable {
7 public var updated: [String] = []
8 public var failed: [String: String] = [:]
9 /// Sources that aren't set up, with what they need.
10 public var skipped: [String: String] = [:]
11 public var points = 0
12 }
13
14 let store: WorkspaceStore
15 let ga = GoogleAnalytics()
16 let asc = AppStoreConnect()
17 let ratings = AppStoreRatings()
18 let gsc = SearchConsole()
19 let bing = BingWebmaster()
20 let socials = Socials()
21 let todos = OpenTalonTodos()
22 let cloud: SnapshotSync?
23
24 public init(store: WorkspaceStore, cloud: SnapshotSync? = nil) { self.store = store; self.cloud = cloud }
25
26 /// Every event Graphley counts per day.
27 public static let defaultEvents = GoogleAnalytics.trackedEvents
28
29 /// 180 days so the 90-day range can compare against the 90 days before it.
30 public func refreshAll(days: Int = 180) async -> Report {
31 var report = Report()
32 let ws = (try? store.load()) ?? Workspace()
33
34 func record(_ name: String, _ work: () async throws -> [DataPoint]) async {
35 do {
36 let pts = try await work()
37 try store.merge(pts); report.updated.append(name); report.points += pts.count
38 } catch { report.failed[name] = error.localizedDescription }
39 }
40
41 // Google Analytics: every site and section in parallel.
42 if GoogleAuth.isConfigured {
43 struct SiteResult: Sendable { var name: String; var points: [DataPoint]; var error: String? }
44 let views = GA4SiteView.views(for: ws.sites)
45 let client = ga
46 let results = await withTaskGroup(of: SiteResult.self, returning: [SiteResult].self) { group in
47 for view in views {
48 group.addTask {
49 do { return SiteResult(name: view.site.name, points: try await client.pull(view, days: days)) }
50 catch { return SiteResult(name: view.site.name, points: [], error: error.localizedDescription) }
51 }
52 }
53 var all: [SiteResult] = []
54 for await r in group { all.append(r) }
55 return all
56 }
57 for r in results {
58 if let e = r.error { report.failed[r.name] = e; continue }
59 do { try store.merge(r.points); report.updated.append(r.name); report.points += r.points.count }
60 catch { report.failed[r.name] = error.localizedDescription }
61 }
62 } else if !ws.sites.isEmpty {
63 report.skipped["Google Analytics"] = "Sign in with Google or save a service account key in Sources & keys."
64 }
65
66 // App Store Connect sales: re-pull the last 3 days (Apple revises them) and any older gap.
67 let listed = ws.apps.filter(\.hasAppStoreListing)
68 if !listed.isEmpty {
69 if asc.isConfigured {
70 await record("App Store downloads") {
71 let have = Set(((try? store.points()) ?? []).filter { $0.metric == .appDownloads && $0.breakdown == nil }.map(\.day))
72 let wanted = DayKey.lastDays(days).enumerated().filter { $0.offset >= days - 3 || !have.contains($0.element) }.map(\.element)
73 return try await asc.daily(apps: listed, days: wanted)
74 }
75 } else {
76 report.skipped["App Store downloads"] = "Add an App Store Connect key (Sales and Reports) in Sources & keys."
77 }
78 }
79
80 // Ratings and reviews, every storefront; new apps by the same developer are added.
81 let seed = ws.apps.filter { $0.id.allSatisfy(\.isNumber) }.map(\.id)
82 if !seed.isEmpty {
83 do {
84 let known = Dictionary((ws.reviews ?? []).map { ($0.id, $0.firstSeen) }, uniquingKeysWith: { a, _ in a })
85 let result = try await ratings.pull(seed: seed, firstSeen: known)
86 try store.merge(result.points); report.points += result.points.count
87 var freshCount = 0
88 try store.update { w in
89 var all = Dictionary((w.reviews ?? []).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
90 var fresh: [Review] = []
91 for r in result.reviews where !r.id.isEmpty {
92 if all[r.id] == nil { fresh.append(r) }
93 all[r.id] = r
94 }
95 freshCount = fresh.count
96 w.reviews = all.values.sorted { $0.date > $1.date }
97 // Name every app by its newest App Store name, so renames merge; add new apps by the developer.
98 for (id, name) in result.names {
99 if let i = w.apps.firstIndex(where: { $0.id == id }) { w.apps[i].name = name }
100 else { w.apps.append(StoreApp(id: id, name: name)) }
101 }
102 let sent = Set(w.todoKeys ?? [])
103 let waiting = (w.pendingTodos ?? []) + fresh.map(OpenTalonTodos.todo)
104 w.pendingTodos = Dictionary(waiting.filter { !sent.contains($0.key) }.map { ($0.key, $0) }, uniquingKeysWith: { a, _ in a })
105 .values.sorted { $0.key < $1.key }
106 }
107 report.updated.append("App Store ratings and reviews" + (freshCount == 0 ? "" : " (\(freshCount) new)"))
108 } catch { report.failed["App Store ratings and reviews"] = error.localizedDescription }
109 }
110
111 // New reviews → OpenTalon to-dos.
112 let pending = ((try? store.load()) ?? ws).pendingTodos ?? []
113 if !pending.isEmpty {
114 if OpenTalonTodos.isConfigured {
115 do {
116 let sent = try await todos.send(pending)
117 try store.update { w in
118 w.todoKeys = (w.todoKeys ?? []) + sent
119 w.pendingTodos = (w.pendingTodos ?? []).filter { !sent.contains($0.key) }
120 }
121 report.updated.append("OpenTalon review to-dos (\(sent.count))")
122 } catch { report.failed["OpenTalon review to-dos"] = error.localizedDescription + " (kept for the next refresh)" }
123 } else {
124 report.skipped["OpenTalon review to-dos"] = "\(pending.count) waiting. Save OpenTalon's connection with set_source_key."
125 }
126 }
127
128 // Search Console and Bing, per site.
129 let searchable = ws.sites.filter { !$0.archived }
130 if SearchConsole.isConfigured {
131 for site in searchable where site.searchConsoleProperty != nil {
132 await record("Search Console: \(site.name)") { try await gsc.pull(site: site) }
133 }
134 } else {
135 report.skipped["Search Console"] = "Save a Google service account key and add it as a Restricted user on each Search Console property."
136 }
137 if BingWebmaster.isConfigured {
138 for site in searchable where site.bingSiteURL != nil {
139 await record("Bing: \(site.name)") { try await bing.pull(site: site) }
140 }
141 } else {
142 report.skipped["Bing Webmaster Tools"] = "Save the Bing API key (Bing Webmaster Tools → Settings → API access) with set_source_key."
143 }
144
145 // Followers and YouTube videos.
146 if !ws.socials.isEmpty {
147 let result = await socials.pull(accounts: ws.socials)
148 do {
149 try store.merge(result.points); report.points += result.points.count
150 try store.update { w in
151 var all = Dictionary((w.videos ?? []).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
152 for v in result.videos {
153 var merged = v
154 if let old = all[v.id] {
155 merged.published = v.published ?? old.published
156 if v.kind == "video", old.kind != "video" { merged.kind = old.kind }
157 }
158 all[v.id] = merged
159 }
160 w.videos = all.values.sorted { ($0.published ?? "") > ($1.published ?? "") }
161 }
162 } catch { report.failed["Followers"] = error.localizedDescription }
163 report.updated += result.updated.map { "Followers: \($0)" }
164 for (k, v) in result.failed { report.failed["Followers: \(k)"] = v }
165 }
166
167 if ws.settings.shareWithIPhone, let cloud {
168 do { try await cloud.push(try store.snapshot()); _ = try? store.update { $0.settings.lastSharedAt = .now } }
169 catch { report.failed["iCloud sync"] = error.localizedDescription }
170 }
171 _ = try? store.update { $0.settings.lastRefreshAt = .now }
172 return report
173 }
174}