Skip to content

armgit / xtool

Public Imported from GitHub
0

Cross-platform Xcode replacement. Build and deploy iOS apps with SwiftPM on Linux, Windows, macOS.

Begin adopting Concurrency

Kabir Oberai0fb3c15d7699
diff --git a/Supersign/Package.swift b/Supersign/Package.swift
index c6b4bc4..80b200c 100644
--- a/Supersign/Package.swift
+++ b/Supersign/Package.swift
@@ -33,7 +33,7 @@ let package = Package(
.package(path: "../SuperchargeCore"),
.package(path: "../SwiftyMobileDevice"),
.package(path: "../USBMuxSim"),
- .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.0.0"),
+ .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.18.0"),
],
targets: [
.target(
diff --git a/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift
index 4d0f7ef..29182b8 100644
--- a/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift
+++ b/Supersign/Sources/Supersign/DeveloperServices/DeveloperServicesClient.swift
@@ -72,11 +72,10 @@ public final class DeveloperServicesClient {
private func send<R: DeveloperServicesRequest>(
_ request: R,
- anisetteData: AnisetteData,
- completion: @escaping (Result<R.Value, Swift.Error>) -> Void
- ) {
+ anisetteData: AnisetteData
+ ) async throws -> R.Value {
guard let url = request.apiVersion.url(forAction: request.action) else {
- return completion(.failure(Error.malformedRequest))
+ throw Error.malformedRequest
}
var httpRequest = HTTPRequest(url: url, method: "POST")
@@ -98,39 +97,39 @@ public final class DeveloperServicesClient {
anisetteData.dictionary.forEach { httpRequest.headers[$0] = $1 }
- do {
- httpRequest.body = try .buffer(request.apiVersion.body(withParameters: request.parameters))
- } catch {
- return completion(.failure(error))
- }
+ httpRequest.body = try .buffer(request.apiVersion.body(withParameters: request.parameters))
request.configure(urlRequest: &httpRequest)
- httpClient.makeRequest(httpRequest) { result in
- let decoded: R.Response
- do {
- let resp = try result.get()
- // we don't throw if data is nil because sometimes no data is
- // okay (eg in the case of EmptyResponse)
- let data = resp.body ?? Data()
+ let resp = try await httpClient.makeRequest(httpRequest)
-// String(data: data, encoding: .utf8).map { print("\(url): \($0)") }
+ // we don't throw if data is nil because sometimes no data is
+ // okay (eg in the case of EmptyResponse)
+ let data = resp.body ?? Data()
- decoded = try request.apiVersion.decode(response: data)
- } catch {
- return completion(.failure(error))
- }
- request.parse(decoded, completion: completion)
+// String(data: data, encoding: .utf8).map { print("\(url): \($0)") }
+
+ let decoded: R.Response = try request.apiVersion.decode(response: data)
+
+ return try await withCheckedThrowingContinuation {
+ request.parse(decoded, completion: $0.resume(with:))
}
}
+ public func send<R: DeveloperServicesRequest>(_ request: R) async throws -> R.Value {
+ let anisetteData = try await anisetteDataProvider.fetchAnisetteData()
+ return try await self.send(request, anisetteData: anisetteData)
+ }
+
+ @available(*, deprecated, message: "Use async overload")
public func send<R: DeveloperServicesRequest>(
_ request: R,
completion: @escaping (Result<R.Value, Swift.Error>) -> Void
) {
- anisetteDataProvider.fetchAnisetteData { result in
- guard let anisetteData = result.get(withErrorHandler: completion) else { return }
- self.send(request, anisetteData: anisetteData, completion: completion)
+ Task {
+ completion(await Result {
+ try await send(request)
+ })
}
}
diff --git a/Supersign/Sources/Supersign/GrandSlam/Anisette/ADIDataProvider.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/ADIDataProvider.swift
index 886ac79..00ef540 100644
--- a/Supersign/Sources/Supersign/GrandSlam/Anisette/ADIDataProvider.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Anisette/ADIDataProvider.swift
@@ -17,23 +17,16 @@ private extension String {
}
public protocol RawADIProvider {
- func startProvisioning(
- spim: Data,
- completion: @escaping (Result<(String, Data), Error>) -> Void
- )
+ func startProvisioning(spim: Data) async throws -> (String, Data)
func endProvisioning(
session: String,
routingInfo: UInt64,
ptm: Data,
- tk: Data,
- completion: @escaping (Result<Data, Error>) -> Void
- )
-
- func requestOTP(
- provisioningInfo: Data,
- completion: @escaping (Result<(machineID: Data, otp: Data), Error>) -> Void
- )
+ tk: Data
+ ) async throws -> Data
+
+ func requestOTP(provisioningInfo: Data) async throws -> (machineID: Data, otp: Data)
}
// uses CoreADI APIs
@@ -120,138 +113,110 @@ public final class ADIDataProvider: AnisetteDataProvider {
private func sendRequest<Request: Encodable, Response: Decodable>(
endpoint: GrandSlamEndpoint,
- request: Request,
- completion: @escaping (Result<Response, Error>) -> Void
- ) {
- lookupManager.fetchURL(forEndpoint: endpoint) { result in
- guard let endpointURL = result.get(withErrorHandler: completion) else { return }
- let body: Data
- do {
- body = try Self.encoder.encode(GSARequest(request: request))
- } catch {
- return completion(.failure(error))
- }
- var request = HTTPRequest(
- url: endpointURL,
- method: "POST",
- headers: [
- "Content-Type": "text/x-xml-plist",
- AnisetteData.localUserIDKey: self.localUserID,
- "Accept-Language": "en_US"
- ],
- body: .buffer(body)
- )
- request.headers["X-MMe-Country"] = Locale.current.regionCode
-
- // Looks like Apple detects attempts to use a macOS client string on Windows :/
- request.headers[DeviceInfo.clientInfoKey] = """
- <PC> <Windows;6.2(0,0);9200> <com.apple.AuthKitWin/1 (com.apple.iCloud/7.21)>
- """
- request.headers[DeviceInfo.deviceIDKey] = self.deviceInfo.deviceID
-// request.headers[DeviceInfo.clientInfoKey] = self.deviceInfo.clientInfo.clientString
-// self.deviceInfo.dictionary.forEach { request.headers[$0] = $1 }
-
- self.httpClient.makeRequest(request) { result in
- guard let resp = result.get(withErrorHandler: completion) else { return }
- guard let body = resp.body else { return completion(.failure(ADIError.noResponse)) }
-// print(String(data: body, encoding: .utf8) ?? "<no utf8 data>")
- completion(Result {
- try GrandSlamOperationDecoder<Response>.decode(data: body)
- })
- }
- }
+ request: Request
+ ) async throws -> Response {
+ let endpointURL = try await lookupManager.fetchURL(forEndpoint: endpoint)
+
+ let body = try Self.encoder.encode(GSARequest(request: request))
+
+ var request = HTTPRequest(
+ url: endpointURL,
+ method: "POST",
+ headers: [
+ "Content-Type": "text/x-xml-plist",
+ AnisetteData.localUserIDKey: self.localUserID,
+ "Accept-Language": "en_US"
+ ],
+ body: .buffer(body)
+ )
+ request.headers["X-MMe-Country"] = Locale.current.regionCode
+
+ // Looks like Apple detects attempts to use a macOS client string on Windows :/
+ request.headers[DeviceInfo.clientInfoKey] = """
+ <PC> <Windows;6.2(0,0);9200> <com.apple.AuthKitWin/1 (com.apple.iCloud/7.21)>
+ """
+ request.headers[DeviceInfo.deviceIDKey] = self.deviceInfo.deviceID
+// request.headers[DeviceInfo.clientInfoKey] = self.deviceInfo.clientInfo.clientString
+// self.deviceInfo.dictionary.forEach { request.headers[$0] = $1 }
+
+ let resp = try await self.httpClient.makeRequest(request)
+
+ guard let body = resp.body else { throw ADIError.noResponse }
+// print(String(data: body, encoding: .utf8) ?? "<no utf8 data>")
+
+ return try GrandSlamOperationDecoder<Response>.decode(data: body)
}
private func endProvisioning(
id: String,
- cpim: Data,
- completion: @escaping (Result<(routingInfo: UInt64, provisioningInfo: Data), Error>) -> Void
- ) {
- sendRequest(
+ cpim: Data
+ ) async throws -> (routingInfo: UInt64, provisioningInfo: Data) {
+ let resp: EndProvisioningResponse = try await sendRequest(
endpoint: \.midFinishProvisioning,
request: EndProvisioningRequest(cpim: cpim.base64EncodedString())
- ) { (result: Result<EndProvisioningResponse, Error>) -> Void in
- guard let resp = result.get(withErrorHandler: completion) else { return }
- guard let rinfo = UInt64(resp.rinfo),
- let ptm = Data(base64Encoded: resp.ptm),
- let tk = Data(base64Encoded: resp.tk)
- else { return completion(.failure(ADIError.badEndResponse)) }
- self.rawProvider.endProvisioning(session: id, routingInfo: rinfo, ptm: ptm, tk: tk) { result in
- guard let provisioningInfo = result.get(withErrorHandler: completion) else { return }
- completion(.success((rinfo, provisioningInfo)))
- }
- }
+ )
+
+ guard let rinfo = UInt64(resp.rinfo),
+ let ptm = Data(base64Encoded: resp.ptm),
+ let tk = Data(base64Encoded: resp.tk)
+ else { throw ADIError.badEndResponse }
+
+ let provisioningInfo = try await self.rawProvider.endProvisioning(
+ session: id, routingInfo: rinfo, ptm: ptm, tk: tk
+ )
+
+ return (rinfo, provisioningInfo)
}
- private func provision(completion: @escaping (Result<(routingInfo: UInt64, provisioningInfo: Data), Error>) -> Void) {
- sendRequest(
+ private func provision() async throws -> (routingInfo: UInt64, provisioningInfo: Data) {
+ let resp: StartProvisioningResponse = try await sendRequest(
endpoint: \.midStartProvisioning,
request: StartProvisioningRequest()
- ) { (result: Result<StartProvisioningResponse, Error>) -> Void in
- guard let resp = result.get(withErrorHandler: completion) else { return }
- guard let spim = Data(base64Encoded: resp.spim) else {
- return completion(.failure(ADIError.badStartResponse))
- }
- self.rawProvider.startProvisioning(spim: spim) { result in
- guard let (id, cpim) = result.get(withErrorHandler: completion) else { return }
- self.endProvisioning(id: id, cpim: cpim, completion: completion)
- }
- }
+ )
+ guard let spim = Data(base64Encoded: resp.spim) else { throw ADIError.badStartResponse }
+ let (id, cpim) = try await rawProvider.startProvisioning(spim: spim)
+ return try await endProvisioning(id: id, cpim: cpim)
}
private func fetchAnisetteData(
routingInfo: UInt64,
- provisioningInfo: Data,
- completion: @escaping (Result<AnisetteData, Error>) -> Void
- ) {
+ provisioningInfo: Data
+ ) async throws -> AnisetteData {
let requestTime = Date()
- rawProvider.requestOTP(provisioningInfo: provisioningInfo) { result in
- guard let (mid, otp) = result.get(withErrorHandler: completion) else { return }
- completion(.success(AnisetteData(
- clientTime: requestTime,
- routingInfo: routingInfo,
- machineID: mid.base64EncodedString(),
- localUserID: self.localUserID,
- oneTimePassword: otp.base64EncodedString()
- )))
- }
+ let (mid, otp) = try await rawProvider.requestOTP(provisioningInfo: provisioningInfo)
+ return AnisetteData(
+ clientTime: requestTime,
+ routingInfo: routingInfo,
+ machineID: mid.base64EncodedString(),
+ localUserID: self.localUserID,
+ oneTimePassword: otp.base64EncodedString()
+ )
}
- public func resetProvisioning(completion: @escaping (Result<Void, Error>) -> Void) {
- completion(Result {
- try storage.setData(nil, forKey: Self.provisioningKey)
- try storage.setString(nil, forKey: Self.routingInfoKey)
- })
+ public func resetProvisioning() throws {
+ try storage.setData(nil, forKey: Self.provisioningKey)
+ try storage.setString(nil, forKey: Self.routingInfoKey)
}
- public func fetchAnisetteData(completion: @escaping (Result<AnisetteData, Error>) -> Void) {
- do {
- if let provisioningInfo = try storage.data(forKey: Self.provisioningKey),
- let routingInfoString = try storage.string(forKey: Self.routingInfoKey),
- let routingInfo = UInt64(routingInfoString) {
- return fetchAnisetteData(
- routingInfo: routingInfo,
- provisioningInfo: provisioningInfo,
- completion: completion
- )
- }
- } catch {
- return completion(.failure(error))
- }
- provision { result in
- guard let (rinfo, data) = result.get(withErrorHandler: completion) else { return }
- do {
- try self.storage.setData(data, forKey: Self.provisioningKey)
- try self.storage.setString("\(rinfo)", forKey: Self.routingInfoKey)
- } catch {
- return completion(.failure(error))
- }
- self.fetchAnisetteData(
- routingInfo: rinfo,
- provisioningInfo: data,
- completion: completion
+ public func fetchAnisetteData() async throws -> AnisetteData {
+ if let provisioningInfo = try storage.data(forKey: Self.provisioningKey),
+ let routingInfoString = try storage.string(forKey: Self.routingInfoKey),
+ let routingInfo = UInt64(routingInfoString) {
+ return try await fetchAnisetteData(
+ routingInfo: routingInfo,
+ provisioningInfo: provisioningInfo
)
}
+
+ let (rinfo, data) = try await provision()
+
+ try self.storage.setData(data, forKey: Self.provisioningKey)
+ try self.storage.setString("\(rinfo)", forKey: Self.routingInfoKey)
+
+ return try await fetchAnisetteData(
+ routingInfo: rinfo,
+ provisioningInfo: data
+ )
}
}
diff --git a/Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift
index 85341fe..95b160f 100644
--- a/Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Anisette/AnisetteDataProvider.swift
@@ -11,11 +11,11 @@ import Foundation
public protocol AnisetteDataProvider {
// This is a suggestion and not a requirement. The default implementation
// does nothing.
- func resetProvisioning(completion: @escaping (Result<Void, Error>) -> Void)
+ func resetProvisioning() async
- func fetchAnisetteData(completion: @escaping (Result<AnisetteData, Error>) -> Void)
+ func fetchAnisetteData() async throws -> AnisetteData
}
extension AnisetteDataProvider {
- public func resetProvisioning(completion: @escaping (Result<Void, Error>) -> Void) {}
+ public func resetProvisioning() async {}
}
diff --git a/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteADIProvider.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteADIProvider.swift
index 196db36..49cf6c4 100644
--- a/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteADIProvider.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteADIProvider.swift
@@ -21,9 +21,8 @@ public class SupersetteADIProvider: RawADIProvider {
private func makeRequest<Request: Encodable, Response: Decodable>(
endpoint: StaticString,
- request: Request,
- completion: @escaping (Result<Response, Swift.Error>) -> Void
- ) {
+ request: Request
+ ) async throws -> Response {
let url = URL(string: "\(Self.gateway)/\(endpoint)")!
var httpRequest = HTTPRequest(url: url, method: "POST")
httpRequest.headers = [
@@ -31,29 +30,15 @@ public class SupersetteADIProvider: RawADIProvider {
"Accept": "application/json",
"Superkey": "BF95B548-3C87-4BBD-8B96-534421368416"
]
- do {
- httpRequest.body = try .buffer(Self.encoder.encode(request))
- } catch {
- return completion(.failure(error))
- }
+ httpRequest.body = try .buffer(Self.encoder.encode(request))
// print("Requesting \(endpoint):")
// dump(request)
- httpClient.makeRequest(httpRequest) { result in
- let result = Result { () throws -> Response in
- let resp = try result.get()
- let data = try resp.body.orThrow(Error.invalidResponse)
- return try Self.decoder.decode(Response.self, from: data)
- }
-// print("Response for \(endpoint):")
-// dump(result)
- completion(result)
- }
+ let resp = try await httpClient.makeRequest(httpRequest)
+ let data = try resp.body.orThrow(Error.invalidResponse)
+ return try Self.decoder.decode(Response.self, from: data)
}
- public func startProvisioning(
- spim: Data,
- completion: @escaping (Result<(String, Data), Swift.Error>) -> Void
- ) {
+ public func startProvisioning(spim: Data) async throws -> (String, Data) {
struct Request: Encodable {
let spim: Data
}
@@ -61,21 +46,19 @@ public class SupersetteADIProvider: RawADIProvider {
let sessionID: String
let cpim: Data
}
- makeRequest(
+ let resp: Response = try await makeRequest(
endpoint: "start-provisioning",
request: Request(spim: spim)
- ) { (res: Result<Response, Swift.Error>) -> Void in
- completion(res.map { ($0.sessionID, $0.cpim) })
- }
+ )
+ return (resp.sessionID, resp.cpim)
}
public func endProvisioning(
session: String,
routingInfo: UInt64,
ptm: Data,
- tk: Data,
- completion: @escaping (Result<Data, Swift.Error>) -> Void
- ) {
+ tk: Data
+ ) async throws -> Data {
struct Request: Encodable {
let session: String
let rinfo: String
@@ -85,18 +68,14 @@ public class SupersetteADIProvider: RawADIProvider {
struct Response: Decodable {
let provisioningInfo: Data
}
- makeRequest(
+ let resp: Response = try await makeRequest(
endpoint: "end-provisioning",
request: Request(session: session, rinfo: "\(routingInfo)", ptm: ptm, tk: tk)
- ) { (res: Result<Response, Swift.Error>) -> Void in
- completion(res.map { $0.provisioningInfo })
- }
+ )
+ return resp.provisioningInfo
}
- public func requestOTP(
- provisioningInfo: Data,
- completion: @escaping (Result<(machineID: Data, otp: Data), Swift.Error>) -> Void
- ) {
+ public func requestOTP(provisioningInfo: Data) async throws -> (machineID: Data, otp: Data) {
struct Request: Encodable {
let provisioningInfo: Data
}
@@ -104,12 +83,11 @@ public class SupersetteADIProvider: RawADIProvider {
let mid: Data
let otp: Data
}
- makeRequest(
+ let resp: Response = try await makeRequest(
endpoint: "otp",
request: Request(provisioningInfo: provisioningInfo)
- ) { (res: Result<Response, Swift.Error>) -> Void in
- completion(res.map { ($0.mid, $0.otp) })
- }
+ )
+ return (resp.mid, resp.otp)
}
}
diff --git a/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift b/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift
index 5413d80..020360f 100644
--- a/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Anisette/Supersette/SupersetteDataProvider.swift
@@ -40,7 +40,7 @@ public class SupersetteDataProvider: AnisetteDataProvider {
let oneTimePassword: String
}
- public func fetchAnisetteData(completion: @escaping (Result<AnisetteData, Swift.Error>) -> Void) {
+ public func fetchAnisetteData() async throws -> AnisetteData {
let clientTime = Date()
var request = HTTPRequest(url: Self.gateway, method: "POST")
request.headers = [
@@ -48,28 +48,20 @@ public class SupersetteDataProvider: AnisetteDataProvider {
"Accept": "application/json",
"Superpass": "BF95B548-3C87-4BBD-8B96-534421368416"
]
- do {
- request.body = try .buffer(Self.encoder.encode(AnisetteRequestBody(
- deviceID: deviceInfo.deviceID,
- clientInfo: deviceInfo.clientInfo.clientString
- )))
- } catch {
- return completion(.failure(error))
- }
- httpClient.makeRequest(request) { result in
- completion(Result {
- let resp = try result.get()
- let data = try resp.body.orThrow(Error.invalidAnisetteData)
- let anisetteResponse = try Self.decoder.decode(AnisetteResponse.self, from: data)
- return AnisetteData(
- clientTime: clientTime,
- routingInfo: anisetteResponse.routingInfo,
- machineID: anisetteResponse.machineID,
- localUserID: anisetteResponse.localUserID,
- oneTimePassword: anisetteResponse.oneTimePassword
- )
- })
- }
+ request.body = try .buffer(Self.encoder.encode(AnisetteRequestBody(
+ deviceID: deviceInfo.deviceID,
+ clientInfo: deviceInfo.clientInfo.clientString
+ )))
+ let resp = try await httpClient.makeRequest(request)
+ let data = try resp.body.orThrow(Error.invalidAnisetteData)
+ let anisetteResponse = try Self.decoder.decode(AnisetteResponse.self, from: data)
+ return AnisetteData(
+ clientTime: clientTime,
+ routingInfo: anisetteResponse.routingInfo,
+ machineID: anisetteResponse.machineID,
+ localUserID: anisetteResponse.localUserID,
+ oneTimePassword: anisetteResponse.oneTimePassword
+ )
}
}
diff --git a/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift b/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift
index ecbe118..5c82bf7 100644
--- a/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/GrandSlamClient.swift
@@ -28,12 +28,10 @@ class GrandSlamClient {
self.httpClient = httpFactory.makeClient()
}
- private func send<R: GrandSlamRequest>(
- _ request: R,
- anisetteData: AnisetteData,
- url: URL,
- completion: @escaping (Result<R.Decoder.Value, Swift.Error>) -> Void
- ) {
+ func send<R: GrandSlamRequest>(_ request: R) async throws -> R.Decoder.Value {
+ let anisetteData = try await anisetteDataProvider.fetchAnisetteData()
+ let url = try await lookupManager.fetchURL(forEndpoint: R.endpoint)
+
let method = request.method(deviceInfo: deviceInfo, anisetteData: anisetteData)
var httpRequest = HTTPRequest(url: url, method: method.name)
httpRequest.headers = [
@@ -44,43 +42,19 @@ class GrandSlamClient {
case .get:
break
case .post(let body):
- do {
- httpRequest.body = try .buffer(PropertyListSerialization.data(
- fromPropertyList: body, format: .xml, options: 0
- ))
- } catch {
- return completion(.failure(error))
- }
+ httpRequest.body = try .buffer(PropertyListSerialization.data(
+ fromPropertyList: body, format: .xml, options: 0
+ ))
}
request.configure(request: &httpRequest, deviceInfo: deviceInfo, anisetteData: anisetteData)
- httpClient.makeRequest(httpRequest) { result in
- guard let resp = result.get(withErrorHandler: completion) else { return }
- completion(Result {
- try R.Decoder.decode(data: resp.body ?? .init())
- })
- }
+ let resp = try await httpClient.makeRequest(httpRequest)
+ return try R.Decoder.decode(data: resp.body ?? .init())
}
- private func send<R: GrandSlamRequest>(
- _ request: R,
- anisetteData: AnisetteData,
- completion: @escaping (Result<R.Decoder.Value, Swift.Error>) -> Void
- ) {
- lookupManager.fetchURL(forEndpoint: R.endpoint) { result in
- guard let url = result.get(withErrorHandler: completion) else { return }
- self.send(request, anisetteData: anisetteData, url: url, completion: completion)
- }
- }
-
- func send<R: GrandSlamRequest>(
- _ request: R,
- completion: @escaping (Result<R.Decoder.Value, Swift.Error>) -> Void
- ) {
- self.anisetteDataProvider.fetchAnisetteData { result in
- guard let anisetteData = result.get(withErrorHandler: completion) else { return }
- self.send(request, anisetteData: anisetteData, completion: completion)
- }
+ @available(*, deprecated, message: "Use async overload")
+ func send<R: GrandSlamRequest>(_ request: R, completion: @escaping (Result<R.Decoder.Value, Swift.Error>) -> Void) {
+ Task { completion(await Result { try await send(request) }) }
}
}
diff --git a/Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamLookupManager.swift b/Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamLookupManager.swift
index a545fa0..922b43b 100644
--- a/Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamLookupManager.swift
+++ b/Supersign/Sources/Supersign/GrandSlam/Lookup/GrandSlamLookupManager.swift
@@ -26,7 +26,7 @@ class GrandSlamLookupManager {
self.httpClient = httpFactory.makeClient()
}
- private func performLookup(completion: @escaping (Result<GrandSlamEndpoints, Error>) -> Void) {
+ private func performLookup() async throws -> GrandSlamEndpoints {
/* {
"X-Apple-I-Locale" = "en_IN";
"X-Apple-I-TimeZone" = "Asia/Kolkata";
@@ -45,33 +45,21 @@ class GrandSlamLookupManager {
]
request.headers["X-MMe-Country"] = Locale.current.regionCode
- httpClient.makeRequest(request) { result in
- guard let resp = result.get(withErrorHandler: completion) else { return }
- completion(Result {
- try self.decoder.decode(Response.self, from: resp.body ?? .init()).urls
- })
- }
+ let resp = try await httpClient.makeRequest(request)
+
+ return try self.decoder.decode(Response.self, from: resp.body ?? .init()).urls
}
- private func fetchEndpoints(completion: @escaping (Result<GrandSlamEndpoints, Error>) -> Void) {
- if let endpoints = endpoints {
- return completion(.success(endpoints))
- }
- performLookup { result in
- if case let .success(endpoints) = result {
- self.endpoints = endpoints
- }
- completion(result)
- }
+ private func fetchEndpoints() async throws -> GrandSlamEndpoints {
+ if let endpoints = endpoints { return endpoints }
+ let endpoints = try await performLookup()
+ self.endpoints = endpoints
+ return endpoints
}
- func fetchURL(
- forEndpoint endpoint: GrandSlamEndpoint,
- completion: @escaping (Result<URL, Error>) -> Void
- ) {
- fetchEndpoints { result in
- completion(result.map { URL(string: $0[keyPath: endpoint])! })
- }
+ func fetchURL(forEndpoint endpoint: GrandSlamEndpoint) async throws -> URL {
+ let endpoints = try await fetchEndpoints()
+ return URL(string: endpoints[keyPath: endpoint])!
}
}
diff --git a/Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift b/Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift
index 97520c5..384b53a 100644
--- a/Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift
+++ b/Supersign/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift
@@ -14,79 +14,28 @@ import NIOSSL
import NIOFoundationCompat
extension HTTPClient: HTTPClientProtocol {
-// private struct ReadError: Error {}
-//
-// private func read(
-// inputStream stream: InputStream,
-// chunkSize: Int,
-// eventLoop: EventLoop,
-// writer: @escaping (ByteBuffer) -> EventLoopFuture<Void>
-// ) -> EventLoopFuture<Void> {
-// var buf = ByteBuffer()
-// func _read() -> EventLoopFuture<Void> {
-// eventLoop.submit { () throws -> Int in
-// buf.clear()
-// return try buf.writeWithUnsafeMutableBytes(minimumWritableBytes: chunkSize) { raw in
-// let bound = raw.bindMemory(to: UInt8.self)
-// let res = stream.read(bound.baseAddress!, maxLength: bound.count)
-// guard res != -1 else { throw ReadError() }
-// return res
-// }
-// }.flatMap { bytesRead in
-// bytesRead == 0 ?
-// // we've reached the EOF
-// writer(buf) :
-// // there's more. Write and then keep reading.
-// writer(buf).flatMap(_read)
-// }
-// }
-// return _read()
-// }
-
@discardableResult
- public func makeRequest(
- _ request: HTTPRequest,
- completion: @escaping (Result<HTTPResponse, Error>) -> Void
- ) -> HTTPTask {
+ public func makeRequest(_ request: HTTPRequest) async throws -> HTTPResponse {
// print("Requesting \(request.url)")
-
- let headers = HTTPHeaders(request.headers.map { $0 })
- let body: HTTPClient.Body?
- switch request.body {
+ var httpRequest = HTTPClientRequest(url: request.url.absoluteString)
+ httpRequest.method = request.method.map(HTTPMethod.init(rawValue:)) ?? .GET
+ httpRequest.headers = HTTPHeaders(request.headers.map { $0 })
+ httpRequest.body = switch request.body {
case .buffer(let data):
- body = .data(data)
-// case .stream(let stream):
-// body = .stream { writer in
-// let eventLoop = writer.write(.byteBuffer(.init())).eventLoop
-// return self.read(inputStream: stream, chunkSize: 1024, eventLoop: eventLoop) {
-// writer.write(.byteBuffer($0))
-// }
-// }
+ .bytes(data)
+// case .stream(let stream):
+// .stream(...)
case nil:
- body = nil
+ nil
}
- let httpReq: HTTPClient.Request
- do {
- httpReq = try HTTPClient.Request(
- url: request.url,
- method: request.method.map(HTTPMethod.init(rawValue:)) ?? .GET,
- headers: headers,
- body: body
- )
- } catch {
- completion(.failure(error))
- return HTTPTask { }
- }
- let task = execute(request: httpReq, delegate: ResponseAccumulator(request: httpReq))
- task.futureResult.map { result in
- HTTPResponse(
- url: request.url,
- status: Int(result.status.code),
- headers: [String: String](uniqueKeysWithValues: result.headers.map { $0 }),
- body: result.body.flatMap { $0.getData(at: 0, length: $0.writerIndex) }
- )
- }.whenComplete(completion)
- return HTTPTask { task.cancel() }
+ let response = try await execute(httpRequest, deadline: .distantFuture)
+ let body = try await response.body.map(\.readableBytesView).reduce(into: Data(), +=)
+ return HTTPResponse(
+ url: request.url,
+ status: Int(response.status.code),
+ headers: [:],
+ body: body
+ )
}
}
diff --git a/Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift b/Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift
index 461a950..0da91ee 100644
--- a/Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift
+++ b/Supersign/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift
@@ -50,19 +50,8 @@ public struct HTTPResponse {
}
}
-public final class HTTPTask {
- private var cancellationHandler: () -> Void
- public init(cancellationHandler: @escaping () -> Void) {
- self.cancellationHandler = cancellationHandler
- }
- public func cancel() {
- cancellationHandler()
- }
-}
-
public protocol HTTPClientProtocol {
- @discardableResult
- func makeRequest(_ request: HTTPRequest, completion: @escaping (Result<HTTPResponse, Error>) -> Void) -> HTTPTask
+ func makeRequest(_ request: HTTPRequest) async throws -> HTTPResponse
}
public protocol HTTPClientFactory {
diff --git a/Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift b/Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift
index e1b7e66..325284f 100644
--- a/Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift
+++ b/Supersign/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift
@@ -11,11 +11,7 @@ import Foundation
public struct UnknownHTTPError: Error {}
extension URLSession: HTTPClientProtocol {
- @discardableResult
- public func makeRequest(
- _ request: HTTPRequest,
- completion: @escaping (Result<HTTPResponse, Error>) -> Void
- ) -> HTTPTask {
+ public func makeRequest(_ request: HTTPRequest) async throws -> HTTPResponse {
var req = URLRequest(url: request.url)
req.httpMethod = request.method
request.headers.forEach { k, v in
@@ -29,31 +25,22 @@ extension URLSession: HTTPClientProtocol {
case nil:
break
}
- let task = dataTask(with: req) { data, resp, error in
- if let error = error {
- return completion(.failure(error))
+ let (data, resp) = try await data(for: req)
+ guard let httpResp = resp as? HTTPURLResponse else { throw UnknownHTTPError() }
+ let headers = [String: String](
+ uniqueKeysWithValues: httpResp.allHeaderFields.compactMap { k, v in
+ guard let kStr = k as? String,
+ let vStr = v as? String
+ else { return nil }
+ return (kStr, vStr)
}
- guard let httpResp = resp as? HTTPURLResponse else {
- return completion(.failure(UnknownHTTPError()))
- }
- let headers = [String: String](
- uniqueKeysWithValues: httpResp.allHeaderFields.compactMap { k, v in
- guard let kStr = k as? String,
- let vStr = v as? String
- else { return nil }
- return (kStr, vStr)
- }
- )
- let resp = HTTPResponse(
- url: request.url,
- status: httpResp.statusCode,
- headers: headers,
- body: data
- )
- completion(.success(resp))
- }
- task.resume()
- return HTTPTask { task.cancel() }
+ )
+ return HTTPResponse(
+ url: request.url,
+ status: httpResp.statusCode,
+ headers: headers,
+ body: data
+ )
}
}
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/DSCommand.swift b/SupersignCLISupport/Sources/SupersignCLISupport/DSCommand.swift
index 4a22a85..0311216 100644
--- a/SupersignCLISupport/Sources/SupersignCLISupport/DSCommand.swift
+++ b/SupersignCLISupport/Sources/SupersignCLISupport/DSCommand.swift
@@ -17,7 +17,7 @@ private extension AuthToken {
username: String?,
password: String?,
resetProvisioning: Bool = false
- ) throws -> Self {
+ ) async throws -> Self {
guard let username = username ?? Console.prompt("Apple ID: "), !username.isEmpty else {
throw Console.Error("A non-empty Apple ID is required.")
}
@@ -31,7 +31,7 @@ private extension AuthToken {
// storage: SupersignCLI.config.storage
// )
if resetProvisioning {
- try withSyncContinuation(provider.resetProvisioning(completion:))
+ await provider.resetProvisioning()
}
let authDelegate = SupersignCLIAuthDelegate()
let manager = try DeveloperServicesLoginManager(
@@ -50,16 +50,16 @@ private extension AuthToken {
return AuthToken(appleID: username, dsToken: token)
}
- static func retrieve(deviceInfo: DeviceInfo, account: String?) throws -> Self {
+ static func retrieve(deviceInfo: DeviceInfo, account: String?) async throws -> Self {
if let account = account, let token = Self(string: account) {
return token
} else {
- return try retrieve(deviceInfo: deviceInfo, username: account, password: nil)
+ return try await retrieve(deviceInfo: deviceInfo, username: account, password: nil)
}
}
}
-struct DSLoginCommand: ParsableCommand {
+struct DSLoginCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "login",
abstract: "Obtain an Apple ID authentication token"
@@ -69,8 +69,8 @@ struct DSLoginCommand: ParsableCommand {
@Option(name: [.short, .long], help: "Apple ID") var username: String?
@Option(name: [.short, .long]) var password: String?
- func run() throws {
- let fullToken = try AuthToken.retrieve(
+ func run() async throws {
+ let fullToken = try await AuthToken.retrieve(
deviceInfo: .fetch(),
username: self.username,
password: self.password,
@@ -83,7 +83,7 @@ struct DSLoginCommand: ParsableCommand {
}
}
-struct DSTeamsListCommand: ParsableCommand {
+struct DSTeamsListCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "list",
abstract: "List Developer Services teams"
@@ -91,22 +91,20 @@ struct DSTeamsListCommand: ParsableCommand {
@Option(name: .shortAndLong) var account: String?
- func run() throws {
+ func run() async throws {
let deviceInfo = try DeviceInfo.fetch()
let anisetteProvider = SupersetteDataProvider(deviceInfo: deviceInfo)
// let anisetteProvider = try ADIDataProvider.supersetteProvider(
// deviceInfo: deviceInfo, storage: SupersignCLI.config.storage
// )
- let token = try AuthToken.retrieve(deviceInfo: deviceInfo, account: account)
+ let token = try await AuthToken.retrieve(deviceInfo: deviceInfo, account: account)
let client = DeveloperServicesClient(
loginToken: token.dsToken,
deviceInfo: deviceInfo,
anisetteProvider: anisetteProvider
)
- let teams: [DeveloperServicesTeam] = try withSyncContinuation {
- client.send(DeveloperServicesListTeamsRequest(), completion: $0)
- }
+ let teams: [DeveloperServicesTeam] = try await client.send(DeveloperServicesListTeamsRequest())
print(
teams.map {
"\($0.name) [\($0.status)]: \($0.id.rawValue)" +
@@ -116,35 +114,30 @@ struct DSTeamsListCommand: ParsableCommand {
}
}
-struct DSAnisetteCommand: ParsableCommand {
+struct DSAnisetteCommand: AsyncParsableCommand {
private class Provider: RawADIProvider {
- func startProvisioning(
- spim: Data,
- completion: @escaping (Result<(String, Data), Error>) -> Void
- ) {
+ func startProvisioning(spim: Data) -> (String, Data) {
print("spim: \(spim.base64EncodedString())")
- completion(.success(("", Data(base64Encoded: Console.prompt("cpim: ")!)!)))
+ return ("", Data(base64Encoded: Console.prompt("cpim: ")!)!)
}
func endProvisioning(
session: String,
routingInfo: UInt64,
ptm: Data,
- tk: Data,
- completion: @escaping (Result<Data, Error>) -> Void
- ) {
+ tk: Data
+ ) -> Data {
print("""
rinfo: \(routingInfo)
ptm: \(ptm.base64EncodedString())
tk: \(tk.base64EncodedString())
""")
+ return Data(base64Encoded: Console.prompt("pinfo: ")!)!
}
- func requestOTP(
- provisioningInfo: Data,
- completion: @escaping (Result<(machineID: Data, otp: Data), Error>) -> Void
- ) {
+ func requestOTP(provisioningInfo: Data) -> (machineID: Data, otp: Data) {
print("otp; pinfo: \(provisioningInfo)")
+ return (Data(), Data())
}
}
@@ -153,15 +146,14 @@ struct DSAnisetteCommand: ParsableCommand {
abstract: "Test out Anisette data"
)
- func run() throws {
- let res = try withSyncContinuation {
- // swiftlint:disable:next force_try
- try! ADIDataProvider(
- rawProvider: Provider(),
- deviceInfo: .current()!,
- storage: SupersignCLI.config.storage
- ).fetchAnisetteData(completion: $0)
- }
+ func run() async throws {
+ // swiftlint:disable:next force_try
+ let res = try! await ADIDataProvider(
+ rawProvider: Provider(),
+ deviceInfo: .current()!,
+ storage: SupersignCLI.config.storage
+ ).fetchAnisetteData()
+
print(res)
}
}
@@ -175,7 +167,7 @@ struct DSTeamsCommand: ParsableCommand {
)
}
-struct DSCommand: ParsableCommand {
+struct DSCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "ds",
abstract: "Interact with Apple Developer Services",
diff --git a/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCommand.swift b/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCommand.swift
index 3fbf696..c62a32c 100644
--- a/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCommand.swift
+++ b/SupersignCLISupport/Sources/SupersignCLISupport/SupersignCommand.swift
@@ -19,14 +19,23 @@ public enum SupersignCLI {
private static var _config: Configuration!
static var config: Configuration { _config }
- public static func run(configuration: Configuration, arguments: [String]? = nil) throws {
+ public static func run(configuration: Configuration, arguments: [String]? = nil) async throws {
_config = configuration
defer { defaultHTTPClientFactory.shutdown() }
- SupersignCommand.main(arguments)
+ do {
+ var command = try SupersignCommand.parseAsRoot(arguments)
+ if var asyncCommand = command as? AsyncParsableCommand {
+ try await asyncCommand.run()
+ } else {
+ try command.run()
+ }
+ } catch {
+ SupersignCommand.exit(withError: error)
+ }
}
}
-struct SupersignCommand: ParsableCommand {
+struct SupersignCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "supersign",
abstract: "The Supersign command line tool",