Branchwell

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

Raw 17.0 KB on d69ca9c4c8ff088be085e80dbb7478e9463bddf8
1import Foundation
2import CryptoKit
3
4/// App Store Connect sales reports: daily first downloads and redownloads per app and device.
5/// Needs an App Store Connect API key (Sales and Reports role) saved in the Keychain.
6public struct AppStoreConnect: Sendable {
7 static let downloadTypes: Set<String> = ["1", "1F", "1T", "1E", "F1"]
8 static let redownloadTypes: Set<String> = ["3", "3F", "3T", "F3"]
9 let session: URLSession
10 public init(session: URLSession = .shared) { self.session = session }
11
12 public var isConfigured: Bool {
13 [Keychain.Item.appStoreKeyID, .appStoreIssuerID, .appStorePrivateKey, .appStoreVendorNumber].allSatisfy(Keychain.has)
14 }
15
16 /// Pulls each missing day (Apple publishes a day's report the next morning, Pacific time).
17 public func daily(apps: [StoreApp], days: [String]) async throws -> [DataPoint] {
18 guard isConfigured else { throw AnalyticsError.notSignedIn("App Store Connect") }
19 let listed = apps.filter(\.hasAppStoreListing)
20 let ids = Set(listed.map(\.id))
21 let desktop = Dictionary(uniqueKeysWithValues: listed.map { ($0.id, $0.desktopCountsAs ?? "Mac") })
22 var points: [DataPoint] = []
23 for day in days {
24 // Apple 404s a day it hasn't published yet: skip it (never stored as zero) so the next run asks again.
25 guard let tsv = try await report(day: day) else { continue }
26 points += Self.parse(tsv: tsv, day: day, appIDs: ids, desktop: desktop)
27 }
28 return points
29 }
30
31 /// The four parts of an App Store Connect API key. The app's form builds one to check it before saving.
32 public struct Credentials: Sendable {
33 public var keyID, issuerID, vendorNumber, privateKey: String
34 public init(keyID: String, issuerID: String, vendorNumber: String, privateKey: String) {
35 self.keyID = keyID; self.issuerID = issuerID; self.vendorNumber = vendorNumber; self.privateKey = privateKey
36 }
37 /// The saved key, if all four parts are in the Keychain.
38 public static var saved: Credentials? {
39 guard let k = Keychain.get(.appStoreKeyID), let i = Keychain.get(.appStoreIssuerID),
40 let v = Keychain.get(.appStoreVendorNumber), let p = Keychain.get(.appStorePrivateKey) else { return nil }
41 return Credentials(keyID: k, issuerID: i, vendorNumber: v, privateKey: p)
42 }
43 public func save() throws {
44 try Keychain.set(keyID, for: .appStoreKeyID); try Keychain.set(issuerID, for: .appStoreIssuerID)
45 try Keychain.set(vendorNumber, for: .appStoreVendorNumber); try Keychain.set(privateKey, for: .appStorePrivateKey)
46 }
47 public static func remove() {
48 [Keychain.Item.appStoreKeyID, .appStoreIssuerID, .appStoreVendorNumber, .appStorePrivateKey].forEach(Keychain.remove)
49 }
50 /// True when the text is a PEM private key that CryptoKit can sign with.
51 public static func isValidPrivateKey(_ pem: String) -> Bool { (try? P256.Signing.PrivateKey(pemRepresentation: pem)) != nil }
52 }
53
54 /// Asks Apple for one recent day's sales report with these credentials. Throws `AnalyticsError.http`
55 /// (401 bad key, 403 wrong role) or a URL error. A day without sales counts as success.
56 public func check(_ credentials: Credentials) async throws {
57 _ = try await report(day: DayKey.lastDays(2).first ?? "", credentials: credentials)
58 }
59
60 func report(day: String, credentials: Credentials? = nil) async throws -> String? {
61 var c = URLComponents(string: "https://api.appstoreconnect.apple.com/v1/salesReports")!
62 c.queryItems = [
63 .init(name: "filter[frequency]", value: "DAILY"), .init(name: "filter[reportType]", value: "SALES"),
64 .init(name: "filter[reportSubType]", value: "SUMMARY"), .init(name: "filter[version]", value: "1_1"),
65 .init(name: "filter[vendorNumber]", value: credentials?.vendorNumber ?? Keychain.get(.appStoreVendorNumber)),
66 .init(name: "filter[reportDate]", value: day)
67 ]
68 var r = URLRequest(url: c.url!)
69 r.setValue("Bearer \(try token(credentials: credentials))", forHTTPHeaderField: "Authorization")
70 r.setValue("application/a-gzip", forHTTPHeaderField: "Accept")
71 let (data, response) = try await session.data(for: r)
72 let code = (response as? HTTPURLResponse)?.statusCode ?? 0
73 if code == 404 { return nil } // no sales that day, or not published yet
74 guard code == 200 else { throw AnalyticsError.http(code, String(decoding: data, as: UTF8.self)) }
75 return String(decoding: try Gzip.inflate(data), as: UTF8.self)
76 }
77
78 /// Apple's Device column as Graphley shows it: Desktop is a Mac (or, for an iOS-only app like Jotley, the
79 /// iPhone app running on an Apple Silicon Mac), Apple Vision is Vision Pro.
80 public static func platform(device: String, desktopCountsAs: String = "Mac") -> String {
81 switch device.trimmingCharacters(in: .whitespaces).lowercased() {
82 case "iphone", "ipod", "ipod touch": "iPhone"
83 case "ipad": "iPad"
84 case "desktop", "mac", "macos": desktopCountsAs
85 case "apple vision", "vision", "apple vision pro", "visionos", "vision pro": "Vision Pro"
86 case "apple tv", "appletv", "tvos": "Apple TV"
87 case "apple watch", "watchos": "Apple Watch"
88 default: device
89 }
90 }
91
92 static func parse(tsv: String, day: String, appIDs: Set<String>, desktop: [String: String] = [:]) -> [DataPoint] {
93 let lines = tsv.split(whereSeparator: \.isNewline).map { $0.components(separatedBy: "\t") }
94 guard let header = lines.first,
95 let idCol = header.firstIndex(of: "Apple Identifier"), let unitsCol = header.firstIndex(of: "Units"),
96 let typeCol = header.firstIndex(of: "Product Type Identifier"), let deviceCol = header.firstIndex(of: "Device")
97 else { return [] }
98 var totals: [String: Double] = [:] // "appID|metric|device"
99 for row in lines.dropFirst() where row.count > max(idCol, unitsCol, typeCol, deviceCol) {
100 let id = row[idCol], type = row[typeCol]
101 guard appIDs.isEmpty || appIDs.contains(id) else { continue }
102 let metric: Metric
103 if downloadTypes.contains(type) { metric = .appDownloads }
104 else if redownloadTypes.contains(type) { metric = .appRedownloads }
105 else { continue }
106 let device = Self.platform(device: row[deviceCol], desktopCountsAs: desktop[id] ?? "Mac")
107 totals["\(id)|\(metric.rawValue)|\(device)", default: 0] += Double(row[unitsCol]) ?? 0
108 }
109 var appTotals: [String: Double] = [:] // "appID|metric": the day's total across devices
110 let platformPoints = totals.map { key, value -> DataPoint in
111 let p = key.components(separatedBy: "|")
112 appTotals["\(p[0])|\(p[1])", default: 0] += value
113 return DataPoint(day: day, subject: p[0], metric: Metric(rawValue: p[1])!, breakdown: "platform:" + p[2], value: value)
114 }
115 let totalPoints = appTotals.map { key, value -> DataPoint in
116 let p = key.components(separatedBy: "|")
117 return DataPoint(day: day, subject: p[0], metric: Metric(rawValue: p[1])!, breakdown: nil, value: value)
118 }
119 return totalPoints + platformPoints
120 }
121
122 /// ES256 JWT, valid 20 minutes.
123 func token(now: Date = .now, credentials: Credentials? = nil) throws -> String {
124 guard let c = credentials ?? Credentials.saved else { throw AnalyticsError.notSignedIn("App Store Connect") }
125 let kid = c.keyID, iss = c.issuerID, pem = c.privateKey
126 let key = try P256.Signing.PrivateKey(pemRepresentation: pem)
127 let header = try JSONSerialization.data(withJSONObject: ["alg": "ES256", "kid": kid, "typ": "JWT"])
128 let iat = Int(now.timeIntervalSince1970)
129 let payload = try JSONSerialization.data(withJSONObject: ["iss": iss, "iat": iat, "exp": iat + 1200, "aud": "appstoreconnect-v1"])
130 let signingInput = header.base64URL + "." + payload.base64URL
131 let signature = try key.signature(for: Data(signingInput.utf8))
132 return signingInput + "." + signature.rawRepresentation.base64URL
133 }
134}
135
136/// Public star ratings and written reviews (no key): the iTunes lookup in every storefront and the customer
137/// reviews feed, for every app by the same developer (new apps are found automatically). Same as the old
138/// `reviews/pull_reviews.py`.
139public struct AppStoreRatings: Sendable {
140 let session: URLSession
141 public init(session: URLSession = .shared) { self.session = session }
142
143 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 "
144 + "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 "
145 + "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 "
146 + "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 "
147 + "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)
148
149 public struct Result: Sendable {
150 public var points: [DataPoint] = []
151 public var reviews: [Review] = []
152 /// Apple ID → newest App Store name, every app by the developer (including ones not tracked yet).
153 public var names: [String: String] = [:]
154 }
155
156 func get(_ url: URL) async -> [String: Any]? {
157 for _ in 0..<3 {
158 var r = URLRequest(url: url); r.timeoutInterval = 20
159 r.setValue("Mozilla/5.0 (Macintosh) Graphley", forHTTPHeaderField: "User-Agent")
160 if let json = try? await session.json(r) { return json }
161 }
162 return nil
163 }
164
165 /// Apple ID → name for every app by the developer of `seed`.
166 public func discover(seed: [String]) async throws -> [String: String] {
167 guard let lookup = await get(URL(string: "https://itunes.apple.com/lookup?id=\(seed.joined(separator: ","))&country=us")!),
168 let results = lookup["results"] as? [[String: Any]], !results.isEmpty
169 else { throw AnalyticsError.badResponse("Apple's app lookup (ratings not updated this run)") }
170 var apps: [String: String] = [:]
171 var artists = Set<Int>()
172 for r in results {
173 if let id = r["trackId"] as? Int { apps[String(id)] = r["trackName"] as? String ?? String(id) }
174 if let a = r["artistId"] as? Int { artists.insert(a) }
175 }
176 for artist in artists {
177 let url = URL(string: "https://itunes.apple.com/lookup?id=\(artist)&entity=software,macSoftware,iPadSoftware&country=us")!
178 for r in (await get(url))?["results"] as? [[String: Any]] ?? [] where r["wrapperType"] as? String == "software" {
179 if let id = r["trackId"] as? Int { apps[String(id)] = r["trackName"] as? String ?? String(id) }
180 }
181 }
182 return apps
183 }
184
185 /// Today's weighted average and count per app (and count by country), plus written reviews from every
186 /// storefront that has ratings and the US. Refuses the day when more than a tenth of the lookups fail.
187 public func pull(seed: [String], today: String = DayKey.string(.now), firstSeen: [String: String] = [:]) async throws -> Result {
188 var result = Result()
189 result.names = try await discover(seed: seed)
190 let ids = result.names.keys.sorted()
191 struct Hit: Sendable { var country: String; var id: String; var avg: Double; var count: Int }
192 struct Lookup: Sendable { var hits: [Hit]; var ok: Bool }
193 var hits: [Hit] = []
194 var failed = 0
195 let joined = ids.joined(separator: ",")
196 // Eight storefronts at a time.
197 for start in stride(from: 0, to: Self.storefronts.count, by: 8) {
198 let batch = Array(Self.storefronts[start..<min(start + 8, Self.storefronts.count)])
199 let lookups = await withTaskGroup(of: Lookup.self, returning: [Lookup].self) { group in
200 for country in batch {
201 group.addTask {
202 let url = URL(string: "https://itunes.apple.com/lookup?id=\(joined)&country=\(country)")!
203 guard let rows = (await get(url))?["results"] as? [[String: Any]] else { return Lookup(hits: [], ok: false) }
204 return Lookup(hits: rows.compactMap { r -> Hit? in
205 guard let id = (r["trackId"] as? Int).map(String.init), let count = r["userRatingCount"] as? Int, count > 0 else { return nil }
206 return Hit(country: country.uppercased(), id: id, avg: r["averageUserRating"] as? Double ?? 0, count: count)
207 }, ok: true)
208 }
209 }
210 var all: [Lookup] = []
211 for await l in group { all.append(l) }
212 return all
213 }
214 for l in lookups { if l.ok { hits += l.hits } else { failed += 1 } }
215 }
216 if failed > Self.storefronts.count / 10 {
217 throw AnalyticsError.badResponse("\(failed) App Store storefront lookups failed, so ratings weren't recorded today")
218 }
219 for id in ids {
220 let mine = hits.filter { $0.id == id }
221 let count = mine.reduce(0) { $0 + $1.count }
222 result.points.append(DataPoint(day: today, subject: id, metric: .ratingCount, value: Double(count)))
223 if count > 0 {
224 let avg = mine.reduce(0) { $0 + $1.avg * Double($1.count) } / Double(count)
225 result.points.append(DataPoint(day: today, subject: id, metric: .rating, value: (avg * 100).rounded() / 100))
226 }
227 for h in mine { result.points.append(DataPoint(day: today, subject: id, metric: .ratingCount, breakdown: "country:" + h.country, value: Double(h.count))) }
228 }
229 // Written reviews: every storefront with ratings, plus the US (the feed can lead the count).
230 let targets = Set(hits.map { "\($0.country.lowercased())|\($0.id)" } + ids.map { "us|\($0)" }).sorted()
231 let names = result.names
232 let fetched = await withTaskGroup(of: [Review].self, returning: [Review].self) { group in
233 for t in targets {
234 let p = t.components(separatedBy: "|")
235 let name = names[p[1]] ?? p[1]
236 group.addTask { await reviews(country: p[0], appID: p[1], appName: name, today: today) }
237 }
238 var all: [Review] = []
239 for await list in group { all += list }
240 return all
241 }
242 result.reviews += fetched
243 for i in result.reviews.indices { result.reviews[i].firstSeen = firstSeen[result.reviews[i].id] ?? today }
244 return result
245 }
246
247 func reviews(country: String, appID: String, appName: String, today: String) async -> [Review] {
248 func label(_ v: Any?) -> String {
249 if let list = v as? [Any] { return label(list.first) }
250 return (v as? [String: Any])?["label"] as? String ?? ""
251 }
252 var out: [Review] = []
253 for page in 1...2 {
254 let url = URL(string: "https://itunes.apple.com/\(country)/rss/customerreviews/page=\(page)/id=\(appID)/sortby=mostrecent/json")!
255 let feed = (await get(url))?["feed"] as? [String: Any]
256 var entries = feed?["entry"] as? [[String: Any]] ?? []
257 if let single = feed?["entry"] as? [String: Any] { entries = [single] }
258 entries = entries.filter { $0["im:rating"] != nil }
259 for e in entries {
260 out.append(Review(id: label(e["id"]), appID: appID, appName: appName, country: country.uppercased(),
261 stars: Int(label(e["im:rating"])) ?? 0, title: label(e["title"]), text: label(e["content"]),
262 version: label(e["im:version"]), author: label((e["author"] as? [String: Any])?["name"]),
263 date: String(label(e["updated"]).prefix(10)), firstSeen: today,
264 url: "https://apps.apple.com/\(country)/app/id\(appID)?see-all=reviews"))
265 }
266 if entries.count < 50 { break }
267 }
268 return out
269 }
270}
271
272extension Data {
273 var base64URL: String {
274 base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
275 }
276}
277
278enum Gzip {
279 /// Strips the gzip header and trailer, then inflates the raw DEFLATE stream.
280 static func inflate(_ data: Data) throws -> Data {
281 let b = [UInt8](data)
282 guard b.count > 18, b[0] == 0x1f, b[1] == 0x8b, b[2] == 8 else { return data } // not gzip: return as is
283 let flags = b[3]; var i = 10
284 if flags & 0x04 != 0 { i += 2 + Int(b[i]) + Int(b[i + 1]) << 8 } // FEXTRA
285 if flags & 0x08 != 0 { while i < b.count, b[i] != 0 { i += 1 }; i += 1 } // FNAME
286 if flags & 0x10 != 0 { while i < b.count, b[i] != 0 { i += 1 }; i += 1 } // FCOMMENT
287 if flags & 0x02 != 0 { i += 2 } // FHCRC
288 let deflate = Data(b[i..<(b.count - 8)])
289 return try (deflate as NSData).decompressed(using: .zlib) as Data
290 }
291}