Cross-platform Xcode replacement. Build and deploy iOS apps with SwiftPM on Linux, Windows, macOS.
Implement Supersign installation, improve ipa downloading, implement preliminary Me tab, and fix bugs
kabiroberaica526ca983e3
diff --git a/Supersign/Installation/AppInstaller.swift b/Supersign/Installation/AppInstaller.swiftnew file mode 100644index 0000000..f0fcca3--- /dev/null+++ b/Supersign/Installation/AppInstaller.swift@@ -0,0 +1,131 @@+//+// AppInstaller.swift+// Supersign+//+// Created by Kabir Oberai on 13/11/19.+// Copyright © 2019 Kabir Oberai. All rights reserved.+//++import Foundation+import SwiftyMobileDevice++public class AppInstaller {++ public enum Error: LocalizedError {+ case invalidURL++ public var errorDescription: String? {+ switch self {+ case .invalidURL:+ return NSLocalizedString(+ "app_installer.error.invalid_url",+ value: "Invalid URL",+ comment: ""+ )+ }+ }+ }++ public enum Stage {+ case connecting(Double)+ case uploading(Double)+ case installing(String, Double?)++ public var displayName: String {+ switch self {+ case .connecting:+ return NSLocalizedString(+ "app_installer.stage.connecting",+ value: "Connecting",+ comment: ""+ )+ case .uploading:+ return NSLocalizedString(+ "app_installer.stage.uploading",+ value: "Uploading",+ comment: ""+ )+ case .installing(let details, _):+ return String.localizedStringWithFormat(+ NSLocalizedString(+ "app_installer.stage.installing",+ value: "Installing: %@",+ comment: "The %@ represents the stage reported by Apple (eg. VerifyingApplication)"+ ),+ details+ )+ }+ }++ public var displayProgress: Double {+ switch self {+ case .connecting(let progress):+ return progress+ case .installing(_, let progress):+ return progress ?? 0+ case .uploading(let progress):+ return progress+ }+ }+ }++ // serial queue+ private let installQueue = DispatchQueue(+ label: "com.kabiroberai.Supersign.install-queue"+ )++ private init() {}+ public static let shared = AppInstaller()++ // synchronous+ private func installSync(+ ipa: URL,+ bundleID: String,+ udid: String,+ pairingKeys: URL,+ progress: @escaping (Stage) -> Void+ ) throws {+ let connection = try Connection(udid: udid, pairingKeys: pairingKeys) {+ progress(.connecting($0 * 4/6))+ }+ defer { connection.close() }++ let uploader = try IPAUploader(connection: connection)+ progress(.connecting(5/6))++ // we need to start the installer quickly because sometimes it fails if we do it after+ // uploading the ipa to the device+ let installer = try IPAInstaller(connection: connection)+ progress(.connecting(6/6))++ let location = try uploader.upload(ipa: ipa, withBundleID: bundleID) { currentProgress in+ progress(.uploading(currentProgress))+ }++ try installer.install(deviceLocation: location, bundleID: bundleID) { currentProgress in+ progress(.installing(currentProgress.details, currentProgress.progress))+ }+ }++ public func install(+ ipa: URL,+ bundleID: String,+ udid: String,+ pairingKeys: URL,+ progress: @escaping (Stage) -> Void,+ completion: @escaping (Result<(), Swift.Error>) -> Void+ ) {+ installQueue.async {+ completion(Result {+ try self.installSync(+ ipa: ipa,+ bundleID: bundleID,+ udid: udid,+ pairingKeys: pairingKeys,+ progress: progress+ )+ })+ }+ }++}diff --git a/Supersign/Installation/Connection.swift b/Supersign/Installation/Connection.swiftnew file mode 100644index 0000000..dd2d595--- /dev/null+++ b/Supersign/Installation/Connection.swift@@ -0,0 +1,53 @@+//+// Connection.swift+// Supersign+//+// Created by Kabir Oberai on 15/11/19.+// Copyright © 2019 Kabir Oberai. All rights reserved.+//++import Foundation+import SwiftyMobileDevice++class Connection {++ private static let label = "supersign"++ private(set) var isClosed = false++ private let usbmuxHandler: USBMuxHandler+ let device: Device+ let client: LockdownClient+ private let heartbeatHandler: HeartbeatHandler++ init(udid: String, pairingKeys: URL, progress: (Double) -> Void) throws {+ progress(0/0)++ usbmuxHandler = USBMuxHandler(udid: udid, pairingKeys: pairingKeys)+ progress(1/4)++ device = try Device(udid: udid)+ progress(2/4)++ client = try LockdownClient(device: device, label: Self.label, performHandshake: true)+ progress(3/4)++ heartbeatHandler = HeartbeatHandler(device: device, client: client)+ progress(4/4)+ }++ deinit { close() }++ func close() {+ guard !isClosed else { return }+ isClosed = true++ heartbeatHandler.stop()+ usbmuxHandler.stop()+ }++ func startClient<T: Service>(_ type: T.Type = T.self, sendEscrowBag: Bool = false) throws -> T {+ try .init(device: device, service: .init(client: client, sendEscrowBag: sendEscrowBag))+ }++}diff --git a/Supersign/Installation/HeartbeatHandler.swift b/Supersign/Installation/HeartbeatHandler.swiftnew file mode 100644index 0000000..cbfc7b9--- /dev/null+++ b/Supersign/Installation/HeartbeatHandler.swift@@ -0,0 +1,94 @@+//+// HeartbeatHandler.swift+// Supersign+//+// Created by Kabir Oberai on 14/11/19.+// Copyright © 2019 Kabir Oberai. All rights reserved.+//++import Foundation+import SwiftyMobileDevice++class HeartbeatHandler {++ private struct Error: Swift.Error {}++ private static let restartInterval: TimeInterval = 1+ private static let requestCommand = "Marco"+ private static let responseCommand = "Polo"++ // each handler should have its own heartbeat queue+ private let heartbeatQueue = DispatchQueue(+ label: "com.kabiroberai.Supersign.heartbeat-queue"+ )+ private(set) var isStopped = false++ let device: Device+ let client: LockdownClient+ init(device: Device, client: LockdownClient) {+ self.device = device+ self.client = client+ start()+ }++ private func beat(client: HeartbeatClient, idx: Int) throws {+ // allow a 30 second timeout for the first heartbeat+ let plist = try client.receive(timeout: idx == 0 ? 30 : 5)+ guard case let .dictionary(dict) = plist,+ case let .string(command) = dict["Command"],+ case let .integer(interval) = dict["Interval"],+ command == Self.requestCommand+ else { throw Error() }++ try client.send(.dictionary([+ "Command": .string(Self.responseCommand)+ ]))++ sleep(.init(interval))+ }++ private func start() {+ let heartbeatClient: HeartbeatClient+ do {+ heartbeatClient = try HeartbeatClient(device: device, service: .init(client: client))+ } catch {+ // we sleep instead of asyncAfter to allow the initial startHeartbeat+ // call to block until a connection is established+ let timeInterval = Self.restartInterval+ let sec = timeInterval.rounded(.down)+ let nsec = (timeInterval - sec) * 1_000_000_000+ var time = timespec(+ tv_sec: .init(sec),+ tv_nsec: .init(nsec)+ )+ nanosleep(&time, nil)+ start()+ return+ }++ self.heartbeatQueue.async { [weak self] in+ var idx = 0+ while true {+ // only retains `self` for this iteration. This way, if the reference to+ // the handler is dropped,+ guard let self = self, !self.isStopped else { break }+ do {+ try self.beat(client: heartbeatClient, idx: idx)+ idx += 1+ } catch {+ // dispatching async should prevent stack overflows and allow the existing+ // heartbeatClient to deinit+ self.heartbeatQueue.asyncAfter(deadline: .now() + Self.restartInterval) {+ self.start()+ }+ break+ }+ }+ }+ }++ func stop() {+ isStopped = true+ }++}diff --git a/Supersign/Installation/IPAInstaller.swift b/Supersign/Installation/IPAInstaller.swiftnew file mode 100644index 0000000..f9b0943--- /dev/null+++ b/Supersign/Installation/IPAInstaller.swift@@ -0,0 +1,38 @@+//+// IPAInstaller.swift+// Supersign+//+// Created by Kabir Oberai on 14/11/19.+// Copyright © 2019 Kabir Oberai. All rights reserved.+//++import Foundation+import SwiftyMobileDevice++class IPAInstaller {++ private let client: InstallationProxyClient+ init(connection: Connection) throws {+ self.client = try connection.startClient()+ }++ func install(+ deviceLocation: URL,+ bundleID: String,+ progress: @escaping (InstallationProxyClient.InstallProgress) -> Void+ ) throws {+ let options = InstallationProxyClient.InstallOptions()+ options["CFBundleIdentifier"] = bundleID++ var error: Error?+ let semaphore = DispatchSemaphore(value: 0)+ client.install(package: deviceLocation, options: options, progress: progress) { result in+ defer { semaphore.signal() }+ if case let .failure(e) = result { error = e }+ }+ semaphore.wait()++ if let error = error { throw error }+ }++}diff --git a/Supersign/Installation/IPAUploader.swift b/Supersign/Installation/IPAUploader.swiftnew file mode 100644index 0000000..43d937d--- /dev/null+++ b/Supersign/Installation/IPAUploader.swift@@ -0,0 +1,53 @@+//+// IPAUploader.swift+// Supersign+//+// Created by Kabir Oberai on 14/11/19.+// Copyright © 2019 Kabir Oberai. All rights reserved.+//++import Foundation+import SwiftyMobileDevice++class IPAUploader {++ private static let packagePath = URL(fileURLWithPath: "PublicStaging")++ private let client: AFCClient+ init(connection: Connection) throws {+ self.client = try connection.startClient()+ }++ private func upload(_ src: URL, to dest: URL, progress: (Double) -> Void) throws {+ let srcHandle = try FileHandle(forReadingFrom: src)+ let size = srcHandle.seekToEndOfFile()+ srcHandle.seek(toFileOffset: 0)++ let destFile = try client.open(dest, mode: .writeOnly)++ var totalWritten = 0+ var buf: Data+ repeat {+ buf = srcHandle.readData(ofLength: 1 << 20) // 1 MB+ var bufWritten = 0+ while bufWritten < buf.count {+ let written = try destFile.write(buf)+ bufWritten += written+ totalWritten += written+ progress(Double(totalWritten) / Double(size))+ }+ } while !buf.isEmpty+ }++ func upload(ipa: URL, withBundleID bundleID: String, progress: (Double) -> Void) throws -> URL {+ if try !client.fileExists(at: Self.packagePath) {+ try client.createDirectory(at: Self.packagePath)+ }++ let dest = Self.packagePath.appendingPathComponent(bundleID)+ try upload(ipa, to: dest, progress: progress)++ return dest+ }++}diff --git a/Supersign/Signer/Signer.swift b/Supersign/Signer/Signer.swiftindex 3cf45ea..d3b8290 100644--- a/Supersign/Signer/Signer.swift+++ b/Supersign/Signer/Signer.swift@@ -44,6 +44,7 @@ public struct Signer {app: URL,signingInfo: SigningInfo,provisioningDict: [URL: ProvisioningInfo],+ status: @escaping (String) -> Void,progress: @escaping (Double) -> Void,completion: @escaping (Result<(), Swift.Error>) -> Void) {@@ -81,6 +82,7 @@ public struct Signer {public func sign(app: URL,+ status: @escaping (String) -> Void,progress: @escaping (Double) -> Void,completion: @escaping (Result<(), Swift.Error>) -> Void) {@@ -90,6 +92,7 @@ public struct Signer {app: app,signingInfo: response.signingInfo,provisioningDict: response.provisioningDict,+ status: status,progress: progress,completion: completion)diff --git a/Supersign/Utilities/RequestGrouper.swift b/Supersign/Utilities/RequestGrouper.swiftindex 0f00f8e..1c07937 100644--- a/Supersign/Utilities/RequestGrouper.swift+++ b/Supersign/Utilities/RequestGrouper.swift@@ -23,7 +23,10 @@ public struct ErrorList<E: Error>: LocalizedError {class RequestGrouper<T, E: Error> {- private let waitQueue = DispatchQueue(label: "request-wait-queue", attributes: .concurrent)+ private let waitQueue = DispatchQueue(+ label: "com.kabiroberai.Supersign.request-wait-queue",+ attributes: .concurrent+ )private let group = DispatchGroup()private var values: [T] = []