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