Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XKit / Installation / IPAUploader.swift

IPAUploader.swift83 lines · 2.5 KiBRaw
1//
2// IPAUploader.swift
3// XKit
4//
5// Created by Kabir Oberai on 14/11/19.
6// Copyright © 2019 Kabir Oberai. All rights reserved.
7//
8
9import Foundation
10import SwiftyMobileDevice
11
12public final class IPAUploader: Sendable {
13
14 public enum Error: Swift.Error {
15 case unexpectedSymlink(at: URL)
16 }
17
18 private static let packagePath = URL(fileURLWithPath: "/PublicStaging")
19 private static let bufferSize = 1 << 20 // 1 MB
20
21 public final class UploadedIPA: Sendable {
22 public let uploader: IPAUploader
23 let location: URL
24 fileprivate init(uploader: IPAUploader, location: URL) {
25 self.uploader = uploader
26 self.location = location
27 }
28
29 deinit { delete() }
30
31 public func delete() {
32 try? uploader.client.removeItemAndContents(at: location)
33 }
34 }
35
36 private let client: AFCClient
37 public init(connection: Connection) async throws {
38 self.client = try await connection.startClient()
39 }
40
41 private func upload(_ src: URL, to dest: URL, progress: (Double) -> Void) async throws {
42 let srcData = try Data(contentsOf: src)
43 let size = srcData.count
44 let sizeDouble = Double(size)
45 let destFile = try client.open(dest, mode: .writeOnly)
46
47 let bufferSize = Self.bufferSize
48
49 var totalWritten = 0
50 while totalWritten != size {
51 if totalWritten != 0 {
52 await Task.yield()
53 try Task.checkCancellation()
54 }
55 let buf = srcData.dropFirst(totalWritten).prefix(bufferSize)
56 let bufSize = buf.count
57 var bufWritten = 0
58 while bufWritten < bufSize {
59 // not sure if rewriting the same buf is a bug but ideviceinstaller does it this way
60 let written = try destFile.write(buf)
61 bufWritten += written
62 totalWritten += written
63 progress(Double(totalWritten) / sizeDouble)
64 }
65 }
66 }
67
68 public func upload(app: URL, progress: (Double) -> Void) async throws -> UploadedIPA {
69 if try !client.fileExists(at: Self.packagePath) {
70 try client.createDirectory(at: Self.packagePath)
71 }
72
73 let dest = Self.packagePath.appendingPathComponent("XTool-App")
74 if try client.fileExists(at: dest) {
75 try client.removeItemAndContents(at: dest)
76 }
77
78 try await upload(app, to: dest, progress: progress)
79
80 return UploadedIPA(uploader: self, location: dest)
81 }
82
83}