xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XKit / GrandSlam / Lookup / GrandSlamLookupManager.swift
GrandSlamLookupManager.swift67 lines · 2.1 KiBRaw
| 1 | // |
| 2 | // GrandSlamLookupManager.swift |
| 3 | // XKit |
| 4 | // |
| 5 | // Created by Kabir Oberai on 19/11/19. |
| 6 | // Copyright © 2019 Kabir Oberai. All rights reserved. |
| 7 | // |
| 8 | |
| 9 | import Foundation |
| 10 | import Dependencies |
| 11 | import HTTPTypesFoundation |
| 12 | |
| 13 | actor GrandSlamLookupManager { |
| 14 | |
| 15 | private static let lookupURL = URL(string: "https://gsa.apple.com/grandslam/GsService2/lookup")! |
| 16 | |
| 17 | private struct Response: Decodable { |
| 18 | let urls: GrandSlamEndpoints |
| 19 | } |
| 20 | |
| 21 | private let decoder = PropertyListDecoder() |
| 22 | private var endpoints: GrandSlamEndpoints? |
| 23 | |
| 24 | @Dependency(\.anisetteDataProvider) var anisetteDataProvider |
| 25 | @Dependency(\.httpClient) var httpClient |
| 26 | |
| 27 | init() {} |
| 28 | |
| 29 | private func performLookup() async throws -> GrandSlamEndpoints { |
| 30 | let deviceInfo = try await anisetteDataProvider.deviceInfo() |
| 31 | |
| 32 | var request = HTTPRequest(url: Self.lookupURL) |
| 33 | request.headerFields = [ |
| 34 | .userAgent: deviceInfo.akdUserAgent, |
| 35 | .init(AnisetteData.iLocaleKey)!: Locale.current.identifier, |
| 36 | .init(AnisetteData.timeZoneKey)!: TimeZone.current.identifier, |
| 37 | .init("X-Apple-I-TimeZone-Offset")!: "\(TimeZone.current.secondsFromGMT())" |
| 38 | ] |
| 39 | request.headerFields[.init("X-MMe-Country")!] = Locale.current.region?.identifier |
| 40 | |
| 41 | for (key, value) in deviceInfo.dictionary { |
| 42 | request.headerFields[.init(key)!] = value |
| 43 | } |
| 44 | |
| 45 | let (_, body) = try await httpClient.makeRequest(request, ephemeral: true) |
| 46 | |
| 47 | return try self.decoder.decode(Response.self, from: body).urls |
| 48 | } |
| 49 | |
| 50 | private func fetchEndpoints() async throws -> GrandSlamEndpoints { |
| 51 | if let endpoints = endpoints { return endpoints } |
| 52 | let endpoints = try await performLookup() |
| 53 | self.endpoints = endpoints |
| 54 | return endpoints |
| 55 | } |
| 56 | |
| 57 | func fetchURL(forEndpoint endpoint: GrandSlamEndpoint) async throws -> URL { |
| 58 | switch endpoint { |
| 59 | case .lookup(let keyPath): |
| 60 | let endpoints = try await fetchEndpoints() |
| 61 | return URL(string: endpoints[keyPath: keyPath])! |
| 62 | case .url(let url): |
| 63 | return url |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | } |