Modern Apps git

xtool.git

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

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

ProfileManager.swift71 lines · 2.6 KiBRaw
1//
2// ProfileManager.swift
3// XKit
4//
5// Created by Kabir Oberai on 25/03/21.
6// Copyright © 2021 Kabir Oberai. All rights reserved.
7//
8
9import Foundation
10import XUtils
11import SwiftyMobileDevice
12
13public final class ProfileManager {
14
15 private let client: MISAgentClient
16 private let version: String
17
18 private lazy var ge9_3: Bool = {
19 let components = version.split(separator: ".")
20 guard !components.isEmpty, let major = Int(components[0]) else { return false }
21 if major > 9 {
22 return true
23 } else if major < 9 {
24 return false
25 }
26 guard components.count >= 2, let minor = Int(components[1]) else { return false }
27 return minor >= 3
28 }()
29
30 public init(connection: Connection) async throws {
31 self.client = try await connection.startClient()
32 self.version = try connection.client.value(ofType: String.self, forDomain: nil, key: "ProductVersion")
33 }
34
35 private func allProfiles() throws -> [Mobileprovision] {
36 try (ge9_3 ? client.profiles() : client.profilesLegacy())
37 .map(Mobileprovision.init(data:))
38 }
39
40 private func parse(profiles: [Mobileprovision]) throws -> [String: [(Mobileprovision, Mobileprovision.Digest)]] {
41 let pairs = try profiles.compactMap { (p: Mobileprovision) -> (String, (Mobileprovision, Mobileprovision.Digest))? in
42 let d = try p.digest()
43 let ents = try d.entitlements.entitlements()
44 guard let appID = ents.lazy.compactMap({ $0 as? ApplicationIdentifierEntitlement }).first
45 else { return nil }
46 return (appID.rawValue, (p, d))
47 }
48 return Dictionary(grouping: pairs) { $0.0 }.mapValues { $0.map { $0.1 } }
49 }
50
51 public func install(profiles: [Mobileprovision]) throws {
52 let toInstall = try parse(profiles: profiles)
53 let installed = try parse(profiles: allProfiles())
54
55 for (bundleID, profiles) in toInstall {
56 guard profiles.count == 1 else {
57 d.out.print("Unexpected # of profiles for \(bundleID): \(profiles.count). Skipping.")
58 continue
59 }
60 let profile = profiles[0]
61 let installedProfiles = installed[bundleID] ?? []
62 for installedProfile in installedProfiles {
63 d.out.print("Removing \(installedProfile.1.uuid) for \(bundleID)")
64 try client.removeProfile(withUUID: installedProfile.1.uuid)
65 }
66 d.out.print("Installing profile with UUID \(profile.1.uuid)")
67 try client.install(profile: profile.0.data())
68 }
69 }
70
71}