-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLaunchViewController.swift
More file actions
322 lines (290 loc) · 15.2 KB
/
Copy pathLaunchViewController.swift
File metadata and controls
322 lines (290 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
//
// LaunchViewController.swift
// AltStore
//
// Created by Riley Testut on 7/30/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
import UIKit
import Roxas
import WidgetKit
import AltSign
import AltStoreCore
import UniformTypeIdentifiers
let pairingFileName = "ALTPairingFile.mobiledevicepairing"
final class LaunchViewController: UIViewController, UIDocumentPickerDelegate {
private var didFinishLaunching = false
private var retries = 0
private var maxRetries = 3
private var destinationViewController: TabBarController?
override func viewDidLoad() {
super.viewDidLoad()
// Set background immediately so there is no grey flash when OLED mode is on.
view.backgroundColor = .altBackground
destinationViewController = storyboard?.instantiateViewController(withIdentifier: "tabBarController") as? TabBarController
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard !didFinishLaunching else { return }
Task {
await runLaunchSequence()
doPostLaunch()
}
}
private func runLaunchSequence() async {
guard retries < maxRetries else { return }
retries += 1
await Task.detached {
if !DatabaseManager.shared.isStarted {
await withCheckedContinuation { continuation in
DatabaseManager.shared.start { error in
if let error {
Task { await self.handleLaunchError(error, retryCallback: self.runLaunchSequence) }
} else {
Task { await self.finishLaunching() }
}
continuation.resume(returning: ())
}
}
} else {
await self.finishLaunching()
}
}.value
}
private func doPostLaunch() {
#if !targetEnvironment(simulator)
detectAndImportAccountFile()
if UserDefaults.standard.enableEMPforWireguard {
startEMProxy(bind_addr: AppConstants.Proxy.serverURL)
}
guard let pf = fetchPairingFile() else {
displayError("Device pairing file not found.")
return
}
start_minimuxer_threads(pf)
#endif
}
func start_minimuxer_threads(_ pairing_file: String) {
targetMinimuxerAddress()
let documentsDirectory = FileManager.default.documentsDirectory.absoluteString
do {
let loggingEnabled = UserDefaults.standard.isMinimuxerConsoleLoggingEnabled
try minimuxerStartWithLogger(pairing_file, documentsDirectory, loggingEnabled)
} catch {
try? FileManager.default.removeItem(at: FileManager.default.documentsDirectory.appendingPathComponent(pairingFileName))
displayError("minimuxer failed to start, please restart MiniStore. \((error as? LocalizedError)?.failureReason ?? "UNKNOWN ERROR")")
return
}
}
func fetchPairingFile() -> String? { PairingFileManager.shared.fetchPairingFile(presentingVC: self) }
func displayError(_ msg: String) {
Logger.main.error("LaunchViewController: \(msg, privacy: .public)")
let alert = UIAlertController(title: "Error launching MiniStore", message: msg, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default))
self.present(alert, animated: true)
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let url = urls.first else { return }
let isSecuredURL = url.startAccessingSecurityScopedResource() == true
defer {
if isSecuredURL {
url.stopAccessingSecurityScopedResource()
}
}
do {
let data = try Data(contentsOf: url)
guard let pairingString = String(data: data, encoding: .utf8) else {
displayError("Unable to read pairing file")
return
}
try pairingString.write(to: FileManager.default.documentsDirectory.appendingPathComponent(pairingFileName), atomically: true, encoding: .utf8)
start_minimuxer_threads(pairingString)
} catch {
// Covers both the read at the top of the block and the Documents write —
// include the underlying error so the two are distinguishable.
Logger.main.error("Pairing file import failed: [\(error._domain, privacy: .public) \(error._code)] \(error.localizedDescription, privacy: .public)")
displayError("Unable to import pairing file: \(error.localizedDescription)")
}
controller.dismiss(animated: true, completion: nil)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
displayError("Choosing a pairing file was cancelled. Please re-open the app and try again.")
}
func importAccountAtFile(_ file: URL, remove: Bool = false) {
let accessGranted = file.startAccessingSecurityScopedResource()
defer { file.stopAccessingSecurityScopedResource() }
if !accessGranted {
Logger.main.warning("importAccountAtFile: security-scoped access denied for \(file.lastPathComponent, privacy: .public) — proceeding anyway (non-scoped URL)")
}
guard let accountD = try? Data(contentsOf: file) else {
return Logger.main.notice("Could not parse data from file \(file)")
}
guard let account = try? Foundation.JSONDecoder().decode(ImportedAccount.self, from: accountD) else {
return Logger.main.notice("Could not parse data from file \(file)")
}
Logger.main.info("Importing account: \(account.email, privacy: .private)")
if remove {
try? FileManager.default.removeItem(at: file)
}
Keychain.shared.appleIDEmailAddress = account.email
Keychain.shared.appleIDPassword = account.password
Keychain.shared.adiPb = account.adiPB
Keychain.shared.identifier = account.local_user
if let altCert = ALTCertificate(p12Data: account.cert, password: account.certpass) {
Keychain.shared.signingCertificate = altCert.encryptedP12Data(withPassword: "") ?? Data()
Keychain.shared.signingCertificatePassword = account.certpass
let toastView = ToastView(text: String(format: NSLocalizedString("Successfully imported '%@'!", comment: ""), account.email), detailText: "MiniStore should be fully operational!")
return toastView.show(in: self)
} else {
let toastView = ToastView(text: NSLocalizedString("Failed to import account certificate!", comment: ""), detailText: "Failed to create ALTCertificate. Check if the password is correct. Still imported account/adi.pb details!")
return toastView.show(in: self)
}
}
func detectAndImportAccountFile() {
let accountFileURL = FileManager.default.documentsDirectory.appendingPathComponent("Account.sideconf")
#if !DEBUG
importAccountAtFile(accountFileURL, remove: true)
#else
importAccountAtFile(accountFileURL)
#endif
}
}
extension LaunchViewController {
@MainActor
func handleLaunchError(_ error: Error, retryCallback: (() async -> Void)? = nil) {
do { throw error } catch let error as NSError {
let title = error.userInfo[NSLocalizedFailureErrorKey] as? String ?? NSLocalizedString("Unable to Launch MiniStore", comment: "")
let desc: String
desc = ([error.debugDescription] + error.underlyingErrors.map { ($0 as NSError).debugDescription }).joined(separator: "\n\n")
let alert = UIAlertController(title: title, message: desc, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Retry", comment: ""), style: .default) { _ in
Task { await retryCallback?() }
})
present(alert, animated: true)
}
}
@MainActor
func finishLaunching() async {
guard !didFinishLaunching else { return }
didFinishLaunching = true
AppManager.shared.update()
AppManager.shared.updateAllSources { [weak self] result in
guard let self, case .failure(let error) = result else { return }
Logger.main.error("Failed to update sources on launch. \(error.localizedDescription, privacy: .public)")
let errorDesc = ErrorProcessing(.fullError).getDescription(error: error as NSError)
Logger.main.error("Failed to update sources on launch: \(errorDesc, privacy: .public)")
var mode: ToastView.InfoMode = .fullError
// Suppress verbose error details for a simple offline condition.
func isOffline(_ e: Error) -> Bool {
let ns = e as NSError
if ns.domain == NSURLErrorDomain && ns.code == NSURLErrorNotConnectedToInternet { return true }
return ns.underlyingErrors.contains(where: isOffline)
}
if isOffline(error) {
mode = .localizedDescription
}
let toastView = ToastView(error: error, mode: mode)
toastView.addTarget(self.destinationViewController, action: #selector(TabBarController.presentSources), for: .touchUpInside)
if let dest = self.destinationViewController {
toastView.show(in: dest.selectedViewController ?? dest)
}
}
updateKnownSources()
WidgetCenter.shared.reloadAllTimelines()
guard let destinationVC = destinationViewController else {
Logger.main.error("finishLaunching: destinationViewController is nil — cannot complete launch")
return
}
destinationVC.loadViewIfNeeded()
addChild(destinationVC)
destinationVC.view.translatesAutoresizingMaskIntoConstraints = false
destinationVC.view.alpha = 0
UIView.performWithoutAnimation {
view.addSubview(destinationVC.view)
NSLayoutConstraint.activate([
destinationVC.view.topAnchor.constraint(equalTo: view.topAnchor),
destinationVC.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
destinationVC.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
destinationVC.view.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
view.layoutIfNeeded()
}
destinationVC.didMove(toParent: self)
self.destinationViewController = destinationVC
destinationVC.view.transform = CGAffineTransform(scaleX: 0.96, y: 0.96)
UIView.animate(withDuration: 0.2, delay: 0,
usingSpringWithDamping: 0.9,
initialSpringVelocity: 0.3,
options: .allowUserInteraction) {
destinationVC.view.alpha = 1
destinationVC.view.transform = .identity
}
}
func updateKnownSources() {
AppManager.shared.updateKnownSources { [weak self] result in
switch result {
case .failure(let error): Logger.main.error("Failed to update known sources: \(error.localizedDescription, privacy: .public)")
case .success((_, let blockedSources)):
DatabaseManager.shared.persistentContainer.performBackgroundTask { [weak self] context in
let blockedSourceIDs = Set(blockedSources.lazy.map { $0.identifier })
let blockedSourceURLs = Set(blockedSources.lazy.compactMap { $0.sourceURL })
let predicate = NSPredicate(format: "%K IN %@ OR %K IN %@", #keyPath(Source.identifier), blockedSourceIDs, #keyPath(Source.sourceURL), blockedSourceURLs)
let sourceErrors = Source.all(satisfying: predicate, in: context).map { source in
let blocked = blockedSources.first { $0.identifier == source.identifier }
return SourceError.blocked(source, bundleIDs: blocked?.bundleIDs, existingSource: source)
}
guard !sourceErrors.isEmpty else { return }
Task { [weak self] in
guard let self else { return }
for error in sourceErrors {
let title = String(format: NSLocalizedString("\"%@\" Blocked", comment: ""), error.$source.name)
let message = [error.localizedDescription, error.recoverySuggestion].compactMap { $0 }.joined(separator: "\n\n")
await self.presentAlert(title: title, message: message)
}
}
}
}
}
}
}
// MARK: - PairingFileManager
final class PairingFileManager {
static let shared = PairingFileManager()
func fetchPairingFile(presentingVC: UIViewController) -> String? {
let fm = FileManager.default
let filename = pairingFileName
let documentsPath = fm.documentsDirectory.appendingPathComponent("/\(filename)")
if fm.fileExists(atPath: documentsPath.path),
let contents = try? String(contentsOf: documentsPath), !contents.isEmpty {
return contents
}
if let url = Bundle.main.url(forResource: "ALTPairingFile", withExtension: "mobiledevicepairing"),
fm.fileExists(atPath: url.path),
let data = fm.contents(atPath: url.path),
let contents = String(data: data, encoding: .utf8),
!contents.isEmpty, !UserDefaults.standard.isPairingReset { return contents }
if let plistString = Bundle.main.object(forInfoDictionaryKey: "ALTPairingFile") as? String,
!plistString.isEmpty, !plistString.contains("insert pairing file here"), !UserDefaults.standard.isPairingReset { return plistString }
presentPairingFileAlert(on: presentingVC)
return nil
}
private func presentPairingFileAlert(on vc: UIViewController) {
let alert = UIAlertController(title: "Pairing File", message: "Select the pairing file or select \"Help\" for help.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Help", style: .default) { _ in
if let url = URL(string: "https://github.com/The-Big-Mini/MiniStore/wiki") { UIApplication.shared.open(url) }
// Delay exit so the URL open animation can complete; asyncAfter keeps the main thread free.
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { exit(0) }
})
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
var types = UTType.types(tag: "plist", tagClass: .filenameExtension, conformingTo: nil)
types.append(contentsOf: UTType.types(tag: "mobiledevicepairing", tagClass: .filenameExtension, conformingTo: .data))
types.append(.xml)
let picker = UIDocumentPickerViewController(forOpeningContentTypes: types)
picker.delegate = vc as? UIDocumentPickerDelegate
picker.shouldShowFileExtensions = true
vc.present(picker, animated: true)
UserDefaults.standard.isPairingReset = false
})
vc.present(alert, animated: true)
}
}