Branchwell

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

1import Foundation
2
3/// Google sign-in for an installed app: the Mac app runs the loopback + PKCE flow once (see
4/// `GoogleSignIn` in the Mac target) and saves the refresh token in the Keychain. A saved service
5/// account key (see `ServiceAccount`) is used instead when present. Scope: analytics.readonly.
6public struct GoogleAuth: Sendable {
7 public static let scope = "https://www.googleapis.com/auth/analytics.readonly"
8 /// A service account also reads Search Console (add it as a Restricted user on each property).
9 public static let serviceAccountScope = scope + " https://www.googleapis.com/auth/webmasters.readonly"
10 /// Desktop-type OAuth client shipped with the app. Users can supply their own in Settings.
11 public static let defaultClientID = "REPLACE_WITH_DESKTOP_CLIENT_ID.apps.googleusercontent.com"
12 let session: URLSession
13
14 public init(session: URLSession = .shared) { self.session = session }
15
16 /// Signed in with Google, or a service account key is saved.
17 public static var isConfigured: Bool { Keychain.has(.googleServiceAccount) || Keychain.has(.googleRefreshToken) }
18
19 /// Uses the saved service account key when there is one, otherwise the sign-in refresh token.
20 public func accessToken() async throws -> String {
21 if let json = Keychain.get(.googleServiceAccount) {
22 return try await exchange(["grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
23 "assertion": try ServiceAccount(json: json).assertion()])
24 }
25 guard let refresh = Keychain.get(.googleRefreshToken) else { throw AnalyticsError.notSignedIn("Google") }
26 let clientID = Keychain.get(.googleClientID) ?? Self.defaultClientID
27 return try await exchange(["client_id": clientID, "grant_type": "refresh_token", "refresh_token": refresh])
28 }
29
30 private func exchange(_ fields: [String: String]) async throws -> String {
31 var request = URLRequest(url: URL(string: "https://oauth2.googleapis.com/token")!)
32 request.httpMethod = "POST"
33 request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
34 request.httpBody = form(fields)
35 let json = try await session.json(request)
36 guard let token = json["access_token"] as? String else { throw AnalyticsError.badResponse("Google token") }
37 return token
38 }
39
40 private func form(_ fields: [String: String]) -> Data {
41 var c = URLComponents(); c.queryItems = fields.map { URLQueryItem(name: $0, value: $1) }
42 return Data((c.percentEncodedQuery ?? "").utf8)
43 }
44}
45
46/// GA4 Admin API (find properties) and Data API (daily reports).
47public struct GoogleAnalytics: Sendable {
48 public struct Property: Sendable, Hashable, Codable {
49 public let id: String // "564127557"
50 public let name: String // "Textley"
51 public let account: String // "Protomota"
52 }
53
54 let auth: GoogleAuth
55 let session: URLSession
56 public init(auth: GoogleAuth = .init(), session: URLSession = .shared) { self.auth = auth; self.session = session }
57
58 /// Every GA4 property the signed-in Google account can read. Agents call this through
59 /// `discover_ga4_properties` and then `add_site` for the ones the user wants.
60 public func properties() async throws -> [Property] {
61 let token = try await auth.accessToken()
62 var found: [Property] = []
63 var pageToken: String?
64 repeat {
65 var c = URLComponents(string: "https://analyticsadmin.googleapis.com/v1beta/accountSummaries")!
66 c.queryItems = [URLQueryItem(name: "pageSize", value: "200")] + (pageToken.map { [URLQueryItem(name: "pageToken", value: $0)] } ?? [])
67 var r = URLRequest(url: c.url!); r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
68 let json = try await session.json(r)
69 found += Self.parseAccountSummaries(json)
70 pageToken = json["nextPageToken"] as? String
71 } while pageToken?.isEmpty == false
72 return found
73 }
74
75 static func parseAccountSummaries(_ json: [String: Any]) -> [Property] {
76 let accounts = json["accountSummaries"] as? [[String: Any]] ?? []
77 return accounts.flatMap { account -> [Property] in
78 let accountName = account["displayName"] as? String ?? ""
79 return (account["propertySummaries"] as? [[String: Any]] ?? []).compactMap { p in
80 guard let ref = p["property"] as? String else { return nil }
81 return Property(id: ref.replacingOccurrences(of: "properties/", with: ""),
82 name: p["displayName"] as? String ?? ref, account: accountName)
83 }
84 }
85 }
86
87 /// Daily users, new users, sessions and page views for one site.
88 public func daily(site: Site, days: Int = 90) async throws -> [DataPoint] {
89 guard let property = site.ga4PropertyID else { return [] }
90 let metrics: [Metric] = [.users, .newUsers, .sessions, .pageViews, .engagedSessions]
91 let body: [String: Any] = [
92 "dateRanges": [["startDate": "\(days)daysAgo", "endDate": "yesterday"]],
93 "dimensions": [["name": "date"]],
94 "metrics": metrics.compactMap(\.ga4Name).map { ["name": $0] },
95 "keepEmptyRows": true
96 ]
97 let json = try await runReport(property: property, body: body)
98 return Self.parseDaily(json, subject: site.id, metrics: metrics)
99 }
100
101 /// Top page paths over the last `days` days, stored on the last day with `breakdown` = path.
102 public func topPages(site: Site, days: Int = 30, limit: Int = 10) async throws -> [DataPoint] {
103 guard let property = site.ga4PropertyID else { return [] }
104 let body: [String: Any] = [
105 "dateRanges": [["startDate": "\(days)daysAgo", "endDate": "yesterday"]],
106 "dimensions": [["name": "pagePath"]],
107 "metrics": [["name": "screenPageViews"]],
108 "orderBys": [["metric": ["metricName": "screenPageViews"], "desc": true]],
109 "limit": limit
110 ]
111 let json = try await runReport(property: property, body: body)
112 let day = DayKey.lastDays(1).last ?? DayKey.string(.now)
113 return (json["rows"] as? [[String: Any]] ?? []).compactMap { row in
114 guard let path = Self.dims(row).first, let v = Self.mets(row).first else { return nil }
115 return DataPoint(day: day, subject: site.id, metric: .pageViews, breakdown: "page:" + path, value: v)
116 }
117 }
118
119 /// Daily counts of named key events (e.g. mac_installer_download, app_store_click).
120 public func events(site: Site, names: [String], days: Int = 90) async throws -> [DataPoint] {
121 guard let property = site.ga4PropertyID, !names.isEmpty else { return [] }
122 let body: [String: Any] = [
123 "dateRanges": [["startDate": "\(days)daysAgo", "endDate": "yesterday"]],
124 "dimensions": [["name": "date"], ["name": "eventName"]],
125 "metrics": [["name": "eventCount"]],
126 "dimensionFilter": ["filter": ["fieldName": "eventName", "inListFilter": ["values": names]]]
127 ]
128 let json = try await runReport(property: property, body: body)
129 return (json["rows"] as? [[String: Any]] ?? []).compactMap { row in
130 let d = Self.dims(row)
131 guard d.count == 2, let v = Self.mets(row).first else { return nil }
132 return DataPoint(day: Self.dayKey(d[0]), subject: site.id, metric: .keyEvent, event: d[1], value: v)
133 }
134 }
135
136 func runReport(property: String, body: [String: Any]) async throws -> [String: Any] {
137 let token = try await auth.accessToken()
138 var r = URLRequest(url: URL(string: "https://analyticsdata.googleapis.com/v1beta/properties/\(property):runReport")!)
139 r.httpMethod = "POST"
140 r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
141 r.setValue("application/json", forHTTPHeaderField: "Content-Type")
142 r.httpBody = try JSONSerialization.data(withJSONObject: body)
143 return try await session.json(r, retries: 4)
144 }
145
146 static func parseDaily(_ json: [String: Any], subject: String, metrics: [Metric]) -> [DataPoint] {
147 (json["rows"] as? [[String: Any]] ?? []).flatMap { row -> [DataPoint] in
148 guard let date = dims(row).first else { return [] }
149 let values = mets(row)
150 return zip(metrics, values).map { DataPoint(day: dayKey(date), subject: subject, metric: $0, value: $1) }
151 }
152 }
153
154 static func dims(_ row: [String: Any]) -> [String] { (row["dimensionValues"] as? [[String: Any]] ?? []).map { $0["value"] as? String ?? "" } }
155 static func mets(_ row: [String: Any]) -> [Double] { (row["metricValues"] as? [[String: Any]] ?? []).map { Double($0["value"] as? String ?? "") ?? 0 } }
156 /// GA4 returns dates as YYYYMMDD.
157 static func dayKey(_ s: String) -> String {
158 guard s.count == 8 else { return s }
159 let a = Array(s); return "\(String(a[0..<4]))-\(String(a[4..<6]))-\(String(a[6..<8]))"
160 }
161}
162
163public enum AnalyticsError: Error, LocalizedError {
164 case notSignedIn(String), badResponse(String), http(Int, String), missing(String), notAllowed(String)
165 public var errorDescription: String? {
166 switch self {
167 case .notSignedIn(let s): "Sign in to \(s) in Sources & keys."
168 case .badResponse(let s): "\(s) sent a response the app couldn't read."
169 case .http(let code, let body): "Request failed (\(code)): \(body.prefix(200))"
170 case .missing(let s): s
171 case .notAllowed(let s): s
172 }
173 }
174}
175
176extension URLSession {
177 /// JSON request with retries on 429/5xx and timeouts (the old pull script needed the same).
178 func json(_ request: URLRequest, retries: Int = 0) async throws -> [String: Any] {
179 var attempt = 0
180 while true {
181 do {
182 let (data, response) = try await data(for: request)
183 let code = (response as? HTTPURLResponse)?.statusCode ?? 0
184 if (code == 429 || code >= 500), attempt < retries {
185 attempt += 1; try await Task.sleep(nanoseconds: UInt64(pow(2, Double(attempt))) * 1_000_000_000); continue
186 }
187 guard (200..<300).contains(code) else { throw AnalyticsError.http(code, String(decoding: data, as: UTF8.self)) }
188 return (try JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
189 } catch let e as URLError where e.code == .timedOut && attempt < retries {
190 attempt += 1
191 }
192 }
193 }
194}