@capgo/capacitor-updater 9.0.0 → 9.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CapgoCapacitorUpdater.podspec +3 -6
  2. package/Package.swift +30 -0
  3. package/README.md +2382 -292
  4. package/android/build.gradle +37 -15
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +23 -0
  7. package/android/src/main/AndroidManifest.xml +0 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +92 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +115 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +227 -195
  11. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +24 -23
  12. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +7435 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5144 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +564 -121
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +43 -49
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
  19. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +230 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +1969 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +278 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +385 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +356 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +553 -0
  26. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +79 -0
  27. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +419 -0
  28. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  29. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
  30. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +959 -0
  31. package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
  32. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +323 -0
  33. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  34. package/dist/docs.json +4431 -840
  35. package/dist/esm/definitions.d.ts +2607 -225
  36. package/dist/esm/definitions.js +103 -1
  37. package/dist/esm/definitions.js.map +1 -1
  38. package/dist/esm/history.d.ts +1 -0
  39. package/dist/esm/history.js +283 -0
  40. package/dist/esm/history.js.map +1 -0
  41. package/dist/esm/index.d.ts +3 -2
  42. package/dist/esm/index.js +5 -4
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/web.d.ts +53 -42
  45. package/dist/esm/web.js +180 -37
  46. package/dist/esm/web.js.map +1 -1
  47. package/dist/plugin.cjs.js +570 -37
  48. package/dist/plugin.cjs.js.map +1 -1
  49. package/dist/plugin.js +570 -37
  50. package/dist/plugin.js.map +1 -1
  51. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  52. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  53. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  54. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  55. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +5642 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +4572 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +380 -0
  60. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  61. package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
  62. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +452 -0
  63. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +380 -0
  64. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  65. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  66. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +97 -0
  67. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +871 -0
  68. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
  69. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  70. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +304 -0
  71. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  72. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  73. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  74. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  75. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +3905 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +151 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +249 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +528 -0
  80. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  81. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  82. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  83. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  84. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1095 -0
  85. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  86. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  87. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  88. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +192 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +454 -0
  91. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  92. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  93. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  94. package/package.json +80 -43
  95. package/scripts/builtin-hashes-lib.mjs +148 -0
  96. package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
  97. package/scripts/resolve-real-path.mjs +25 -0
  98. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1130
  99. package/ios/Plugin/BundleInfo.swift +0 -113
  100. package/ios/Plugin/BundleStatus.swift +0 -48
  101. package/ios/Plugin/CapacitorUpdater.swift +0 -858
  102. package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
  103. package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
  104. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -677
  105. package/ios/Plugin/CryptoCipher.swift +0 -240
  106. /package/{LICENCE → LICENSE} +0 -0
  107. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  108. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  109. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -0,0 +1,871 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ import UIKit
8
+ import Capacitor
9
+
10
+ private var lastShakeMenuShownAt: TimeInterval = 0
11
+ private let shakeMenuCooldownSeconds: TimeInterval = 1.2
12
+ private let threeFingerPinchScaleDelta: CGFloat = 0.12
13
+
14
+ final class ThreeFingerPinchGestureRecognizer: UIGestureRecognizer {
15
+ private var initialSpan: CGFloat = 0
16
+ private(set) var scale: CGFloat = 1
17
+ var onTrackingStarted: (() -> Void)?
18
+
19
+ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
20
+ super.touchesBegan(touches, with: event)
21
+ guard let view = self.view, let activeTouches = activeTouches(with: event), activeTouches.count <= 3 else {
22
+ self.state = .failed
23
+ return
24
+ }
25
+
26
+ if activeTouches.count == 3 {
27
+ self.initialSpan = span(for: activeTouches, in: view)
28
+ self.scale = 1
29
+ if self.initialSpan > 0 {
30
+ self.onTrackingStarted?()
31
+ } else {
32
+ self.state = .failed
33
+ }
34
+ }
35
+ }
36
+
37
+ override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
38
+ super.touchesMoved(touches, with: event)
39
+ guard let view = self.view,
40
+ let activeTouches = activeTouches(with: event),
41
+ activeTouches.count == 3,
42
+ self.initialSpan > 0 else {
43
+ self.state = .failed
44
+ return
45
+ }
46
+
47
+ self.scale = span(for: activeTouches, in: view) / self.initialSpan
48
+ if abs(self.scale - 1) >= threeFingerPinchScaleDelta {
49
+ self.state = .recognized
50
+ }
51
+ }
52
+
53
+ override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
54
+ super.touchesEnded(touches, with: event)
55
+ if self.state == .possible {
56
+ self.state = .failed
57
+ }
58
+ }
59
+
60
+ override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
61
+ super.touchesCancelled(touches, with: event)
62
+ self.state = .cancelled
63
+ }
64
+
65
+ override func reset() {
66
+ super.reset()
67
+ self.initialSpan = 0
68
+ self.scale = 1
69
+ }
70
+
71
+ private func activeTouches(with event: UIEvent) -> [UITouch]? {
72
+ event.touches(for: self)?.filter { touch in
73
+ touch.phase != .ended && touch.phase != .cancelled
74
+ }
75
+ }
76
+
77
+ private func span(for touches: [UITouch], in view: UIView) -> CGFloat {
78
+ guard !touches.isEmpty else {
79
+ return 0
80
+ }
81
+
82
+ let points = touches.map { $0.location(in: view) }
83
+ let center = points.reduce(CGPoint.zero) { result, point in
84
+ CGPoint(x: result.x + point.x, y: result.y + point.y)
85
+ }
86
+ let centerPoint = CGPoint(x: center.x / CGFloat(points.count), y: center.y / CGFloat(points.count))
87
+ let totalDistance = points.reduce(CGFloat(0)) { result, point in
88
+ result + hypot(point.x - centerPoint.x, point.y - centerPoint.y)
89
+ }
90
+ return totalDistance / CGFloat(points.count)
91
+ }
92
+ }
93
+
94
+ extension UIApplication {
95
+ public class func topViewController(_ base: UIViewController? = nil) -> UIViewController? {
96
+ let resolvedBase = base ?? keyWindowRootViewController
97
+ if let nav = resolvedBase as? UINavigationController {
98
+ return topViewController(nav.visibleViewController)
99
+ }
100
+ if let tab = resolvedBase as? UITabBarController, let selected = tab.selectedViewController {
101
+ return topViewController(selected)
102
+ }
103
+ if let presented = resolvedBase?.presentedViewController {
104
+ return topViewController(presented)
105
+ }
106
+ return resolvedBase
107
+ }
108
+
109
+ private static var keyWindowRootViewController: UIViewController? {
110
+ let scenes = shared.connectedScenes.compactMap { $0 as? UIWindowScene }
111
+ let foregroundScenes = scenes.filter { $0.activationState == .foregroundActive }
112
+ let candidates = foregroundScenes.isEmpty ? scenes : foregroundScenes
113
+ let window = candidates.flatMap(\.windows).first(where: \.isKeyWindow) ?? candidates.first?.windows.first
114
+ return window?.rootViewController
115
+ }
116
+ }
117
+
118
+ extension CapacitorUpdaterPlugin: UIGestureRecognizerDelegate {
119
+ func syncShakeMenuGestureRecognizer() {
120
+ DispatchQueue.main.async { [weak self] in
121
+ guard let self else { return }
122
+
123
+ let shouldInstall = self.shakeMenuGesture == Self.shakeMenuGestureThreeFingerPinch &&
124
+ (self.shakeMenuEnabled || self.shakeChannelSelectorEnabled)
125
+
126
+ guard shouldInstall, let targetView = self.bridge?.viewController?.view ?? self.bridge?.webView else {
127
+ self.removeShakeMenuGestureRecognizer()
128
+ return
129
+ }
130
+
131
+ if self.shakeMenuPinchGestureRecognizer?.view === targetView {
132
+ return
133
+ }
134
+
135
+ self.removeShakeMenuGestureRecognizer()
136
+
137
+ let recognizer = ThreeFingerPinchGestureRecognizer(target: self, action: #selector(self.handleShakeMenuPinch(_:)))
138
+ recognizer.cancelsTouchesInView = false
139
+ recognizer.delaysTouchesBegan = false
140
+ recognizer.delaysTouchesEnded = false
141
+ recognizer.delegate = self
142
+ recognizer.onTrackingStarted = { [weak self] in
143
+ self?.logger.info("Three finger pinch tracking started")
144
+ }
145
+ targetView.addGestureRecognizer(recognizer)
146
+ self.shakeMenuPinchGestureRecognizer = recognizer
147
+ self.logger.info("Three finger pinch menu gesture initialized")
148
+ }
149
+ }
150
+
151
+ func removeShakeMenuGestureRecognizer() {
152
+ if let recognizer = self.shakeMenuPinchGestureRecognizer {
153
+ recognizer.view?.removeGestureRecognizer(recognizer)
154
+ self.shakeMenuPinchGestureRecognizer = nil
155
+ self.shakeMenuPinchGestureTriggered = false
156
+ self.logger.info("Three finger pinch menu gesture stopped")
157
+ }
158
+ }
159
+
160
+ @objc func handleShakeMenuPinch(_ recognizer: ThreeFingerPinchGestureRecognizer) {
161
+ guard recognizer.state == .recognized, !self.shakeMenuPinchGestureTriggered else {
162
+ return
163
+ }
164
+ guard abs(recognizer.scale - 1) >= threeFingerPinchScaleDelta else {
165
+ return
166
+ }
167
+ guard self.shakeMenuGesture == Self.shakeMenuGestureThreeFingerPinch, let bridge = self.bridge else {
168
+ return
169
+ }
170
+ guard let window = recognizer.view?.window ?? bridge.viewController?.view.window else {
171
+ return
172
+ }
173
+
174
+ self.shakeMenuPinchGestureTriggered = true
175
+ self.logger.info("Three finger pinch detected")
176
+ _ = window.showCapacitorUpdaterMenu(plugin: self, bridge: bridge, gestureName: "Three finger pinch")
177
+ }
178
+
179
+ public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
180
+ if gestureRecognizer === self.shakeMenuPinchGestureRecognizer {
181
+ self.shakeMenuPinchGestureTriggered = false
182
+ }
183
+ return true
184
+ }
185
+
186
+ public func gestureRecognizer(
187
+ _: UIGestureRecognizer,
188
+ shouldRecognizeSimultaneouslyWith _: UIGestureRecognizer
189
+ ) -> Bool {
190
+ true
191
+ }
192
+ }
193
+
194
+ extension UIWindow {
195
+ private var menuHostViewController: UIViewController? {
196
+ UIApplication.topViewController(rootViewController)
197
+ }
198
+
199
+ override open func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
200
+ if motion == .motionShake {
201
+ guard let bridgeViewController = rootViewController as? CAPBridgeViewController,
202
+ let bridge = bridgeViewController.bridge,
203
+ let plugin = bridge.plugin(withName: "CapacitorUpdater") as? CapacitorUpdaterPlugin else {
204
+ return
205
+ }
206
+ guard plugin.shakeMenuGesture == CapacitorUpdaterPlugin.shakeMenuGestureShake else {
207
+ return
208
+ }
209
+
210
+ _ = showCapacitorUpdaterMenu(plugin: plugin, bridge: bridge, gestureName: "Shake")
211
+ }
212
+ }
213
+
214
+ @discardableResult
215
+ fileprivate func showCapacitorUpdaterMenu(plugin: CapacitorUpdaterPlugin, bridge: CAPBridgeProtocol, gestureName: String) -> Bool {
216
+ let canShowPreviewMenu = plugin.shakeMenuEnabled && plugin.hasActivePreviewSession()
217
+ let canShowChannelSelector = plugin.shakeChannelSelectorEnabled
218
+
219
+ if !canShowPreviewMenu && !canShowChannelSelector {
220
+ if plugin.shakeMenuEnabled {
221
+ plugin.logger.info("\(gestureName) preview menu ignored because no preview session is active")
222
+ }
223
+ return false
224
+ }
225
+
226
+ let now = Date().timeIntervalSince1970
227
+ guard now - lastShakeMenuShownAt >= shakeMenuCooldownSeconds else {
228
+ plugin.logger.info("\(gestureName) menu ignored because cooldown is active")
229
+ return false
230
+ }
231
+
232
+ let didShow = canShowPreviewMenu
233
+ ? showDefaultMenu(plugin: plugin, bridge: bridge)
234
+ : showChannelSelector(plugin: plugin, bridge: bridge)
235
+
236
+ if didShow {
237
+ lastShakeMenuShownAt = now
238
+ }
239
+ return didShow
240
+ }
241
+
242
+ @discardableResult
243
+ private func showDefaultMenu(plugin: CapacitorUpdaterPlugin, bridge: CAPBridgeProtocol) -> Bool {
244
+ // Prevent multiple alerts from showing
245
+ guard let topVC = self.menuHostViewController else {
246
+ return false
247
+ }
248
+ if topVC.isKind(of: UIAlertController.self) {
249
+ plugin.logger.info("UIAlertController is already presented")
250
+ return false
251
+ }
252
+
253
+ guard plugin.hasActivePreviewSession() else {
254
+ plugin.logger.info("Shake preview menu ignored because no preview session is active")
255
+ return false
256
+ }
257
+
258
+ let appName = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String ?? "App"
259
+ let title = "Preview \(appName) Menu"
260
+ let message = "Reload, switch, or leave the current preview."
261
+ let okButtonTitle = "Leave test app"
262
+ let reloadButtonTitle = "Reload preview"
263
+ let cancelButtonTitle = "Close menu"
264
+
265
+ let alertShake = UIAlertController(title: title, message: message, preferredStyle: .alert)
266
+
267
+ alertShake.addAction(UIAlertAction(title: reloadButtonTitle, style: .default) { _ in
268
+ DispatchQueue.global(qos: .userInitiated).async {
269
+ if !plugin.reloadPreviewSessionFromShakeMenu() {
270
+ DispatchQueue.main.async {
271
+ self.showError(message: "Could not reload the test app.", plugin: plugin)
272
+ }
273
+ }
274
+ }
275
+ })
276
+
277
+ if !plugin.previewMenuPreviews().isEmpty {
278
+ alertShake.addAction(UIAlertAction(title: "Switch preview", style: .default) { _ in
279
+ let showSelector = {
280
+ self.showPreviewSelector(plugin: plugin)
281
+ }
282
+
283
+ if let presenter = alertShake.presentingViewController {
284
+ presenter.dismiss(animated: true, completion: showSelector)
285
+ } else {
286
+ DispatchQueue.main.async(execute: showSelector)
287
+ }
288
+ })
289
+ }
290
+
291
+ if plugin.shakeChannelSelectorEnabled {
292
+ alertShake.addAction(UIAlertAction(title: "Switch channel", style: .default) { _ in
293
+ let showSelector = {
294
+ _ = self.showChannelSelector(plugin: plugin, bridge: bridge)
295
+ }
296
+
297
+ if let presenter = alertShake.presentingViewController {
298
+ presenter.dismiss(animated: true, completion: showSelector)
299
+ } else {
300
+ DispatchQueue.main.async(execute: showSelector)
301
+ }
302
+ })
303
+ }
304
+
305
+ alertShake.addAction(UIAlertAction(title: okButtonTitle, style: .default) { _ in
306
+ DispatchQueue.global(qos: .userInitiated).async {
307
+ if !plugin.leavePreviewSessionFromShakeMenu() {
308
+ DispatchQueue.main.async {
309
+ self.showError(message: "Could not leave the test app.", plugin: plugin)
310
+ }
311
+ }
312
+ }
313
+ })
314
+
315
+ alertShake.addAction(UIAlertAction(title: cancelButtonTitle, style: .default))
316
+
317
+ DispatchQueue.main.async {
318
+ topVC.present(alertShake, animated: true)
319
+ }
320
+ return true
321
+ }
322
+
323
+ private func showConfiguredDefaultMenu(plugin: CapacitorUpdaterPlugin, bridge: CAPBridgeProtocol) {
324
+ let appName = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String ?? "App"
325
+ let title = "Preview \(appName) Menu"
326
+ let message = "What would you like to do?"
327
+ let okButtonTitle = "Go Home"
328
+ let reloadButtonTitle = "Reload app"
329
+ let cancelButtonTitle = "Close menu"
330
+
331
+ let updater = plugin.implementation
332
+
333
+ func resetBuiltin() {
334
+ updater.reset()
335
+ bridge.setServerBasePath("")
336
+ DispatchQueue.main.async {
337
+ if let viewController = (self.rootViewController as? CAPBridgeViewController) {
338
+ viewController.loadView()
339
+ viewController.viewDidLoad()
340
+ }
341
+ _ = updater.delete(id: updater.getCurrentBundleId())
342
+ plugin.logger.info("Reset to builtin version")
343
+ }
344
+ }
345
+
346
+ let bundleId = updater.getCurrentBundleId()
347
+ if let viewController = (self.rootViewController as? CAPBridgeViewController) {
348
+ plugin.logger.info("getServerBasePath: \(viewController.getServerBasePath())")
349
+ }
350
+ plugin.logger.info("bundleId: \(bundleId)")
351
+
352
+ let alertShake = UIAlertController(title: title, message: message, preferredStyle: .alert)
353
+
354
+ alertShake.addAction(UIAlertAction(title: okButtonTitle, style: .default) { _ in
355
+ guard let next = updater.getNextBundle() else {
356
+ resetBuiltin()
357
+ return
358
+ }
359
+ if !next.isBuiltin() {
360
+ plugin.logger.info("Resetting to: \(next.toString())")
361
+ _ = updater.set(bundle: next)
362
+ guard let destHot = try? updater.getBundleDirectory(id: next.getId()) else {
363
+ resetBuiltin()
364
+ return
365
+ }
366
+ plugin.logger.info("Reloading \(next.toString())")
367
+ bridge.setServerBasePath(destHot.path)
368
+ } else {
369
+ resetBuiltin()
370
+ }
371
+ plugin.logger.info("Reload app done")
372
+ })
373
+
374
+ alertShake.addAction(UIAlertAction(title: cancelButtonTitle, style: .default))
375
+
376
+ alertShake.addAction(UIAlertAction(title: reloadButtonTitle, style: .default) { _ in
377
+ DispatchQueue.main.async {
378
+ bridge.webView?.reload()
379
+ }
380
+ })
381
+
382
+ DispatchQueue.main.async {
383
+ if let topVC = self.menuHostViewController {
384
+ topVC.present(alertShake, animated: true)
385
+ }
386
+ }
387
+ }
388
+
389
+ private func previewLabel(_ preview: [String: Any]) -> String {
390
+ let bundle = preview["bundle"] as? [String: Any]
391
+ let name = preview["name"] as? String
392
+ let version = bundle?["version"] as? String
393
+ var label = [name, version, preview["id"] as? String]
394
+ .compactMap { value in
395
+ guard let value, !value.isEmpty else { return nil }
396
+ return value
397
+ }
398
+ .first ?? "Preview"
399
+ if preview["isActive"] as? Bool == true {
400
+ label += " (current)"
401
+ }
402
+ return label
403
+ }
404
+
405
+ private func showPreviewSelector(plugin: CapacitorUpdaterPlugin) {
406
+ guard let topVC = self.menuHostViewController else {
407
+ return
408
+ }
409
+ if topVC.isKind(of: UIAlertController.self) {
410
+ plugin.logger.info("UIAlertController is already presented")
411
+ return
412
+ }
413
+
414
+ let previews = plugin.previewMenuPreviews()
415
+ guard !previews.isEmpty else {
416
+ self.showError(message: "No saved previews available on this device.", plugin: plugin)
417
+ return
418
+ }
419
+
420
+ let alert = UIAlertController(title: "Select Preview", message: "Choose a local preview to open", preferredStyle: .actionSheet)
421
+ let previewsToShow = Array(previews.prefix(5))
422
+ for preview in previewsToShow {
423
+ let title = self.previewLabel(preview)
424
+ let id = preview["id"] as? String ?? ""
425
+ alert.addAction(UIAlertAction(title: title, style: .default) { [weak self] _ in
426
+ self?.selectPreview(id: id, plugin: plugin)
427
+ })
428
+ }
429
+
430
+ if previews.count > 5 {
431
+ alert.addAction(UIAlertAction(title: "More previews...", style: .default) { [weak self] _ in
432
+ self?.showSearchablePreviewPicker(previews: previews, plugin: plugin)
433
+ })
434
+ }
435
+
436
+ alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
437
+
438
+ if let popoverController = alert.popoverPresentationController {
439
+ popoverController.sourceView = self
440
+ popoverController.sourceRect = CGRect(x: self.bounds.midX, y: self.bounds.midY, width: 0, height: 0)
441
+ popoverController.permittedArrowDirections = []
442
+ }
443
+
444
+ topVC.present(alert, animated: true)
445
+ }
446
+
447
+ private func showSearchablePreviewPicker(previews: [[String: Any]], plugin: CapacitorUpdaterPlugin) {
448
+ let alert = UIAlertController(title: "Search Previews", message: "Enter preview name or version", preferredStyle: .alert)
449
+
450
+ alert.addTextField { textField in
451
+ textField.placeholder = "Preview name..."
452
+ }
453
+
454
+ alert.addAction(UIAlertAction(title: "Search", style: .default) { [weak self, weak alert] _ in
455
+ guard let self else { return }
456
+ guard let searchText = alert?.textFields?.first?.text?.lowercased(), !searchText.isEmpty else {
457
+ self.showPreviewSelector(plugin: plugin)
458
+ return
459
+ }
460
+
461
+ let filtered = previews.filter { self.previewLabel($0).lowercased().contains(searchText) }
462
+ if filtered.isEmpty {
463
+ self.showError(message: "No previews found matching '\(searchText)'", plugin: plugin)
464
+ } else if filtered.count == 1, let id = filtered[0]["id"] as? String {
465
+ self.selectPreview(id: id, plugin: plugin)
466
+ } else {
467
+ self.presentPreviewPicker(previews: filtered, plugin: plugin)
468
+ }
469
+ })
470
+
471
+ alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
472
+
473
+ DispatchQueue.main.async {
474
+ if let topVC = self.menuHostViewController {
475
+ topVC.present(alert, animated: true)
476
+ }
477
+ }
478
+ }
479
+
480
+ private func presentPreviewPicker(previews: [[String: Any]], plugin: CapacitorUpdaterPlugin) {
481
+ let alert = UIAlertController(title: "Select Preview", message: "Choose a local preview to open", preferredStyle: .actionSheet)
482
+ for preview in previews.prefix(5) {
483
+ let id = preview["id"] as? String ?? ""
484
+ alert.addAction(UIAlertAction(title: self.previewLabel(preview), style: .default) { [weak self] _ in
485
+ self?.selectPreview(id: id, plugin: plugin)
486
+ })
487
+ }
488
+ alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
489
+
490
+ if let popoverController = alert.popoverPresentationController {
491
+ popoverController.sourceView = self
492
+ popoverController.sourceRect = CGRect(x: self.bounds.midX, y: self.bounds.midY, width: 0, height: 0)
493
+ popoverController.permittedArrowDirections = []
494
+ }
495
+
496
+ DispatchQueue.main.async {
497
+ if let topVC = self.menuHostViewController {
498
+ topVC.present(alert, animated: true)
499
+ }
500
+ }
501
+ }
502
+
503
+ private func selectPreview(id: String, plugin: CapacitorUpdaterPlugin) {
504
+ DispatchQueue.global(qos: .userInitiated).async {
505
+ if !plugin.setPreviewFromShakeMenu(id: id) {
506
+ DispatchQueue.main.async {
507
+ self.showError(message: "Could not switch preview.", plugin: plugin)
508
+ }
509
+ }
510
+ }
511
+ }
512
+
513
+ @discardableResult
514
+ private func showChannelSelector(plugin: CapacitorUpdaterPlugin, bridge: CAPBridgeProtocol) -> Bool {
515
+ // Prevent multiple alerts from showing
516
+ guard let topVC = self.menuHostViewController else {
517
+ return false
518
+ }
519
+ if topVC.isKind(of: UIAlertController.self) {
520
+ plugin.logger.info("UIAlertController is already presented")
521
+ return false
522
+ }
523
+
524
+ let updater = plugin.implementation
525
+
526
+ // Show loading indicator
527
+ let loadingAlert = UIAlertController(title: "Loading Channels...", message: nil, preferredStyle: .alert)
528
+ var didCancel = false
529
+ let loadingIndicator = UIActivityIndicatorView(style: .medium)
530
+ loadingIndicator.translatesAutoresizingMaskIntoConstraints = false
531
+ loadingIndicator.startAnimating()
532
+ loadingAlert.view.addSubview(loadingIndicator)
533
+
534
+ NSLayoutConstraint.activate([
535
+ loadingIndicator.centerXAnchor.constraint(equalTo: loadingAlert.view.centerXAnchor),
536
+ loadingIndicator.bottomAnchor.constraint(equalTo: loadingAlert.view.bottomAnchor, constant: -20)
537
+ ])
538
+
539
+ // Add cancel button to loading alert
540
+ loadingAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
541
+ didCancel = true
542
+ })
543
+
544
+ DispatchQueue.main.async {
545
+ topVC.present(loadingAlert, animated: true) {
546
+ // Fetch channels in background
547
+ DispatchQueue.global(qos: .userInitiated).async {
548
+ let result = updater.listChannels()
549
+
550
+ DispatchQueue.main.async {
551
+ loadingAlert.dismiss(animated: true) {
552
+ guard !didCancel else { return }
553
+ if !result.error.isEmpty {
554
+ self.showError(message: "Failed to load channels: \(result.error)", plugin: plugin)
555
+ } else if result.channels.isEmpty {
556
+ self.showError(message: "No channels available for self-assignment", plugin: plugin)
557
+ } else {
558
+ self.presentChannelPicker(channels: result.channels, plugin: plugin, bridge: bridge)
559
+ }
560
+ }
561
+ }
562
+ }
563
+ }
564
+ }
565
+ return true
566
+ }
567
+
568
+ private func presentChannelPicker(channels: [[String: Any]], plugin: CapacitorUpdaterPlugin, bridge: CAPBridgeProtocol) {
569
+ let alert = UIAlertController(title: "Select Channel", message: "Choose a channel to switch to", preferredStyle: .actionSheet)
570
+
571
+ // Get channel names
572
+ let channelNames = channels.compactMap { $0["name"] as? String }
573
+
574
+ // Show first 5 channels as actions
575
+ let channelsToShow = Array(channelNames.prefix(5))
576
+
577
+ for channelName in channelsToShow {
578
+ alert.addAction(UIAlertAction(title: channelName, style: .default) { [weak self] _ in
579
+ self?.selectChannel(name: channelName, plugin: plugin, bridge: bridge)
580
+ })
581
+ }
582
+
583
+ // If there are more channels, add a "More..." option
584
+ if channelNames.count > 5 {
585
+ alert.addAction(UIAlertAction(title: "More channels...", style: .default) { [weak self] _ in
586
+ self?.showSearchableChannelPicker(channels: channels, plugin: plugin, bridge: bridge)
587
+ })
588
+ }
589
+
590
+ alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
591
+
592
+ // For iPad support
593
+ if let popoverController = alert.popoverPresentationController {
594
+ popoverController.sourceView = self
595
+ popoverController.sourceRect = CGRect(x: self.bounds.midX, y: self.bounds.midY, width: 0, height: 0)
596
+ popoverController.permittedArrowDirections = []
597
+ }
598
+
599
+ DispatchQueue.main.async {
600
+ if let topVC = self.menuHostViewController {
601
+ topVC.present(alert, animated: true)
602
+ }
603
+ }
604
+ }
605
+
606
+ private func showSearchableChannelPicker(channels: [[String: Any]], plugin: CapacitorUpdaterPlugin, bridge: CAPBridgeProtocol) {
607
+ let alert = UIAlertController(title: "Search Channels", message: "Enter channel name to search", preferredStyle: .alert)
608
+
609
+ alert.addTextField { textField in
610
+ textField.placeholder = "Channel name..."
611
+ }
612
+
613
+ let channelNames = channels.compactMap { $0["name"] as? String }
614
+
615
+ alert.addAction(UIAlertAction(title: "Search", style: .default) { [weak self, weak alert] _ in
616
+ guard let searchText = alert?.textFields?.first?.text?.lowercased(), !searchText.isEmpty else {
617
+ // If empty, show first 5
618
+ self?.presentChannelPicker(channels: channels, plugin: plugin, bridge: bridge)
619
+ return
620
+ }
621
+
622
+ // Filter channels
623
+ let filtered = channelNames.filter { $0.lowercased().contains(searchText) }
624
+
625
+ if filtered.isEmpty {
626
+ self?.showError(message: "No channels found matching '\(searchText)'", plugin: plugin)
627
+ } else if filtered.count == 1 {
628
+ // Directly select if only one match
629
+ self?.selectChannel(name: filtered[0], plugin: plugin, bridge: bridge)
630
+ } else {
631
+ // Show filtered results
632
+ let filteredChannels = channels.filter { channel in
633
+ if let name = channel["name"] as? String {
634
+ return name.lowercased().contains(searchText)
635
+ }
636
+ return false
637
+ }
638
+ self?.presentChannelPicker(channels: filteredChannels, plugin: plugin, bridge: bridge)
639
+ }
640
+ })
641
+
642
+ alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
643
+
644
+ DispatchQueue.main.async {
645
+ if let topVC = self.menuHostViewController {
646
+ topVC.present(alert, animated: true)
647
+ }
648
+ }
649
+ }
650
+
651
+ private func selectChannel(name: String, plugin: CapacitorUpdaterPlugin, bridge: CAPBridgeProtocol) {
652
+ let updater = plugin.implementation
653
+
654
+ // Show progress indicator
655
+ let progressAlert = UIAlertController(title: "Switching to \(name)", message: "Setting channel...", preferredStyle: .alert)
656
+ let indicator = UIActivityIndicatorView(style: .medium)
657
+ indicator.translatesAutoresizingMaskIntoConstraints = false
658
+ indicator.startAnimating()
659
+ progressAlert.view.addSubview(indicator)
660
+
661
+ NSLayoutConstraint.activate([
662
+ indicator.centerXAnchor.constraint(equalTo: progressAlert.view.centerXAnchor),
663
+ indicator.bottomAnchor.constraint(equalTo: progressAlert.view.bottomAnchor, constant: -20)
664
+ ])
665
+
666
+ DispatchQueue.main.async {
667
+ if let topVC = self.menuHostViewController {
668
+ topVC.present(progressAlert, animated: true) {
669
+ DispatchQueue.global(qos: .userInitiated).async {
670
+ // Set the channel - respect plugin's allowSetDefaultChannel config
671
+ let setResult = updater.setChannel(
672
+ channel: name,
673
+ defaultChannelKey: "CapacitorUpdater.defaultChannel",
674
+ defaultChannelFromSetChannelKey: CapacitorUpdaterPlugin.defaultChannelFromSetChannelStorageKey,
675
+ allowSetDefaultChannel: plugin.allowSetDefaultChannel,
676
+ configDefaultChannel: plugin.getConfig().getString("defaultChannel", "") ?? ""
677
+ )
678
+
679
+ if !setResult.error.isEmpty {
680
+ DispatchQueue.main.async {
681
+ progressAlert.dismiss(animated: true) {
682
+ self.showError(message: "Failed to set channel: \(setResult.error)", plugin: plugin)
683
+ }
684
+ }
685
+ return
686
+ }
687
+ guard plugin.persistDefaultChannelStateFromDefaults() else {
688
+ DispatchQueue.main.async {
689
+ progressAlert.dismiss(animated: true) {
690
+ self.showError(message: "Channel set to \(name), but local persistence failed.", plugin: plugin)
691
+ }
692
+ }
693
+ return
694
+ }
695
+
696
+ // Update progress message
697
+ DispatchQueue.main.async {
698
+ progressAlert.message = "Checking for updates..."
699
+ }
700
+
701
+ // Check for updates with the new channel
702
+ let pluginUpdateUrl = plugin.getUpdateUrl()
703
+ let updateUrlStr = pluginUpdateUrl.isEmpty ? CapacitorUpdaterPlugin.updateUrlDefault : pluginUpdateUrl
704
+ guard let updateUrl = URL(string: updateUrlStr) else {
705
+ DispatchQueue.main.async {
706
+ progressAlert.dismiss(animated: true) {
707
+ self.showError(
708
+ message: "Channel set to \(name). Invalid update URL, could not check for updates.",
709
+ plugin: plugin
710
+ )
711
+ }
712
+ }
713
+ return
714
+ }
715
+
716
+ let latest = updater.getLatest(url: updateUrl, channel: name)
717
+ let latestKind = latest.kind
718
+
719
+ let detail = [latest.message, latest.error, latestKind]
720
+ .compactMap { value in
721
+ guard let value, !value.isEmpty else { return nil }
722
+ return value
723
+ }
724
+ .first ?? "server did not provide a message"
725
+
726
+ // Handle update errors first (before "no new version" check)
727
+ if latestKind == "failed" || (latest.error?.isEmpty == false && latestKind != "up_to_date" && latestKind != "blocked") {
728
+ DispatchQueue.main.async {
729
+ progressAlert.dismiss(animated: true) {
730
+ self.showError(message: "Channel set to \(name). Update check failed: \(detail)", plugin: plugin)
731
+ }
732
+ }
733
+ return
734
+ }
735
+
736
+ if latestKind == "blocked" {
737
+ DispatchQueue.main.async {
738
+ progressAlert.dismiss(animated: true) {
739
+ self.showError(message: "Channel set to \(name). Update check blocked: \(detail)", plugin: plugin)
740
+ }
741
+ }
742
+ return
743
+ }
744
+
745
+ // Check if there's an actual update available. A manifest-only
746
+ // response legitimately has no URL (the files come from the
747
+ // manifest, not a zip), so only report "already on latest" when
748
+ // the URL is empty AND there is no manifest to download from.
749
+ let hasManifest = !(latest.manifest?.isEmpty ?? true)
750
+ if latestKind == "up_to_date" || (latest.url.isEmpty && !hasManifest) {
751
+ DispatchQueue.main.async {
752
+ progressAlert.dismiss(animated: true) {
753
+ self.showSuccess(message: "Channel set to \(name). Already on latest version.", plugin: plugin)
754
+ }
755
+ }
756
+ return
757
+ }
758
+
759
+ // Update message
760
+ DispatchQueue.main.async {
761
+ progressAlert.message = "Downloading update \(latest.version)..."
762
+ }
763
+
764
+ // Download the update
765
+ do {
766
+ let bundle: BundleInfo
767
+ if let manifest = latest.manifest, !manifest.isEmpty {
768
+ bundle = try updater.downloadManifest(
769
+ manifest: manifest,
770
+ version: latest.version,
771
+ sessionKey: latest.sessionKey ?? ""
772
+ )
773
+ } else {
774
+ // Safe unwrap URL
775
+ guard let downloadUrl = URL(string: latest.url) else {
776
+ DispatchQueue.main.async {
777
+ progressAlert.dismiss(animated: true) {
778
+ self.showError(message: "Failed to download update: invalid update URL.", plugin: plugin)
779
+ }
780
+ }
781
+ return
782
+ }
783
+ // Same gate as download() and auto-update: the checksum is required and
784
+ // verified (decrypted when a public key is set) before extraction.
785
+ bundle = try updater.downloadVerified(
786
+ url: downloadUrl,
787
+ version: latest.version,
788
+ sessionKey: latest.sessionKey ?? "",
789
+ expectedChecksum: latest.checksum
790
+ )
791
+ }
792
+
793
+ // Set as next bundle
794
+ _ = updater.setNextBundle(next: bundle.getId())
795
+
796
+ DispatchQueue.main.async {
797
+ progressAlert.dismiss(animated: true) {
798
+ self.showSuccessWithReload(
799
+ message: "Update downloaded! Reload to apply version \(latest.version)?",
800
+ plugin: plugin,
801
+ bridge: bridge,
802
+ onReload: {
803
+ _ = updater.set(bundle: bundle)
804
+ _ = plugin.reloadCurrentBundle()
805
+ }
806
+ )
807
+ }
808
+ }
809
+ } catch {
810
+ DispatchQueue.main.async {
811
+ progressAlert.dismiss(animated: true) {
812
+ self.showError(message: "Failed to download update: \(error.localizedDescription)", plugin: plugin)
813
+ }
814
+ }
815
+ }
816
+ }
817
+ }
818
+ }
819
+ }
820
+ }
821
+
822
+ private func showError(message: String, plugin: CapacitorUpdaterPlugin) {
823
+ plugin.logger.error(message)
824
+ let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
825
+ alert.addAction(UIAlertAction(title: "OK", style: .default))
826
+
827
+ DispatchQueue.main.async {
828
+ if let topVC = self.menuHostViewController {
829
+ topVC.present(alert, animated: true)
830
+ }
831
+ }
832
+ }
833
+
834
+ private func showSuccess(message: String, plugin: CapacitorUpdaterPlugin) {
835
+ plugin.logger.info(message)
836
+ let alert = UIAlertController(title: "Success", message: message, preferredStyle: .alert)
837
+ alert.addAction(UIAlertAction(title: "OK", style: .default))
838
+
839
+ DispatchQueue.main.async {
840
+ if let topVC = self.menuHostViewController {
841
+ topVC.present(alert, animated: true)
842
+ }
843
+ }
844
+ }
845
+
846
+ private func showSuccessWithReload(
847
+ message: String,
848
+ plugin: CapacitorUpdaterPlugin,
849
+ bridge: CAPBridgeProtocol,
850
+ onReload: (() -> Void)? = nil
851
+ ) {
852
+ plugin.logger.info(message)
853
+ let alert = UIAlertController(title: "Update Ready", message: message, preferredStyle: .alert)
854
+ alert.addAction(UIAlertAction(title: "Later", style: .cancel))
855
+ alert.addAction(UIAlertAction(title: "Reload Now", style: .default) { _ in
856
+ if let onReload = onReload {
857
+ onReload()
858
+ } else {
859
+ DispatchQueue.main.async {
860
+ bridge.webView?.reload()
861
+ }
862
+ }
863
+ })
864
+
865
+ DispatchQueue.main.async {
866
+ if let topVC = self.menuHostViewController {
867
+ topVC.present(alert, animated: true)
868
+ }
869
+ }
870
+ }
871
+ }