import Foundation import CryptoKit /// App Store Connect sales reports: daily first downloads and redownloads per app and device. /// Needs an App Store Connect API key (Sales and Reports role) saved in the Keychain. public struct AppStoreConnect: Sendable { static let downloadTypes: Set = ["1", "1F", "1T", "1E", "F1"] static let redownloadTypes: Set = ["3", "3F", "3T", "F3"] let session: URLSession public init(session: URLSession = .shared) { self.session = session } public var isConfigured: Bool { [Keychain.Item.appStoreKeyID, .appStoreIssuerID, .appStorePrivateKey, .appStoreVendorNumber].allSatisfy(Keychain.has) } /// Pulls each missing day (Apple publishes a day's report the next morning, Pacific time). public func daily(apps: [StoreApp], days: [String]) async throws -> [DataPoint] { guard isConfigured else { throw AnalyticsError.notSignedIn("App Store Connect") } let listed = apps.filter(\.hasAppStoreListing) let ids = Set(listed.map(\.id)) let desktop = Dictionary(uniqueKeysWithValues: listed.map { ($0.id, $0.desktopCountsAs ?? "Mac") }) var points: [DataPoint] = [] for day in days { // Apple 404s a day it hasn't published yet: skip it (never stored as zero) so the next run asks again. guard let tsv = try await report(day: day) else { continue } points += Self.parse(tsv: tsv, day: day, appIDs: ids, desktop: desktop) } return points } /// The four parts of an App Store Connect API key. The app's form builds one to check it before saving. public struct Credentials: Sendable { public var keyID, issuerID, vendorNumber, privateKey: String public init(keyID: String, issuerID: String, vendorNumber: String, privateKey: String) { self.keyID = keyID; self.issuerID = issuerID; self.vendorNumber = vendorNumber; self.privateKey = privateKey } /// The saved key, if all four parts are in the Keychain. public static var saved: Credentials? { guard let k = Keychain.get(.appStoreKeyID), let i = Keychain.get(.appStoreIssuerID), let v = Keychain.get(.appStoreVendorNumber), let p = Keychain.get(.appStorePrivateKey) else { return nil } return Credentials(keyID: k, issuerID: i, vendorNumber: v, privateKey: p) } public func save() throws { try Keychain.set(keyID, for: .appStoreKeyID); try Keychain.set(issuerID, for: .appStoreIssuerID) try Keychain.set(vendorNumber, for: .appStoreVendorNumber); try Keychain.set(privateKey, for: .appStorePrivateKey) } public static func remove() { [Keychain.Item.appStoreKeyID, .appStoreIssuerID, .appStoreVendorNumber, .appStorePrivateKey].forEach(Keychain.remove) } /// True when the text is a PEM private key that CryptoKit can sign with. public static func isValidPrivateKey(_ pem: String) -> Bool { (try? P256.Signing.PrivateKey(pemRepresentation: pem)) != nil } } /// Asks Apple for one recent day's sales report with these credentials. Throws `AnalyticsError.http` /// (401 bad key, 403 wrong role) or a URL error. A day without sales counts as success. public func check(_ credentials: Credentials) async throws { _ = try await report(day: DayKey.lastDays(2).first ?? "", credentials: credentials) } func report(day: String, credentials: Credentials? = nil) async throws -> String? { var c = URLComponents(string: "https://api.appstoreconnect.apple.com/v1/salesReports")! c.queryItems = [ .init(name: "filter[frequency]", value: "DAILY"), .init(name: "filter[reportType]", value: "SALES"), .init(name: "filter[reportSubType]", value: "SUMMARY"), .init(name: "filter[version]", value: "1_1"), .init(name: "filter[vendorNumber]", value: credentials?.vendorNumber ?? Keychain.get(.appStoreVendorNumber)), .init(name: "filter[reportDate]", value: day) ] var r = URLRequest(url: c.url!) r.setValue("Bearer \(try token(credentials: credentials))", forHTTPHeaderField: "Authorization") r.setValue("application/a-gzip", forHTTPHeaderField: "Accept") let (data, response) = try await session.data(for: r) let code = (response as? HTTPURLResponse)?.statusCode ?? 0 if code == 404 { return nil } // no sales that day, or not published yet guard code == 200 else { throw AnalyticsError.http(code, String(decoding: data, as: UTF8.self)) } return String(decoding: try Gzip.inflate(data), as: UTF8.self) } /// Apple's Device column as Graphley shows it: Desktop is a Mac (or, for an iOS-only app like Jotley, the /// iPhone app running on an Apple Silicon Mac), Apple Vision is Vision Pro. public static func platform(device: String, desktopCountsAs: String = "Mac") -> String { switch device.trimmingCharacters(in: .whitespaces).lowercased() { case "iphone", "ipod", "ipod touch": "iPhone" case "ipad": "iPad" case "desktop", "mac", "macos": desktopCountsAs case "apple vision", "vision", "apple vision pro", "visionos", "vision pro": "Vision Pro" case "apple tv", "appletv", "tvos": "Apple TV" case "apple watch", "watchos": "Apple Watch" default: device } } static func parse(tsv: String, day: String, appIDs: Set, desktop: [String: String] = [:]) -> [DataPoint] { let lines = tsv.split(whereSeparator: \.isNewline).map { $0.components(separatedBy: "\t") } guard let header = lines.first, let idCol = header.firstIndex(of: "Apple Identifier"), let unitsCol = header.firstIndex(of: "Units"), let typeCol = header.firstIndex(of: "Product Type Identifier"), let deviceCol = header.firstIndex(of: "Device") else { return [] } var totals: [String: Double] = [:] // "appID|metric|device" for row in lines.dropFirst() where row.count > max(idCol, unitsCol, typeCol, deviceCol) { let id = row[idCol], type = row[typeCol] guard appIDs.isEmpty || appIDs.contains(id) else { continue } let metric: Metric if downloadTypes.contains(type) { metric = .appDownloads } else if redownloadTypes.contains(type) { metric = .appRedownloads } else { continue } let device = Self.platform(device: row[deviceCol], desktopCountsAs: desktop[id] ?? "Mac") totals["\(id)|\(metric.rawValue)|\(device)", default: 0] += Double(row[unitsCol]) ?? 0 } var appTotals: [String: Double] = [:] // "appID|metric": the day's total across devices let platformPoints = totals.map { key, value -> DataPoint in let p = key.components(separatedBy: "|") appTotals["\(p[0])|\(p[1])", default: 0] += value return DataPoint(day: day, subject: p[0], metric: Metric(rawValue: p[1])!, breakdown: "platform:" + p[2], value: value) } let totalPoints = appTotals.map { key, value -> DataPoint in let p = key.components(separatedBy: "|") return DataPoint(day: day, subject: p[0], metric: Metric(rawValue: p[1])!, breakdown: nil, value: value) } return totalPoints + platformPoints } /// ES256 JWT, valid 20 minutes. func token(now: Date = .now, credentials: Credentials? = nil) throws -> String { guard let c = credentials ?? Credentials.saved else { throw AnalyticsError.notSignedIn("App Store Connect") } let kid = c.keyID, iss = c.issuerID, pem = c.privateKey let key = try P256.Signing.PrivateKey(pemRepresentation: pem) let header = try JSONSerialization.data(withJSONObject: ["alg": "ES256", "kid": kid, "typ": "JWT"]) let iat = Int(now.timeIntervalSince1970) let payload = try JSONSerialization.data(withJSONObject: ["iss": iss, "iat": iat, "exp": iat + 1200, "aud": "appstoreconnect-v1"]) let signingInput = header.base64URL + "." + payload.base64URL let signature = try key.signature(for: Data(signingInput.utf8)) return signingInput + "." + signature.rawRepresentation.base64URL } } /// Public star ratings and written reviews (no key): the iTunes lookup in every storefront and the customer /// reviews feed, for every app by the same developer (new apps are found automatically). Same as the old /// `reviews/pull_reviews.py`. public struct AppStoreRatings: Sendable { let session: URLSession public init(session: URLSession = .shared) { self.session = session } public static let storefronts = ("ae ag ai al am ao ar at au az bb be bf bg bh bj bm bn bo br bs bt bw by bz ca cg ch cl cn co cr " + "cv cy cz de dk dm do dz ec ee eg es fi fj fm fr gb gd gh gm gr gt gw gy hk hn hr hu id ie il in " + "is it jm jo jp ke kg kh kn kr kw ky kz la lb lc lk lr lt lu lv md mg mk ml mn mo mr ms mt mu mw " + "mx my mz na ne ng ni nl no np nz om pa pe pg ph pk pl pt pw py qa ro ru sa sb sc se sg si sk sl " + "sn sr st sv sz tc td th tj tm tn tr tt tw tz ua ug us uy uz vc ve vg vn ye za zw").split(separator: " ").map(String.init) public struct Result: Sendable { public var points: [DataPoint] = [] public var reviews: [Review] = [] /// Apple ID → newest App Store name, every app by the developer (including ones not tracked yet). public var names: [String: String] = [:] } func get(_ url: URL) async -> [String: Any]? { for _ in 0..<3 { var r = URLRequest(url: url); r.timeoutInterval = 20 r.setValue("Mozilla/5.0 (Macintosh) Graphley", forHTTPHeaderField: "User-Agent") if let json = try? await session.json(r) { return json } } return nil } /// Apple ID → name for every app by the developer of `seed`. public func discover(seed: [String]) async throws -> [String: String] { guard let lookup = await get(URL(string: "https://itunes.apple.com/lookup?id=\(seed.joined(separator: ","))&country=us")!), let results = lookup["results"] as? [[String: Any]], !results.isEmpty else { throw AnalyticsError.badResponse("Apple's app lookup (ratings not updated this run)") } var apps: [String: String] = [:] var artists = Set() for r in results { if let id = r["trackId"] as? Int { apps[String(id)] = r["trackName"] as? String ?? String(id) } if let a = r["artistId"] as? Int { artists.insert(a) } } for artist in artists { let url = URL(string: "https://itunes.apple.com/lookup?id=\(artist)&entity=software,macSoftware,iPadSoftware&country=us")! for r in (await get(url))?["results"] as? [[String: Any]] ?? [] where r["wrapperType"] as? String == "software" { if let id = r["trackId"] as? Int { apps[String(id)] = r["trackName"] as? String ?? String(id) } } } return apps } /// Today's weighted average and count per app (and count by country), plus written reviews from every /// storefront that has ratings and the US. Refuses the day when more than a tenth of the lookups fail. public func pull(seed: [String], today: String = DayKey.string(.now), firstSeen: [String: String] = [:]) async throws -> Result { var result = Result() result.names = try await discover(seed: seed) let ids = result.names.keys.sorted() struct Hit: Sendable { var country: String; var id: String; var avg: Double; var count: Int } struct Lookup: Sendable { var hits: [Hit]; var ok: Bool } var hits: [Hit] = [] var failed = 0 let joined = ids.joined(separator: ",") // Eight storefronts at a time. for start in stride(from: 0, to: Self.storefronts.count, by: 8) { let batch = Array(Self.storefronts[start.. Hit? in guard let id = (r["trackId"] as? Int).map(String.init), let count = r["userRatingCount"] as? Int, count > 0 else { return nil } return Hit(country: country.uppercased(), id: id, avg: r["averageUserRating"] as? Double ?? 0, count: count) }, ok: true) } } var all: [Lookup] = [] for await l in group { all.append(l) } return all } for l in lookups { if l.ok { hits += l.hits } else { failed += 1 } } } if failed > Self.storefronts.count / 10 { throw AnalyticsError.badResponse("\(failed) App Store storefront lookups failed, so ratings weren't recorded today") } for id in ids { let mine = hits.filter { $0.id == id } let count = mine.reduce(0) { $0 + $1.count } result.points.append(DataPoint(day: today, subject: id, metric: .ratingCount, value: Double(count))) if count > 0 { let avg = mine.reduce(0) { $0 + $1.avg * Double($1.count) } / Double(count) result.points.append(DataPoint(day: today, subject: id, metric: .rating, value: (avg * 100).rounded() / 100)) } for h in mine { result.points.append(DataPoint(day: today, subject: id, metric: .ratingCount, breakdown: "country:" + h.country, value: Double(h.count))) } } // Written reviews: every storefront with ratings, plus the US (the feed can lead the count). let targets = Set(hits.map { "\($0.country.lowercased())|\($0.id)" } + ids.map { "us|\($0)" }).sorted() let names = result.names let fetched = await withTaskGroup(of: [Review].self, returning: [Review].self) { group in for t in targets { let p = t.components(separatedBy: "|") let name = names[p[1]] ?? p[1] group.addTask { await reviews(country: p[0], appID: p[1], appName: name, today: today) } } var all: [Review] = [] for await list in group { all += list } return all } result.reviews += fetched for i in result.reviews.indices { result.reviews[i].firstSeen = firstSeen[result.reviews[i].id] ?? today } return result } func reviews(country: String, appID: String, appName: String, today: String) async -> [Review] { func label(_ v: Any?) -> String { if let list = v as? [Any] { return label(list.first) } return (v as? [String: Any])?["label"] as? String ?? "" } var out: [Review] = [] for page in 1...2 { let url = URL(string: "https://itunes.apple.com/\(country)/rss/customerreviews/page=\(page)/id=\(appID)/sortby=mostrecent/json")! let feed = (await get(url))?["feed"] as? [String: Any] var entries = feed?["entry"] as? [[String: Any]] ?? [] if let single = feed?["entry"] as? [String: Any] { entries = [single] } entries = entries.filter { $0["im:rating"] != nil } for e in entries { out.append(Review(id: label(e["id"]), appID: appID, appName: appName, country: country.uppercased(), stars: Int(label(e["im:rating"])) ?? 0, title: label(e["title"]), text: label(e["content"]), version: label(e["im:version"]), author: label((e["author"] as? [String: Any])?["name"]), date: String(label(e["updated"]).prefix(10)), firstSeen: today, url: "https://apps.apple.com/\(country)/app/id\(appID)?see-all=reviews")) } if entries.count < 50 { break } } return out } } extension Data { var base64URL: String { base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") } } enum Gzip { /// Strips the gzip header and trailer, then inflates the raw DEFLATE stream. static func inflate(_ data: Data) throws -> Data { let b = [UInt8](data) guard b.count > 18, b[0] == 0x1f, b[1] == 0x8b, b[2] == 8 else { return data } // not gzip: return as is let flags = b[3]; var i = 10 if flags & 0x04 != 0 { i += 2 + Int(b[i]) + Int(b[i + 1]) << 8 } // FEXTRA if flags & 0x08 != 0 { while i < b.count, b[i] != 0 { i += 1 }; i += 1 } // FNAME if flags & 0x10 != 0 { while i < b.count, b[i] != 0 { i += 1 }; i += 1 } // FCOMMENT if flags & 0x02 != 0 { i += 2 } // FHCRC let deflate = Data(b[i..<(b.count - 8)]) return try (deflate as NSData).decompressed(using: .zlib) as Data } }