Graphley / app · graphley.ai / Sources / AnalyticsKit / SearchSources.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// Google Search Console through the saved service account (added as a Restricted user on each property). |
| 4 | /// Daily clicks, impressions and position, plus the top queries and pages of the last 28 days. |
| 5 | public struct SearchConsole: Sendable { |
| 6 | let auth: GoogleAuth |
| 7 | let session: URLSession |
| 8 | public init(auth: GoogleAuth = .init(), session: URLSession = .shared) { self.auth = auth; self.session = session } |
| 9 | |
| 10 | public static var isConfigured: Bool { Keychain.has(.googleServiceAccount) } |
| 11 | |
| 12 | public func pull(site: Site, days: Int = 90) async throws -> [DataPoint] { |
| 13 | guard let property = site.searchConsoleProperty else { return [] } |
| 14 | let token = try await auth.accessToken() |
| 15 | let end = DayKey.lastDays(1).last ?? DayKey.string(.now) |
| 16 | let start = DayKey.lastDays(days).first ?? end |
| 17 | let windowStart = DayKey.lastDays(28).first ?? end |
| 18 | func query(_ dims: [String], from: String, limit: Int) async throws -> [[String: Any]] { |
| 19 | let encoded = property.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? property |
| 20 | var r = URLRequest(url: URL(string: "https://www.googleapis.com/webmasters/v3/sites/\(encoded)/searchAnalytics/query")!) |
| 21 | r.httpMethod = "POST" |
| 22 | r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") |
| 23 | r.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 24 | var body: [String: Any] = ["startDate": from, "endDate": end, "dimensions": dims, "rowLimit": limit, "dataState": "all"] |
| 25 | // A section of a site (protomota.com/services) reads its parent's property, filtered to its pages. |
| 26 | if site.parentID != nil, let prefix = site.pathPrefix { |
| 27 | body["dimensionFilterGroups"] = [["filters": [["dimension": "page", "operator": "includingRegex", "expression": "^https?://[^/]+\(prefix)(/|$|\\?)"]]]] |
| 28 | } |
| 29 | r.httpBody = try JSONSerialization.data(withJSONObject: body) |
| 30 | return try await session.json(r, retries: 3)["rows"] as? [[String: Any]] ?? [] |
| 31 | } |
| 32 | var out: [DataPoint] = [] |
| 33 | for row in try await query(["date"], from: start, limit: 1_000) { |
| 34 | guard let day = (row["keys"] as? [String])?.first else { continue } |
| 35 | out += [DataPoint(day: day, subject: site.id, metric: .searchClicks, event: "google", value: row["clicks"] as? Double ?? 0), |
| 36 | DataPoint(day: day, subject: site.id, metric: .searchImpressions, event: "google", value: row["impressions"] as? Double ?? 0), |
| 37 | DataPoint(day: day, subject: site.id, metric: .searchPosition, event: "google", value: row["position"] as? Double ?? 0)] |
| 38 | } |
| 39 | for (dim, family) in [("query", "query"), ("page", "spage")] { |
| 40 | for row in try await query([dim], from: windowStart, limit: 10) { |
| 41 | guard let key = (row["keys"] as? [String])?.first else { continue } |
| 42 | let label = family == "spage" ? Self.path(key) : key |
| 43 | out += [DataPoint(day: end, subject: site.id, metric: .searchClicks, breakdown: "\(family):\(label)", event: "google", value: row["clicks"] as? Double ?? 0), |
| 44 | DataPoint(day: end, subject: site.id, metric: .searchImpressions, breakdown: "\(family):\(label)", event: "google", value: row["impressions"] as? Double ?? 0)] |
| 45 | } |
| 46 | } |
| 47 | return out |
| 48 | } |
| 49 | |
| 50 | static func path(_ url: String) -> String { URL(string: url).map { $0.path.isEmpty ? "/" : $0.path } ?? url } |
| 51 | } |
| 52 | |
| 53 | /// Bing Webmaster Tools API with the account's API key (Keychain only). Daily clicks and impressions, |
| 54 | /// and the top queries of the last four weeks. |
| 55 | public struct BingWebmaster: Sendable { |
| 56 | let session: URLSession |
| 57 | public init(session: URLSession = .shared) { self.session = session } |
| 58 | public static var isConfigured: Bool { Keychain.has(.bingAPIKey) } |
| 59 | |
| 60 | func call(_ method: String, site: String) async throws -> [[String: Any]] { |
| 61 | guard let key = Keychain.get(.bingAPIKey) else { throw AnalyticsError.notSignedIn("Bing Webmaster Tools") } |
| 62 | var c = URLComponents(string: "https://ssl.bing.com/webmaster/api.svc/json/\(method)")! |
| 63 | c.queryItems = [.init(name: "siteUrl", value: site), .init(name: "apikey", value: key)] |
| 64 | do { return try await session.json(URLRequest(url: c.url!), retries: 2)["d"] as? [[String: Any]] ?? [] } |
| 65 | catch AnalyticsError.http(let code, _) { throw AnalyticsError.http(code, "Bing \(method) for \(site)") } // never echo the URL (it has the key) |
| 66 | } |
| 67 | |
| 68 | /// "/Date(1732262400000-0800)/" → "2026-11-22" (Pacific, like Bing's own UI). |
| 69 | static func day(_ s: String) -> String? { |
| 70 | guard let ms = s.split(separator: "(").last?.prefix(while: { $0.isNumber || $0 == "-" }).split(separator: "-").first, let v = Double(ms) else { return nil } |
| 71 | var cal = Calendar(identifier: .gregorian); cal.timeZone = TimeZone(identifier: "America/Los_Angeles")! |
| 72 | return DayKey.string(Date(timeIntervalSince1970: v / 1000), calendar: cal) |
| 73 | } |
| 74 | |
| 75 | public func pull(site: Site) async throws -> [DataPoint] { |
| 76 | guard let url = site.bingSiteURL else { return [] } |
| 77 | var out: [DataPoint] = [] |
| 78 | for row in try await call("GetRankAndTrafficStats", site: url) { |
| 79 | guard let day = (row["Date"] as? String).flatMap(Self.day) else { continue } |
| 80 | out += [DataPoint(day: day, subject: site.id, metric: .searchClicks, event: "bing", value: Self.number(row["Clicks"])), |
| 81 | DataPoint(day: day, subject: site.id, metric: .searchImpressions, event: "bing", value: Self.number(row["Impressions"]))] |
| 82 | } |
| 83 | let cutoff = DayKey.lastDays(28).first ?? "" |
| 84 | let end = DayKey.lastDays(1).last ?? "" |
| 85 | var clicks: [String: Double] = [:], impressions: [String: Double] = [:] |
| 86 | for row in try await call("GetQueryStats", site: url) { |
| 87 | guard let day = (row["Date"] as? String).flatMap(Self.day), day >= cutoff, let q = row["Query"] as? String else { continue } |
| 88 | clicks[q, default: 0] += Self.number(row["Clicks"]); impressions[q, default: 0] += Self.number(row["Impressions"]) |
| 89 | } |
| 90 | for q in impressions.keys.sorted(by: { (clicks[$0]!, impressions[$0]!) > (clicks[$1]!, impressions[$1]!) }).prefix(10) { |
| 91 | out += [DataPoint(day: end, subject: site.id, metric: .searchClicks, breakdown: "query:" + q, event: "bing", value: clicks[q] ?? 0), |
| 92 | DataPoint(day: end, subject: site.id, metric: .searchImpressions, breakdown: "query:" + q, event: "bing", value: impressions[q] ?? 0)] |
| 93 | } |
| 94 | return out |
| 95 | } |
| 96 | |
| 97 | static func number(_ v: Any?) -> Double { (v as? Double) ?? (v as? Int).map(Double.init) ?? 0 } |
| 98 | } |