[Shared] Refactors error handling based on ALTLocalizedError protocol (#1115)

* [Shared] Revises ALTLocalizedError protocol

* Refactors errors to conform to revised ALTLocalizedError protocol

* [Missing Commit] Remaining changes for ALTLocalizedError

* [AltServer] Refactors errors to conform to revised ALTLocalizedError protocol

* [Missing Commit] Declares ALTLocalizedTitleErrorKey + ALTLocalizedDescriptionKey

* Updates Objective-C errors to match revised ALTLocalizedError

* [Missing Commit] Unnecessary ALTLocalizedDescription logic

* [Shared] Refactors NSError.withLocalizedFailure to properly support ALTLocalizedError

* [Shared] Supports adding localized titles to errors via NSError.withLocalizedTitle()

* Revises ErrorResponse logic to support arbitrary errors and user info values

* [Missed Commit] Renames CodableServerError to CodableError

* Merges ConnectionError into OperationError

* [Missed Commit] Doesn’t check ALTWrappedError’s userInfo for localizedDescription

* [Missed] Fixes incorrect errorDomain for ALTErrorEnums

* [Missed] Removes nonexistent ALTWrappedError.h

* Includes source file and line number in OperationError.unknown failureReason

* Adds localizedTitle to AppManager operation errors

* Fixes adding localizedTitle + localizedFailure to ALTWrappedError

* Updates ToastView to use error’s localizedTitle as title

* [Shared] Adds NSError.formattedDetailedDescription(with:)

Returns formatted NSAttributedString containing all user info values intended for displaying to the user.

* [Shared] Updates Error.localizedErrorCode to say “code” instead of “error”

* Conforms ALTLocalizedError to CustomStringConvertible

* Adds “View More Details” option to Error Log context menu to view detailed error description

* [Shared] Fixes NSError.formattedDetailedDescription appearing black in dark mode

* [AltServer] Updates error alert to match revised error logic

Uses error’s localizedTitle as alert title.

* [AltServer] Adds “View More Details” button to error alert to view detailed error info

* [AltServer] Renames InstallError to OperationError and conforms to ALTErrorEnum

* [Shared] Removes CodableError support for Date user info values

Not currently used, and we don’t want to accidentally parse a non-Date as a Date in the meantime.

* [Shared] Includes dynamic UserInfoValueProvider values in NSError.formattedDetailedDescription()

* [Shared] Includes source file + line in NSError.formattedDetailedDescription()

Automatically captures source file + line when throwing ALTErrorEnums.

* [Shared] Captures source file + line for unknown errors

* Removes sourceFunction from OperationError

* Adds localizedTitle to AuthenticationViewController errors

* [Shared] Moves nested ALTWrappedError logic to ALTWrappedError initializer

* [AltServer] Removes now-redundant localized failure from JIT errors

All JIT errors now have a localizedTitle which effectively says the same thing.

* Makes OperationError.Code start at 1000

“Connection errors” subsection starts at 1200.

* [Shared] Updates Error domains to revised [Source].[ErrorType] format

* Updates ALTWrappedError.localizedDescription to prioritize using wrapped NSLocalizedDescription as failure reason

* Makes ALTAppleAPIError codes start at 3000

* [AltServer] Adds relevant localizedFailures to ALTDeviceManager.installApplication() errors

* Revises OperationError failureReasons and recovery suggestions

All failure reasons now read correctly when preceded by a failure reason and “because”.

* Revises ALTServerError error messages
All failure reasons now read correctly when preceded by a failure reason and “because”.

* Most failure reasons now read correctly when preceded by a failure reason and “because”.
* ALTServerErrorUnderlyingError forwards all user info provider calls to underlying error.

* Revises error messages for ALTAppleAPIErrorIncorrectCredentials

* [Missed] Removes NSError+AltStore.swift from AltStore target

* [Shared] Updates AltServerErrorDomain to revised [Source].[ErrorType] format

* [Shared] Removes “code” from Error.localizedErrorCode

* [Shared] Makes ALTServerError codes (appear to) start at 2000

We can’t change the actual error codes without breaking backwards compatibility, so instead we just add 2000 whenever we display ALTServerError codes to the user.

* Moves VerificationError.errorFailure to VerifyAppOperation

* Supports custom failure reason for OperationError.unknown

* [Shared] Changes AltServerErrorDomain to “AltServer.ServerError”

* [Shared] Converts ALTWrappedError to Objective-C class

NSError subclasses must be written in ObjC for Swift.Error <-> NSError bridging to work correctly.

# Conflicts:
#	AltStore.xcodeproj/project.pbxproj

* Fixes decoding CodableError nested user info values
This commit is contained in:
Riley Testut
2023-01-24 13:56:41 -06:00
committed by GitHub
parent 0c4fe98370
commit 3b38d725d7
44 changed files with 1707 additions and 644 deletions

View File

@@ -13,7 +13,8 @@ import Network
import AltStoreCore
import AltSign
enum AuthenticationError: LocalizedError
typealias AuthenticationError = AuthenticationErrorCode.Error
enum AuthenticationErrorCode: Int, ALTErrorEnum, CaseIterable
{
case noTeam
case noCertificate
@@ -21,10 +22,10 @@ enum AuthenticationError: LocalizedError
case missingPrivateKey
case missingCertificate
var errorDescription: String? {
var errorFailureReason: String {
switch self {
case .noTeam: return NSLocalizedString("Developer team could not be found.", comment: "")
case .noCertificate: return NSLocalizedString("Developer certificate could not be found.", comment: "")
case .noTeam: return NSLocalizedString("Your Apple ID has no developer teams.", comment: "")
case .noCertificate: return NSLocalizedString("The developer certificate could not be found.", comment: "")
case .missingPrivateKey: return NSLocalizedString("The certificate's private key could not be found.", comment: "")
case .missingCertificate: return NSLocalizedString("The certificate could not be found.", comment: "")
}
@@ -210,7 +211,7 @@ class AuthenticationOperation: ResultOperation<(ALTTeam, ALTCertificate, ALTAppl
guard
let account = Account.first(satisfying: NSPredicate(format: "%K == %@", #keyPath(Account.identifier), altTeam.account.identifier), in: context),
let team = Team.first(satisfying: NSPredicate(format: "%K == %@", #keyPath(Team.identifier), altTeam.identifier), in: context)
else { throw AuthenticationError.noTeam }
else { throw AuthenticationError(.noTeam) }
// Account
account.isActiveAccount = true
@@ -429,7 +430,7 @@ private extension AuthenticationOperation
}
else
{
completionHandler(.failure(error ?? OperationError.unknown))
completionHandler(.failure(error ?? OperationError.unknown()))
}
}
}
@@ -456,7 +457,7 @@ private extension AuthenticationOperation
}
else
{
return completionHandler(.failure(AuthenticationError.noTeam))
return completionHandler(.failure(AuthenticationError(.noTeam)))
}
}
@@ -488,7 +489,7 @@ private extension AuthenticationOperation
do
{
let certificate = try Result(certificate, error).get()
guard let privateKey = certificate.privateKey else { throw AuthenticationError.missingPrivateKey }
guard let privateKey = certificate.privateKey else { throw AuthenticationError(.missingPrivateKey) }
ALTAppleAPI.shared.fetchCertificates(for: team, session: session) { (certificates, error) in
do
@@ -496,7 +497,7 @@ private extension AuthenticationOperation
let certificates = try Result(certificates, error).get()
guard let certificate = certificates.first(where: { $0.serialNumber == certificate.serialNumber }) else {
throw AuthenticationError.missingCertificate
throw AuthenticationError(.missingCertificate)
}
certificate.privateKey = privateKey
@@ -517,7 +518,7 @@ private extension AuthenticationOperation
func replaceCertificate(from certificates: [ALTCertificate])
{
guard let certificate = certificates.first(where: { $0.machineName?.starts(with: "AltStore") == true }) ?? certificates.first else { return completionHandler(.failure(AuthenticationError.noCertificate)) }
guard let certificate = certificates.first(where: { $0.machineName?.starts(with: "AltStore") == true }) ?? certificates.first else { return completionHandler(.failure(AuthenticationError(.noCertificate))) }
ALTAppleAPI.shared.revoke(certificate, for: team, session: session) { (success, error) in
if let error = error, !success

View File

@@ -11,11 +11,12 @@ import CoreData
import AltStoreCore
enum RefreshError: LocalizedError
typealias RefreshError = RefreshErrorCode.Error
enum RefreshErrorCode: Int, ALTErrorEnum, CaseIterable
{
case noInstalledApps
var errorDescription: String? {
var errorFailureReason: String {
switch self
{
case .noInstalledApps: return NSLocalizedString("No active apps require refreshing.", comment: "")
@@ -91,7 +92,7 @@ class BackgroundRefreshAppsOperation: ResultOperation<[String: Result<InstalledA
super.main()
guard !self.installedApps.isEmpty else {
self.finish(.failure(RefreshError.noInstalledApps))
self.finish(.failure(RefreshError(.noInstalledApps)))
return
}
@@ -207,11 +208,11 @@ private extension BackgroundRefreshAppsOperation
content.title = NSLocalizedString("Refreshed Apps", comment: "")
content.body = NSLocalizedString("All apps have been refreshed.", comment: "")
}
catch ConnectionError.serverNotFound
catch ~OperationError.Code.serverNotFound
{
shouldPresentAlert = false
}
catch RefreshError.noInstalledApps
catch ~RefreshErrorCode.noInstalledApps
{
shouldPresentAlert = false
}

View File

@@ -55,7 +55,7 @@ class BackupAppOperation: ResultOperation<Void>
let appName = installedApp.name
self.appName = appName
guard let altstoreApp = InstalledApp.fetchAltStore(in: context) else { throw OperationError.appNotFound }
guard let altstoreApp = InstalledApp.fetchAltStore(in: context) else { throw OperationError.appNotFound(name: appName) }
let altstoreOpenURL = altstoreApp.openAppURL
var returnURLComponents = URLComponents(url: altstoreOpenURL, resolvingAgainstBaseURL: false)

View File

@@ -12,29 +12,13 @@ import Roxas
import AltStoreCore
import AltSign
private extension DownloadAppOperation
{
struct DependencyError: ALTLocalizedError
{
let dependency: Dependency
let error: Error
var failure: String? {
return String(format: NSLocalizedString("Could not download “%@”.", comment: ""), self.dependency.preferredFilename)
}
var underlyingError: Error? {
return self.error
}
}
}
@objc(DownloadAppOperation)
class DownloadAppOperation: ResultOperation<ALTApplication>
{
let app: AppProtocol
let context: AppOperationContext
private let appName: String
private let bundleIdentifier: String
private var sourceURL: URL?
private let destinationURL: URL
@@ -47,6 +31,7 @@ class DownloadAppOperation: ResultOperation<ALTApplication>
self.app = app
self.context = context
self.appName = app.name
self.bundleIdentifier = app.bundleIdentifier
self.sourceURL = app.url
self.destinationURL = destinationURL
@@ -69,7 +54,7 @@ class DownloadAppOperation: ResultOperation<ALTApplication>
print("Downloading App:", self.bundleIdentifier)
guard let sourceURL = self.sourceURL else { return self.finish(.failure(OperationError.appNotFound)) }
guard let sourceURL = self.sourceURL else { return self.finish(.failure(OperationError.appNotFound(name: self.appName))) }
self.downloadApp(from: sourceURL) { result in
do
@@ -138,7 +123,7 @@ private extension DownloadAppOperation
let fileURL = try result.get()
var isDirectory: ObjCBool = false
guard FileManager.default.fileExists(atPath: fileURL.path, isDirectory: &isDirectory) else { throw OperationError.appNotFound }
guard FileManager.default.fileExists(atPath: fileURL.path, isDirectory: &isDirectory) else { throw OperationError.appNotFound(name: self.appName) }
try FileManager.default.createDirectory(at: self.temporaryDirectory, withIntermediateDirectories: true, attributes: nil)
@@ -252,7 +237,7 @@ private extension DownloadAppOperation
let altstorePlist = try PropertyListDecoder().decode(AltStorePlist.self, from: data)
var dependencyURLs = Set<URL>()
var dependencyError: DependencyError?
var dependencyError: Error?
let dispatchGroup = DispatchGroup()
let progress = Progress(totalUnitCount: Int64(altstorePlist.dependencies.count), parent: self.progress, pendingUnitCount: 1)
@@ -285,7 +270,7 @@ private extension DownloadAppOperation
}
catch let error as DecodingError
{
let nsError = (error as NSError).withLocalizedFailure(String(format: NSLocalizedString("Could not download dependencies for %@.", comment: ""), application.name))
let nsError = (error as NSError).withLocalizedFailure(String(format: NSLocalizedString("The dependencies for %@ could not be determined.", comment: ""), application.name))
completionHandler(.failure(nsError))
}
catch
@@ -294,7 +279,7 @@ private extension DownloadAppOperation
}
}
func download(_ dependency: Dependency, for application: ALTApplication, progress: Progress, completionHandler: @escaping (Result<URL, DependencyError>) -> Void)
func download(_ dependency: Dependency, for application: ALTApplication, progress: Progress, completionHandler: @escaping (Result<URL, Error>) -> Void)
{
let downloadTask = self.session.downloadTask(with: dependency.downloadURL) { (fileURL, response, error) in
do
@@ -315,9 +300,10 @@ private extension DownloadAppOperation
completionHandler(.success(destinationURL))
}
catch
catch let error as NSError
{
completionHandler(.failure(DependencyError(dependency: dependency, error: error)))
let localizedFailure = String(format: NSLocalizedString("The dependency “%@” could not be downloaded.", comment: ""), dependency.preferredFilename)
completionHandler(.failure(error.withLocalizedFailure(localizedFailure)))
}
}
progress.addChild(downloadTask.progress, withPendingUnitCount: 1)

View File

@@ -45,7 +45,7 @@ class FetchProvisioningProfilesOperation: ResultOperation<[String: ALTProvisioni
let session = self.context.session
else { return self.finish(.failure(OperationError.invalidParameters)) }
guard let app = self.context.app else { return self.finish(.failure(OperationError.appNotFound)) }
guard let app = self.context.app else { return self.finish(.failure(OperationError.appNotFound(name: nil))) }
self.progress.totalUnitCount = Int64(1 + app.appExtensions.count)
@@ -260,7 +260,7 @@ extension FetchProvisioningProfilesOperation
{
if let expirationDate = sortedExpirationDates.first
{
throw OperationError.maximumAppIDLimitReached(application: application, requiredAppIDs: requiredAppIDs, availableAppIDs: availableAppIDs, nextExpirationDate: expirationDate)
throw OperationError.maximumAppIDLimitReached(appName: application.name, requiredAppIDs: requiredAppIDs, availableAppIDs: availableAppIDs, expirationDate: expirationDate)
}
else
{
@@ -281,7 +281,7 @@ extension FetchProvisioningProfilesOperation
{
if let expirationDate = sortedExpirationDates.first
{
throw OperationError.maximumAppIDLimitReached(application: application, requiredAppIDs: requiredAppIDs, availableAppIDs: availableAppIDs, nextExpirationDate: expirationDate)
throw OperationError.maximumAppIDLimitReached(appName: application.name, requiredAppIDs: requiredAppIDs, availableAppIDs: availableAppIDs, expirationDate: expirationDate)
}
else
{

View File

@@ -85,7 +85,7 @@ class FindServerOperation: ResultOperation<Server>
else
{
// No servers.
self.finish(.failure(ConnectionError.serverNotFound))
self.finish(.failure(OperationError.serverNotFound))
}
}
}

View File

@@ -8,55 +8,135 @@
import Foundation
import AltSign
import AltStoreCore
enum OperationError: LocalizedError
extension OperationError
{
static let domain = OperationError.unknown._domain
enum Code: Int, ALTErrorCode, CaseIterable
{
typealias Error = OperationError
/* General */
case unknown = 1000
case unknownResult
case cancelled
case timedOut
case notAuthenticated
case appNotFound
case unknownUDID
case invalidApp
case invalidParameters
case maximumAppIDLimitReached
case noSources
case openAppFailed
case missingAppGroup
/* Connection */
case serverNotFound = 1200
case connectionFailed
case connectionDropped
}
case unknown
case unknownResult
case cancelled
case timedOut
static let unknownResult: OperationError = .init(code: .unknownResult)
static let cancelled: OperationError = .init(code: .cancelled)
static let timedOut: OperationError = .init(code: .timedOut)
static let notAuthenticated: OperationError = .init(code: .notAuthenticated)
static let unknownUDID: OperationError = .init(code: .unknownUDID)
static let invalidApp: OperationError = .init(code: .invalidApp)
static let invalidParameters: OperationError = .init(code: .invalidParameters)
static let noSources: OperationError = .init(code: .noSources)
static let missingAppGroup: OperationError = .init(code: .missingAppGroup)
case notAuthenticated
case appNotFound
static let serverNotFound: OperationError = .init(code: .serverNotFound)
static let connectionFailed: OperationError = .init(code: .connectionFailed)
static let connectionDropped: OperationError = .init(code: .connectionDropped)
case unknownUDID
static func unknown(failureReason: String? = nil, file: String = #fileID, line: UInt = #line) -> OperationError {
OperationError(code: .unknown, failureReason: failureReason, sourceFile: file, sourceLine: line)
}
case invalidApp
case invalidParameters
static func appNotFound(name: String?) -> OperationError { OperationError(code: .appNotFound, appName: name) }
static func openAppFailed(name: String) -> OperationError { OperationError(code: .openAppFailed, appName: name) }
case maximumAppIDLimitReached(application: ALTApplication, requiredAppIDs: Int, availableAppIDs: Int, nextExpirationDate: Date)
static func maximumAppIDLimitReached(appName: String, requiredAppIDs: Int, availableAppIDs: Int, expirationDate: Date) -> OperationError {
OperationError(code: .maximumAppIDLimitReached, appName: appName, requiredAppIDs: requiredAppIDs, availableAppIDs: availableAppIDs, expirationDate: expirationDate)
}
}
struct OperationError: ALTLocalizedError
{
let code: Code
case noSources
var errorTitle: String?
var errorFailure: String?
case openAppFailed(name: String)
case missingAppGroup
var appName: String?
var requiredAppIDs: Int?
var availableAppIDs: Int?
var expirationDate: Date?
var failureReason: String? {
switch self {
case .unknown: return NSLocalizedString("An unknown error occured.", comment: "")
var sourceFile: String?
var sourceLine: UInt?
private init(code: Code, failureReason: String? = nil, appName: String? = nil, requiredAppIDs: Int? = nil, availableAppIDs: Int? = nil, expirationDate: Date? = nil,
sourceFile: String? = nil, sourceLine: UInt? = nil)
{
self.code = code
self._failureReason = failureReason
self.appName = appName
self.requiredAppIDs = requiredAppIDs
self.availableAppIDs = availableAppIDs
self.expirationDate = expirationDate
self.sourceFile = sourceFile
self.sourceLine = sourceLine
}
var errorFailureReason: String {
switch self.code
{
case .unknown:
var failureReason = self._failureReason ?? NSLocalizedString("An unknown error occured.", comment: "")
guard let sourceFile, let sourceLine else { return failureReason }
failureReason += " (\(sourceFile) line \(sourceLine))"
return failureReason
case .unknownResult: return NSLocalizedString("The operation returned an unknown result.", comment: "")
case .cancelled: return NSLocalizedString("The operation was cancelled.", comment: "")
case .timedOut: return NSLocalizedString("The operation timed out.", comment: "")
case .notAuthenticated: return NSLocalizedString("You are not signed in.", comment: "")
case .appNotFound: return NSLocalizedString("App not found.", comment: "")
case .unknownUDID: return NSLocalizedString("Unknown device UDID.", comment: "")
case .invalidApp: return NSLocalizedString("The app is invalid.", comment: "")
case .unknownUDID: return NSLocalizedString("AltStore could not determine this device's UDID.", comment: "")
case .invalidApp: return NSLocalizedString("The app is in an invalid format.", comment: "")
case .invalidParameters: return NSLocalizedString("Invalid parameters.", comment: "")
case .maximumAppIDLimitReached: return NSLocalizedString("You cannot register more than 10 App IDs within a 7 day period.", comment: "")
case .noSources: return NSLocalizedString("There are no AltStore sources.", comment: "")
case .openAppFailed(let name): return String(format: NSLocalizedString("AltStore was denied permission to launch %@.", comment: ""), name)
case .missingAppGroup: return NSLocalizedString("AltStore's shared app group could not be found.", comment: "")
case .maximumAppIDLimitReached: return NSLocalizedString("Cannot register more than 10 App IDs.", comment: "")
case .missingAppGroup: return NSLocalizedString("AltStore's shared app group could not be accessed.", comment: "")
case .appNotFound:
let appName = self.appName ?? NSLocalizedString("The app", comment: "")
return String(format: NSLocalizedString("%@ could not be found.", comment: ""), appName)
case .openAppFailed:
let appName = self.appName ?? NSLocalizedString("the app", comment: "")
return String(format: NSLocalizedString("AltStore was denied permission to launch %@.", comment: ""), appName)
case .serverNotFound: return NSLocalizedString("AltServer could not be found.", comment: "")
case .connectionFailed: return NSLocalizedString("A connection to AltServer could not be established.", comment: "")
case .connectionDropped: return NSLocalizedString("The connection to AltServer was dropped.", comment: "")
}
}
private var _failureReason: String?
var recoverySuggestion: String? {
switch self
switch self.code
{
case .maximumAppIDLimitReached(let application, let requiredAppIDs, let availableAppIDs, let date):
case .serverNotFound: return NSLocalizedString("Make sure you're on the same WiFi network as a computer running AltServer, or try connecting this device to your computer via USB.", comment: "")
case .maximumAppIDLimitReached:
let baseMessage = NSLocalizedString("Delete sideloaded apps to free up App ID slots.", comment: "")
let message: String
guard let appName = self.appName, let requiredAppIDs = self.requiredAppIDs, let availableAppIDs = self.availableAppIDs, let date = self.expirationDate else { return baseMessage }
var message: String = ""
if requiredAppIDs > 1
{
@@ -69,23 +149,25 @@ enum OperationError: LocalizedError
default: availableText = String(format: NSLocalizedString("only %@ are available", comment: ""), NSNumber(value: availableAppIDs))
}
let prefixMessage = String(format: NSLocalizedString("%@ requires %@ App IDs, but %@.", comment: ""), application.name, NSNumber(value: requiredAppIDs), availableText)
message = prefixMessage + " " + baseMessage
let prefixMessage = String(format: NSLocalizedString("%@ requires %@ App IDs, but %@.", comment: ""), appName, NSNumber(value: requiredAppIDs), availableText)
message = prefixMessage + " " + baseMessage + "\n\n"
}
else
{
let dateComponents = Calendar.current.dateComponents([.day, .hour, .minute], from: Date(), to: date)
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.maximumUnitCount = 1
dateComponentsFormatter.unitsStyle = .full
let remainingTime = dateComponentsFormatter.string(from: dateComponents)!
let remainingTimeMessage = String(format: NSLocalizedString("You can register another App ID in %@.", comment: ""), remainingTime)
message = baseMessage + " " + remainingTimeMessage
message = baseMessage + " "
}
let dateComponents = Calendar.current.dateComponents([.day, .hour, .minute], from: Date(), to: date)
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.maximumUnitCount = 1
dateComponentsFormatter.unitsStyle = .full
let remainingTime = dateComponentsFormatter.string(from: dateComponents)!
let remainingTimeMessage = String(format: NSLocalizedString("You can register another App ID in %@.", comment: ""), remainingTime)
message += remainingTimeMessage
return message
default: return nil

View File

@@ -25,21 +25,41 @@ protocol PatchAppContext
var error: Error? { get }
}
enum PatchAppError: LocalizedError
extension PatchAppError
{
case unsupportedOperatingSystemVersion(OperatingSystemVersion)
enum Code: Int, ALTErrorCode, CaseIterable
{
typealias Error = PatchAppError
case unsupportedOperatingSystemVersion
}
var errorDescription: String? {
switch self
static func unsupportedOperatingSystemVersion(_ osVersion: OperatingSystemVersion) -> PatchAppError { PatchAppError(code: .unsupportedOperatingSystemVersion, osVersion: osVersion) }
}
struct PatchAppError: ALTLocalizedError
{
let code: Code
var errorFailure: String?
var errorTitle: String?
var osVersion: OperatingSystemVersion?
var errorFailureReason: String {
switch self.code
{
case .unsupportedOperatingSystemVersion(let osVersion):
var osVersionString = "\(osVersion.majorVersion).\(osVersion.minorVersion)"
if osVersion.patchVersion != 0
case .unsupportedOperatingSystemVersion:
let osVersionString: String
if let osVersion = self.osVersion?.stringValue
{
osVersionString += ".\(osVersion.patchVersion)"
osVersionString = NSLocalizedString("iOS", comment: "") + " " + osVersion
}
else
{
osVersionString = NSLocalizedString("your device's iOS version", comment: "")
}
let errorDescription = String(format: NSLocalizedString("The OTA download URL for iOS %@ could not be determined.", comment: ""), osVersionString)
let errorDescription = String(format: NSLocalizedString("The OTA download URL for %@ could not be determined.", comment: ""), osVersionString)
return errorDescription
}
}

View File

@@ -439,7 +439,7 @@ private extension PatchViewController
do
{
guard let (bundleIdentifier, result) = results.first else { throw refreshGroup?.context.error ?? OperationError.unknown }
guard let (bundleIdentifier, result) = results.first else { throw refreshGroup?.context.error ?? OperationError.unknown() }
_ = try result.get()
if var patchedApps = UserDefaults.standard.patchedApps, let index = patchedApps.firstIndex(of: bundleIdentifier)

View File

@@ -41,7 +41,7 @@ class RefreshAppOperation: ResultOperation<InstalledApp>
guard let server = self.context.server, let profiles = self.context.provisioningProfiles else { throw OperationError.invalidParameters }
guard let app = self.context.app else { throw OperationError.appNotFound }
guard let app = self.context.app else { throw OperationError.appNotFound(name: nil) }
guard let udid = Bundle.main.object(forInfoDictionaryKey: Bundle.Info.deviceID) as? String else { throw OperationError.unknownUDID }
ServerManager.shared.connect(to: server) { (result) in
@@ -84,7 +84,7 @@ class RefreshAppOperation: ResultOperation<InstalledApp>
self.managedObjectContext.perform {
let predicate = NSPredicate(format: "%K == %@", #keyPath(InstalledApp.bundleIdentifier), app.bundleIdentifier)
guard let installedApp = InstalledApp.first(satisfying: predicate, in: self.managedObjectContext) else {
return self.finish(.failure(OperationError.appNotFound))
return self.finish(.failure(OperationError.appNotFound(name: app.name)))
}
self.progress.completedUnitCount += 1

View File

@@ -8,48 +8,74 @@
import Foundation
import AltStoreCore
import AltSign
import Roxas
enum VerificationError: ALTLocalizedError
extension VerificationError
{
case privateEntitlements(ALTApplication, entitlements: [String: Any])
case mismatchedBundleIdentifiers(ALTApplication, sourceBundleID: String)
case iOSVersionNotSupported(ALTApplication)
var app: ALTApplication {
switch self
{
case .privateEntitlements(let app, _): return app
case .mismatchedBundleIdentifiers(let app, _): return app
case .iOSVersionNotSupported(let app): return app
}
enum Code: Int, ALTErrorCode, CaseIterable
{
typealias Error = VerificationError
case privateEntitlements
case mismatchedBundleIdentifiers
case iOSVersionNotSupported
}
var failure: String? {
return String(format: NSLocalizedString("“%@” could not be installed.", comment: ""), app.name)
}
static func privateEntitlements(_ entitlements: [String: Any], app: ALTApplication) -> VerificationError { VerificationError(code: .privateEntitlements, app: app, entitlements: entitlements) }
static func mismatchedBundleIdentifiers(sourceBundleID: String, app: ALTApplication) -> VerificationError { VerificationError(code: .mismatchedBundleIdentifiers, app: app, sourceBundleID: sourceBundleID) }
static func iOSVersionNotSupported(app: ALTApplication) -> VerificationError { VerificationError(code: .iOSVersionNotSupported, app: app) }
}
struct VerificationError: ALTLocalizedError
{
let code: Code
var failureReason: String? {
switch self
var errorTitle: String?
var errorFailure: String?
var app: ALTApplication?
var entitlements: [String: Any]?
var sourceBundleID: String?
var errorFailureReason: String {
switch self.code
{
case .privateEntitlements(let app, _):
return String(format: NSLocalizedString("“%@” requires private permissions.", comment: ""), app.name)
case .privateEntitlements:
let appName = (self.app?.name as String?).map { String(format: NSLocalizedString("“%@”", comment: ""), $0) } ?? NSLocalizedString("The app", comment: "")
return String(format: NSLocalizedString("%@ requires private permissions.", comment: ""), appName)
case .mismatchedBundleIdentifiers(let app, let sourceBundleID):
return String(format: NSLocalizedString("The bundle ID “%@” does not match the one specified by the source (“%@”).", comment: ""), app.bundleIdentifier, sourceBundleID)
case .iOSVersionNotSupported(let app):
let name = app.name
var version = "iOS \(app.minimumiOSVersion.majorVersion).\(app.minimumiOSVersion.minorVersion)"
if app.minimumiOSVersion.patchVersion > 0
case .mismatchedBundleIdentifiers:
if let app = self.app, let bundleID = self.sourceBundleID
{
version += ".\(app.minimumiOSVersion.patchVersion)"
return String(format: NSLocalizedString("The bundle ID “%@” does not match the one specified by the source (“%@”).", comment: ""), app.bundleIdentifier, bundleID)
}
else
{
return NSLocalizedString("The bundle ID does not match the one specified by the source.", comment: "")
}
let localizedDescription = String(format: NSLocalizedString("%@ requires %@.", comment: ""), name, version)
return localizedDescription
case .iOSVersionNotSupported:
if let app = self.app
{
var version = "iOS \(app.minimumiOSVersion.majorVersion).\(app.minimumiOSVersion.minorVersion)"
if app.minimumiOSVersion.patchVersion > 0
{
version += ".\(app.minimumiOSVersion.patchVersion)"
}
let failureReason = String(format: NSLocalizedString("%@ requires %@.", comment: ""), app.name, version)
return failureReason
}
else
{
let version = ProcessInfo.processInfo.operatingSystemVersion.stringValue
let failureReason = String(format: NSLocalizedString("This app does not support iOS %@.", comment: ""), version)
return failureReason
}
}
}
}
@@ -78,14 +104,17 @@ class VerifyAppOperation: ResultOperation<Void>
throw error
}
let appName = self.context.app?.name ?? NSLocalizedString("The app", comment: "")
self.localizedFailure = String(format: NSLocalizedString("%@ could not be installed.", comment: ""), appName)
guard let app = self.context.app else { throw OperationError.invalidParameters }
guard app.bundleIdentifier == self.context.bundleIdentifier else {
throw VerificationError.mismatchedBundleIdentifiers(app, sourceBundleID: self.context.bundleIdentifier)
throw VerificationError.mismatchedBundleIdentifiers(sourceBundleID: self.context.bundleIdentifier, app: app)
}
guard ProcessInfo.processInfo.isOperatingSystemAtLeast(app.minimumiOSVersion) else {
throw VerificationError.iOSVersionNotSupported(app)
throw VerificationError.iOSVersionNotSupported(app: app)
}
if #available(iOS 13.5, *)
@@ -116,7 +145,7 @@ class VerifyAppOperation: ResultOperation<Void>
let entitlements = try PropertyListSerialization.propertyList(from: entitlementsPlist.data(using: .utf8)!, options: [], format: nil) as! [String: Any]
app.hasPrivateEntitlements = true
let error = VerificationError.privateEntitlements(app, entitlements: entitlements)
let error = VerificationError.privateEntitlements(entitlements, app: app)
self.process(error) { (result) in
self.finish(result.mapError { $0 as Error })
}
@@ -145,15 +174,16 @@ private extension VerifyAppOperation
guard let presentingViewController = self.context.presentingViewController else { return completion(.failure(error)) }
DispatchQueue.main.async {
switch error
switch error.code
{
case .privateEntitlements(_, let entitlements):
case .privateEntitlements:
guard let entitlements = error.entitlements else { return completion(.failure(error)) }
let permissions = entitlements.keys.sorted().joined(separator: "\n")
let message = String(format: NSLocalizedString("""
You must allow access to these private permissions before continuing:
%@
Private permissions allow apps to do more than normally allowed by iOS, including potentially accessing sensitive private data. Make sure to only install apps from sources you trust.
""", comment: ""), permissions)