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.

Library download progress

Kabir Oberai74d2c5d76f3d
diff --git a/Sources/Supersign/GrandSlam/Anisette/SupersetteADIProvider.swift b/Sources/Supersign/GrandSlam/Anisette/SupersetteADIProvider.swift
index 5325fe0..2fc8974 100644
--- a/Sources/Supersign/GrandSlam/Anisette/SupersetteADIProvider.swift
+++ b/Sources/Supersign/GrandSlam/Anisette/SupersetteADIProvider.swift
@@ -26,9 +26,16 @@ public struct SupersetteADIProvider: RawADIProvider {
let applemusic = tmp.appending(path: "applemusic.apk")
if !applemusic.exists {
- print("Downloading libraries...")
+ print("[Downloading libraries] ...", terminator: "")
+ fflush(stdout)
let url = URL(string: "https://apps.mzstatic.com/content/android-apple-music-apk/applemusic.apk")!
- let data = try await httpClient.makeRequest(HTTPRequest(url: url)).body!
+ defer { print("") }
+ let data = try await httpClient.makeRequest(HTTPRequest(url: url)) { progress in
+ guard let progress else { return }
+ let progString = "\(Int(progress * 100))%".padding(toLength: 4, leading: true)
+ print("\r[Downloading libraries] \(progString)", terminator: "")
+ fflush(stdout)
+ }.body!
try data.write(to: applemusic)
}
@@ -167,4 +174,15 @@ private func check(_ adiStatus: Int32) throws {
}
}
+extension StringProtocol {
+ fileprivate func padding(
+ toLength minLength: Int,
+ withPad pad: Character = " ",
+ leading: Bool = false
+ ) -> String {
+ let justPadding = String(repeating: pad, count: Swift.max(minLength - count, 0))
+ return leading ? justPadding + self : self + justPadding
+ }
+}
+
#endif
diff --git a/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift b/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift
index 5938b1b..c39bcb4 100644
--- a/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift
+++ b/Sources/Supersign/HTTPClientProtocol/AsyncHTTPClient+HTTP.swift
@@ -16,7 +16,7 @@ import WebSocketKit
extension HTTPClient: HTTPClientProtocol {
@discardableResult
- public func makeRequest(_ request: HTTPRequest) async throws -> HTTPResponse {
+ public func makeRequest(_ request: HTTPRequest, onProgress: (Double?) -> Void) async throws -> HTTPResponse {
// print("Requesting \(request.url)")
var httpRequest = HTTPClientRequest(url: request.url.absoluteString)
httpRequest.method = request.method.map(HTTPMethod.init(rawValue:)) ?? .GET
@@ -24,13 +24,21 @@ extension HTTPClient: HTTPClientProtocol {
httpRequest.body = switch request.body {
case .buffer(let data):
.bytes(data)
-// case .stream(let stream):
-// .stream(...)
case nil:
nil
}
let response = try await execute(httpRequest, deadline: .distantFuture)
- let body = try await response.body.map(\.readableBytesView).reduce(into: Data(), +=)
+ let expectedBytes = response.headers.first(name: "content-length").flatMap(Int.init).map(Double.init)
+ if expectedBytes == nil {
+ onProgress(nil)
+ }
+ var body = Data()
+ for try await chunk in response.body {
+ body += chunk.readableBytesView
+ if let expectedBytes {
+ onProgress(min(Double(body.count) / expectedBytes, 1))
+ }
+ }
return HTTPResponse(
url: request.url,
status: Int(response.status.code),
diff --git a/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift b/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift
index a9c702a..eedf727 100644
--- a/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift
+++ b/Sources/Supersign/HTTPClientProtocol/HTTPClientProtocol.swift
@@ -10,7 +10,6 @@ import Foundation
public struct HTTPRequest {
public enum Body {
case buffer(Data)
-// case stream(InputStream)
}
public var url: URL
@@ -51,10 +50,16 @@ public struct HTTPResponse {
}
public protocol HTTPClientProtocol {
- func makeRequest(_ request: HTTPRequest) async throws -> HTTPResponse
+ func makeRequest(_ request: HTTPRequest, onProgress: (Double?) -> Void) async throws -> HTTPResponse
func makeWebSocket(url: URL) async throws -> WebSocketSession
}
+extension HTTPClientProtocol {
+ public func makeRequest(_ request: HTTPRequest) async throws -> HTTPResponse {
+ try await makeRequest(request) { _ in }
+ }
+}
+
public protocol WebSocketSession {
func receive() async throws -> WebSocketMessage
func send(_ message: WebSocketMessage) async throws
diff --git a/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift b/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift
index ab2e4d3..4559f7c 100644
--- a/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift
+++ b/Sources/Supersign/HTTPClientProtocol/URLSession+HTTP.swift
@@ -20,15 +20,15 @@ final class URLHTTPClientFactory: HTTPClientFactory {
}
private final class Client: HTTPClientProtocol {
- final class WebSocketDelegate: NSObject, URLSessionWebSocketDelegate {
- var callbacks: [URLSessionWebSocketTask: (URLSessionWebSocketTask.CloseCode?) -> Void] = [:]
+ final class ClientDelegate: NSObject, URLSessionWebSocketDelegate {
+ var webSocketCallbacks: [URLSessionWebSocketTask: (URLSessionWebSocketTask.CloseCode?) -> Void] = [:]
func urlSession(
_ session: URLSession,
webSocketTask: URLSessionWebSocketTask,
didOpenWithProtocol protocol: String?
) {
- callbacks.removeValue(forKey: webSocketTask)?(nil)
+ webSocketCallbacks.removeValue(forKey: webSocketTask)?(nil)
}
func urlSession(
@@ -37,21 +37,53 @@ private final class Client: HTTPClientProtocol {
didCloseWith closeCode: URLSessionWebSocketTask.CloseCode,
reason: Data?
) {
- callbacks.removeValue(forKey: webSocketTask)?(closeCode)
+ webSocketCallbacks.removeValue(forKey: webSocketTask)?(closeCode)
}
}
- private let webSocketDelegate = WebSocketDelegate()
+ private let clientDelegate = ClientDelegate()
private let session: URLSession
init() {
// no need for cert handling since the Apple Root CA is already
// installed on any devices which support the Security APIs which
// would have been required to add the custom root anyway
- self.session = URLSession(configuration: .ephemeral, delegate: webSocketDelegate, delegateQueue: .main)
+ self.session = URLSession(configuration: .ephemeral, delegate: clientDelegate, delegateQueue: .main)
}
- public func makeRequest(_ request: HTTPRequest) async throws -> HTTPResponse {
+ public func makeRequest(
+ _ request: HTTPRequest,
+ onProgress: @isolated(any) (Double?) -> Void
+ ) async throws -> HTTPResponse {
+ final class ProgressDelegate: NSObject, URLSessionDataDelegate {
+ private let progressContinuation: AsyncStream<Double>.Continuation
+ let progressStream: AsyncStream<Double>
+
+ @MainActor private var count = 0
+
+ override init() {
+ (progressStream, progressContinuation) = AsyncStream<Double>.makeStream(
+ // it's okay to skip missed progress updates
+ bufferingPolicy: .bufferingNewest(1)
+ )
+ }
+
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
+ let count = MainActor.assumeIsolated {
+ self.count += data.count
+ return self.count
+ }
+ if let contentLength = dataTask.response?.expectedContentLength, contentLength != -1 {
+ let progress = min(Double(count) / Double(contentLength), 1)
+ progressContinuation.yield(progress)
+ }
+ }
+
+ func finish() {
+ progressContinuation.finish()
+ }
+ }
+
var req = URLRequest(url: request.url)
req.httpMethod = request.method
request.headers.forEach { k, v in
@@ -60,13 +92,25 @@ private final class Client: HTTPClientProtocol {
switch request.body {
case .buffer(let data):
req.httpBody = data
-// case .stream(let stream):
-// req.httpBodyStream = stream
case nil:
break
}
- let (data, resp) = try await session.data(for: req)
- guard let httpResp = resp as? HTTPURLResponse else { throw UnknownHTTPError() }
+
+ let delegate = ProgressDelegate()
+ async let progressWatcher: Void = {
+ for await progress in delegate.progressStream {
+ await onProgress(progress)
+ }
+ }()
+ let (data, response) = if #available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) {
+ try await session.data(for: req, delegate: delegate)
+ } else {
+ try await session.data(for: req)
+ }
+ delegate.finish()
+ _ = await progressWatcher
+
+ guard let httpResp = response as? HTTPURLResponse else { throw UnknownHTTPError() }
let headers = [String: String](
uniqueKeysWithValues: httpResp.allHeaderFields.compactMap { k, v in
guard let kStr = k as? String,
@@ -85,11 +129,12 @@ private final class Client: HTTPClientProtocol {
public func makeWebSocket(url: URL) async throws -> any WebSocketSession {
let task = session.webSocketTask(with: url)
- async let event = withCheckedContinuation { continuation in
- webSocketDelegate.callbacks[task] = { continuation.resume(returning: $0) }
+ let (event, eventContinuation) = AsyncStream<URLSessionWebSocketTask.CloseCode?>.makeStream()
+ clientDelegate.webSocketCallbacks[task] = {
+ eventContinuation.yield($0)
+ eventContinuation.finish()
}
- task.resume()
- let code = await event
+ let code = await event.first { _ in true } ?? nil
if let code { throw Errors.webSocketClosed(code) }
return WebSocketSessionWrapper(task: task)
}
@@ -126,4 +171,11 @@ private final class WebSocketSessionWrapper: WebSocketSession {
task.cancel(with: .normalClosure, reason: nil)
}
}
+
+extension Optional {
+ fileprivate mutating func inoutMap<E>(_ transform: (inout Wrapped) throws(E) -> Void) throws(E) {
+ if self != nil { try transform(&self!) }
+ }
+}
+
#endif