import Foundation /// Google Search Console through the saved service account (added as a Restricted user on each property). /// Daily clicks, impressions and position, plus the top queries and pages of the last 28 days. public struct SearchConsole: Sendable { let auth: GoogleAuth let session: URLSession public init(auth: GoogleAuth = .init(), session: URLSession = .shared) { self.auth = auth; self.session = session } public static var isConfigured: Bool { Keychain.has(.googleServiceAccount) } public func pull(site: Site, days: Int = 90) async throws -> [DataPoint] { guard let property = site.searchConsoleProperty else { return [] } let token = try await auth.accessToken() let end = DayKey.lastDays(1).last ?? DayKey.string(.now) let start = DayKey.lastDays(days).first ?? end let windowStart = DayKey.lastDays(28).first ?? end func query(_ dims: [String], from: String, limit: Int) async throws -> [[String: Any]] { let encoded = property.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? property var r = URLRequest(url: URL(string: "https://www.googleapis.com/webmasters/v3/sites/\(encoded)/searchAnalytics/query")!) r.httpMethod = "POST" r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") r.setValue("application/json", forHTTPHeaderField: "Content-Type") var body: [String: Any] = ["startDate": from, "endDate": end, "dimensions": dims, "rowLimit": limit, "dataState": "all"] // A section of a site (protomota.com/services) reads its parent's property, filtered to its pages. if site.parentID != nil, let prefix = site.pathPrefix { body["dimensionFilterGroups"] = [["filters": [["dimension": "page", "operator": "includingRegex", "expression": "^https?://[^/]+\(prefix)(/|$|\\?)"]]]] } r.httpBody = try JSONSerialization.data(withJSONObject: body) return try await session.json(r, retries: 3)["rows"] as? [[String: Any]] ?? [] } var out: [DataPoint] = [] for row in try await query(["date"], from: start, limit: 1_000) { guard let day = (row["keys"] as? [String])?.first else { continue } out += [DataPoint(day: day, subject: site.id, metric: .searchClicks, event: "google", value: row["clicks"] as? Double ?? 0), DataPoint(day: day, subject: site.id, metric: .searchImpressions, event: "google", value: row["impressions"] as? Double ?? 0), DataPoint(day: day, subject: site.id, metric: .searchPosition, event: "google", value: row["position"] as? Double ?? 0)] } for (dim, family) in [("query", "query"), ("page", "spage")] { for row in try await query([dim], from: windowStart, limit: 10) { guard let key = (row["keys"] as? [String])?.first else { continue } let label = family == "spage" ? Self.path(key) : key out += [DataPoint(day: end, subject: site.id, metric: .searchClicks, breakdown: "\(family):\(label)", event: "google", value: row["clicks"] as? Double ?? 0), DataPoint(day: end, subject: site.id, metric: .searchImpressions, breakdown: "\(family):\(label)", event: "google", value: row["impressions"] as? Double ?? 0)] } } return out } static func path(_ url: String) -> String { URL(string: url).map { $0.path.isEmpty ? "/" : $0.path } ?? url } } /// Bing Webmaster Tools API with the account's API key (Keychain only). Daily clicks and impressions, /// and the top queries of the last four weeks. public struct BingWebmaster: Sendable { let session: URLSession public init(session: URLSession = .shared) { self.session = session } public static var isConfigured: Bool { Keychain.has(.bingAPIKey) } func call(_ method: String, site: String) async throws -> [[String: Any]] { guard let key = Keychain.get(.bingAPIKey) else { throw AnalyticsError.notSignedIn("Bing Webmaster Tools") } var c = URLComponents(string: "https://ssl.bing.com/webmaster/api.svc/json/\(method)")! c.queryItems = [.init(name: "siteUrl", value: site), .init(name: "apikey", value: key)] do { return try await session.json(URLRequest(url: c.url!), retries: 2)["d"] as? [[String: Any]] ?? [] } catch AnalyticsError.http(let code, _) { throw AnalyticsError.http(code, "Bing \(method) for \(site)") } // never echo the URL (it has the key) } /// "/Date(1732262400000-0800)/" → "2026-11-22" (Pacific, like Bing's own UI). static func day(_ s: String) -> String? { guard let ms = s.split(separator: "(").last?.prefix(while: { $0.isNumber || $0 == "-" }).split(separator: "-").first, let v = Double(ms) else { return nil } var cal = Calendar(identifier: .gregorian); cal.timeZone = TimeZone(identifier: "America/Los_Angeles")! return DayKey.string(Date(timeIntervalSince1970: v / 1000), calendar: cal) } public func pull(site: Site) async throws -> [DataPoint] { guard let url = site.bingSiteURL else { return [] } var out: [DataPoint] = [] for row in try await call("GetRankAndTrafficStats", site: url) { guard let day = (row["Date"] as? String).flatMap(Self.day) else { continue } out += [DataPoint(day: day, subject: site.id, metric: .searchClicks, event: "bing", value: Self.number(row["Clicks"])), DataPoint(day: day, subject: site.id, metric: .searchImpressions, event: "bing", value: Self.number(row["Impressions"]))] } let cutoff = DayKey.lastDays(28).first ?? "" let end = DayKey.lastDays(1).last ?? "" var clicks: [String: Double] = [:], impressions: [String: Double] = [:] for row in try await call("GetQueryStats", site: url) { guard let day = (row["Date"] as? String).flatMap(Self.day), day >= cutoff, let q = row["Query"] as? String else { continue } clicks[q, default: 0] += Self.number(row["Clicks"]); impressions[q, default: 0] += Self.number(row["Impressions"]) } for q in impressions.keys.sorted(by: { (clicks[$0]!, impressions[$0]!) > (clicks[$1]!, impressions[$1]!) }).prefix(10) { out += [DataPoint(day: end, subject: site.id, metric: .searchClicks, breakdown: "query:" + q, event: "bing", value: clicks[q] ?? 0), DataPoint(day: end, subject: site.id, metric: .searchImpressions, breakdown: "query:" + q, event: "bing", value: impressions[q] ?? 0)] } return out } static func number(_ v: Any?) -> Double { (v as? Double) ?? (v as? Int).map(Double.init) ?? 0 } }