@capgo/capacitor-updater 8.52.1 → 8.53.0

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 (24) hide show
  1. package/README.md +198 -66
  2. package/android/build.gradle +2 -1
  3. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +409 -148
  4. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +521 -197
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +2 -1
  6. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +226 -105
  7. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +30 -10
  8. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +318 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +4 -4
  11. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +1 -1
  12. package/dist/docs.json +378 -27
  13. package/dist/esm/definitions.d.ts +206 -7
  14. package/dist/esm/definitions.js.map +1 -1
  15. package/dist/plugin.cjs.js.map +1 -1
  16. package/dist/plugin.js.map +1 -1
  17. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +292 -94
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +156 -10
  20. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +2 -1
  21. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +202 -90
  22. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  23. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +5 -2
  24. package/package.json +7 -3
@@ -95,11 +95,18 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
95
95
  deinit {
96
96
  implementation.shutdown()
97
97
  }
98
- private let pluginVersion: String = "8.52.1"
98
+ private let pluginVersion: String = "8.53.0"
99
99
  private let launchStartedAtMs = Int64(Date().timeIntervalSince1970 * 1000)
100
100
  static let updateUrlDefault = "https://plugin.capgo.app/updates"
101
101
  static let statsUrlDefault = "https://plugin.capgo.app/stats"
102
102
  static let channelUrlDefault = "https://plugin.capgo.app/channel_self"
103
+ // Stats action for a failed update check (offline, timeout, unreadable response, 429 block).
104
+ // Nothing was downloaded, so it is reported apart from download_fail.
105
+ static let updateCheckErrorAction = "update_check_error"
106
+ // Single listener that receives every plugin event as { type, data }.
107
+ static let updaterEvent = "updaterEvent"
108
+ // Deprecated alias emitted next to breakingAvailable; not forwarded to avoid duplicates.
109
+ static let deprecatedMajorAvailableEvent = "majorAvailable"
103
110
  static let autoUpdateModeOff = "off"
104
111
  static let autoUpdateModeBackground = "atBackground"
105
112
  static let autoUpdateModeInstall = "atInstall"
@@ -152,8 +159,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
152
159
  private var autoUpdateMode = CapacitorUpdaterPlugin.autoUpdateModeOff
153
160
  private var launchStartReported = false
154
161
  private var launchReadyReported = false
162
+ private var launchTimeoutReported = false
163
+ private let launchReportLock = NSLock()
155
164
  private var appReadyTimeout = 10000
156
165
  private var appReadyCheck: DispatchWorkItem?
166
+ // Between appMovedToBackground and appMovedToForeground (main thread). A suspended page cannot
167
+ // call notifyAppReady, so the rollback check waits for the fresh one armed by the next foreground.
168
+ private var appInBackground = false
157
169
  private var resetWhenUpdate = true
158
170
  private var directUpdate = false
159
171
  private var directUpdateMode: String = "false"
@@ -226,6 +238,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
226
238
  private var didEnterSemaphoreWaitForTesting = false
227
239
 
228
240
  private var delayUpdateUtils: DelayUpdateUtils!
241
+ private var nativeUpdatePromptCoordinator: NativeUpdatePromptCoordinator?
229
242
 
230
243
  override public func load() {
231
244
  let disableJSLogging = getConfig().getBoolean("disableJSLogging", false)
@@ -245,6 +258,16 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
245
258
  #endif
246
259
 
247
260
  self.semaphoreUp()
261
+ // A silent push or background fetch launches the app straight into the background:
262
+ // no didEnterBackground is posted, so read the state once. Otherwise the notifyAppReady
263
+ // check would roll back a bundle whose page cannot run before the user opens the app.
264
+ if Thread.isMainThread {
265
+ self.appInBackground = UIApplication.shared.applicationState == .background
266
+ } else {
267
+ DispatchQueue.main.sync {
268
+ self.appInBackground = UIApplication.shared.applicationState == .background
269
+ }
270
+ }
248
271
  // Use DeviceIdHelper to get or create device ID that persists across reinstalls
249
272
  self.implementation.deviceID = DeviceIdHelper.getOrCreateDeviceId()
250
273
  persistCustomId = getConfig().getBoolean("persistCustomId", false)
@@ -307,6 +330,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
307
330
  ?? shakeChannelSelectorEnabled
308
331
  }
309
332
  syncShakeMenuGestureRecognizer()
333
+ nativeUpdatePromptCoordinator = NativeUpdatePromptCoordinator(plugin: self)
310
334
  periodCheckDelay = Self.normalizedPeriodCheckDelaySeconds(getConfig().getInt("periodCheckDelay", 0))
311
335
 
312
336
  implementation.setPublicKey(getConfig().getString("publicKey") ?? "")
@@ -411,19 +435,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
411
435
  state?.exists != true || (!defaultChannelPersistenceDisabled && state?.isReadable != true) {
412
436
  _ = self.persistDefaultChannelStateFromDefaults()
413
437
  }
414
- self.reportAppLaunchStart()
415
- self.implementation.autoReset()
416
- let appHealthTracker = AppHealthTracker(implementation: self.implementation)
417
- self.appHealthTracker = appHealthTracker
418
- appHealthTracker.reportPreviousUncleanForegroundExit()
419
- appHealthTracker.startSession()
420
-
421
- // Check if app was recently installed/updated BEFORE cleanup updates the stored native build version.
422
- self.wasRecentlyInstalledOrUpdated = self.checkIfRecentlyInstalledOrUpdated()
423
- if nativeBuildVersionChanged {
424
- self.clearPreviewSessionForNativeBuildChange()
425
- }
426
- self.leavePreviewSessionForLaunchURLIfNeeded()
438
+ let didResetCurrentBundle = self.resetStartupBundleAndReportAppLaunchStart(
439
+ resetWhenUpdate: resetWhenUpdate,
440
+ nativeBuildVersionChanged: nativeBuildVersionChanged
441
+ )
427
442
 
428
443
  // Downloads (including shake-menu / CapgoUpdater entry points) wait on this gate.
429
444
  self.implementation.beforeDownload = { [weak self] in
@@ -431,11 +446,6 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
431
446
  }
432
447
  // Always run async cleanup: delete obsolete bundles on native update (when enabled)
433
448
  // and sweep orphan directories every launch. Must not block app startup.
434
- if !resetWhenUpdate {
435
- UserDefaults.standard.set(self.currentBuildVersion, forKey: "LatestNativeBuildVersion")
436
- UserDefaults.standard.synchronize()
437
- }
438
- let didResetCurrentBundle = resetWhenUpdate ? self.resetCurrentBundleForNativeBuildChangeIfNeeded() : false
439
449
  self.cleanupObsoleteVersions(
440
450
  resetWhenUpdate: resetWhenUpdate,
441
451
  didResetCurrentBundle: didResetCurrentBundle
@@ -459,7 +469,9 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
459
469
  // This handles cases where the app was killed (willTerminateNotification is not reliable for system kills)
460
470
  self.delayUpdateUtils.checkCancelDelay(source: .killed)
461
471
 
462
- self.appMovedToForeground()
472
+ if !self.appInBackground {
473
+ self.appMovedToForeground()
474
+ }
463
475
  self.checkForUpdateAfterDelay()
464
476
  self.showPreviewSessionNoticeIfNeeded()
465
477
  }
@@ -1039,6 +1051,33 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1039
1051
  return true
1040
1052
  }
1041
1053
 
1054
+ @discardableResult
1055
+ private func resetStartupBundleAndReportAppLaunchStart(
1056
+ resetWhenUpdate: Bool,
1057
+ nativeBuildVersionChanged: Bool
1058
+ ) -> Bool {
1059
+ self.implementation.autoReset()
1060
+ let appHealthTracker = AppHealthTracker(implementation: self.implementation)
1061
+ self.appHealthTracker = appHealthTracker
1062
+ appHealthTracker.reportPreviousUncleanForegroundExit()
1063
+ appHealthTracker.startSession()
1064
+
1065
+ // Check if app was recently installed/updated BEFORE cleanup updates the stored native build version.
1066
+ self.wasRecentlyInstalledOrUpdated = self.checkIfRecentlyInstalledOrUpdated()
1067
+ if nativeBuildVersionChanged {
1068
+ self.clearPreviewSessionForNativeBuildChange()
1069
+ }
1070
+ self.leavePreviewSessionForLaunchURLIfNeeded()
1071
+
1072
+ if !resetWhenUpdate {
1073
+ UserDefaults.standard.set(self.currentBuildVersion, forKey: "LatestNativeBuildVersion")
1074
+ UserDefaults.standard.synchronize()
1075
+ }
1076
+ let didResetCurrentBundle = resetWhenUpdate ? self.resetCurrentBundleForNativeBuildChangeIfNeeded() : false
1077
+ self.reportAppLaunchStart()
1078
+ return didResetCurrentBundle
1079
+ }
1080
+
1042
1081
  private func cleanupObsoleteVersions(resetWhenUpdate: Bool = true, didResetCurrentBundle: Bool = false) {
1043
1082
  // Enter before publishing incomplete state so waiters cannot hit an empty group.
1044
1083
  self.cleanupStateLock.lock()
@@ -1239,11 +1278,34 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1239
1278
  call.keepAlive = true
1240
1279
  }
1241
1280
 
1281
+ static func updateCheckErrorMetadata(error: String, statusCode: Int) -> [String: String] {
1282
+ var metadata = ["error": error.isEmpty ? "unknown" : error]
1283
+ if statusCode > 0 {
1284
+ metadata["status_code"] = String(statusCode)
1285
+ }
1286
+ return metadata
1287
+ }
1288
+
1289
+ static func updaterEventPayload(eventName: String, data: [String: Any]?) -> [String: Any] {
1290
+ return ["type": eventName, "data": data ?? [:]]
1291
+ }
1292
+
1293
+ static func shouldForwardToUpdaterEvent(_ eventName: String) -> Bool {
1294
+ return eventName != updaterEvent && eventName != deprecatedMajorAvailableEvent
1295
+ }
1296
+
1242
1297
  /// CAPPlugin's listener storage is not thread-safe (ionic-team/capacitor#8157), so every
1243
1298
  /// event this plugin emits goes through the main thread. Calls already on main stay synchronous.
1244
1299
  private func notifyListenersOnMain(_ eventName: String, data: [String: Any]?, retainUntilConsumed: Bool = false) {
1245
1300
  let notify = {
1246
1301
  self.notifyListeners(eventName, data: data, retainUntilConsumed: retainUntilConsumed)
1302
+ if CapacitorUpdaterPlugin.shouldForwardToUpdaterEvent(eventName) {
1303
+ self.notifyListeners(
1304
+ CapacitorUpdaterPlugin.updaterEvent,
1305
+ data: CapacitorUpdaterPlugin.updaterEventPayload(eventName: eventName, data: data),
1306
+ retainUntilConsumed: retainUntilConsumed
1307
+ )
1308
+ }
1247
1309
  }
1248
1310
 
1249
1311
  if Thread.isMainThread {
@@ -1625,7 +1687,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1625
1687
  if let manifestEntries = manifestEntries {
1626
1688
  next = try self.implementation.downloadManifest(manifest: manifestEntries, version: version, sessionKey: sessionKey)
1627
1689
  } else {
1628
- next = try self.implementation.download(url: url, version: version, sessionKey: sessionKey)
1690
+ next = try self.implementation.downloadVerified(url: url, version: version, sessionKey: sessionKey, expectedChecksum: rawChecksum)
1629
1691
  }
1630
1692
 
1631
1693
  if manifestEntries == nil {
@@ -1905,7 +1967,11 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
1905
1967
  if !res {
1906
1968
  logger.info("Bundle successfully set to: \(id) ")
1907
1969
  call.reject("Update failed, id \(id) doesn't exist")
1908
- } else if self.previewSessionEnabled {
1970
+ return
1971
+ }
1972
+ // The bundle is now active: it must not stay reported as the pending next bundle.
1973
+ self.implementation.clearNextBundleIfCurrent()
1974
+ if self.previewSessionEnabled {
1909
1975
  let bundle = self.implementation.getBundleInfo(id: id)
1910
1976
  _ = self.recordPreviewBundle(bundle)
1911
1977
  if !self.reloadWithoutWaitingForAppReady() {
@@ -2999,8 +3065,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
2999
3065
  logger.error("Error no url or wrong format")
3000
3066
  return "unavailable"
3001
3067
  }
3068
+ // The TS contract only knows queued / already_running / unavailable.
3002
3069
  if self.shouldBlockAutoUpdateForPreviewSession() {
3003
- return "preview_session"
3070
+ return "unavailable"
3071
+ }
3072
+ if !self._isAutoUpdateEnabled() {
3073
+ logger.info("Auto update is disabled, update check not triggered")
3074
+ return "unavailable"
3004
3075
  }
3005
3076
  if self.isDownloadStuckOrTimedOut() {
3006
3077
  logger.info("Download already in progress, skipping duplicate download request")
@@ -3286,11 +3357,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3286
3357
  }
3287
3358
 
3288
3359
  private func reportAppLaunchReady(_ bundle: BundleInfo) {
3289
- guard !self.implementation.statsUrl.isEmpty, !launchReadyReported else {
3360
+ guard !self.implementation.statsUrl.isEmpty, self.claimLaunchReport(timeout: false) else {
3290
3361
  return
3291
3362
  }
3292
3363
 
3293
- launchReadyReported = true
3294
3364
  let duration = max(0, Int64(Date().timeIntervalSince1970 * 1000) - launchStartedAtMs)
3295
3365
  self.implementation.sendStats(
3296
3366
  action: "app_launch_ready",
@@ -3304,8 +3374,23 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3304
3374
  )
3305
3375
  }
3306
3376
 
3377
+ /// The launch outcome is reported once: either ready or timeout, never both, never twice.
3378
+ private func claimLaunchReport(timeout: Bool) -> Bool {
3379
+ launchReportLock.lock()
3380
+ defer { launchReportLock.unlock() }
3381
+ if launchReadyReported || launchTimeoutReported {
3382
+ return false
3383
+ }
3384
+ if timeout {
3385
+ launchTimeoutReported = true
3386
+ } else {
3387
+ launchReadyReported = true
3388
+ }
3389
+ return true
3390
+ }
3391
+
3307
3392
  private func reportAppLaunchTimeout(_ bundle: BundleInfo) {
3308
- guard !self.implementation.statsUrl.isEmpty else {
3393
+ guard !self.implementation.statsUrl.isEmpty, self.claimLaunchReport(timeout: true) else {
3309
3394
  return
3310
3395
  }
3311
3396
 
@@ -3400,7 +3485,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3400
3485
  return
3401
3486
  }
3402
3487
 
3403
- // Handle background conditions with empty value (set to "0")
3488
+ var conditionsPayload: Any = delayConditionList
3404
3489
  if var modifiableList = delayConditionList as? [[String: Any]] {
3405
3490
  for i in 0..<modifiableList.count {
3406
3491
  if let kind = modifiableList[i]["kind"] as? String,
@@ -3410,20 +3495,33 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3410
3495
  modifiableList[i]["value"] = "0"
3411
3496
  }
3412
3497
  }
3413
- let delayConditions: String = toJson(object: modifiableList)
3414
- if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
3415
- call.resolve()
3416
- } else {
3417
- call.reject("Failed to delay update")
3498
+ conditionsPayload = modifiableList
3499
+ }
3500
+
3501
+ let delayConditions: String = toJson(object: conditionsPayload)
3502
+ let previousConditions = UserDefaults.standard.string(
3503
+ forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES
3504
+ ) ?? "[]"
3505
+ let previousMode = delayUpdateUtils.getConditionMode()
3506
+ guard delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) else {
3507
+ if !delayUpdateUtils.setMultiDelay(delayConditions: previousConditions) {
3508
+ logger.error("Failed to restore previous delay conditions after setMultiDelay failure")
3418
3509
  }
3419
- } else {
3420
- let delayConditions: String = toJson(object: delayConditionList)
3421
- if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
3422
- call.resolve()
3423
- } else {
3424
- call.reject("Failed to delay update")
3510
+ call.reject("Failed to delay update")
3511
+ return
3512
+ }
3513
+ let conditionMode = call.getString("conditionMode") ?? DelayUpdateUtils.DELAY_CONDITION_MODE_AND
3514
+ guard delayUpdateUtils.setConditionMode(conditionMode) else {
3515
+ if !delayUpdateUtils.setMultiDelay(delayConditions: previousConditions) {
3516
+ logger.error("Failed to restore previous delay conditions after setConditionMode failure")
3517
+ }
3518
+ if !delayUpdateUtils.setConditionMode(previousMode) {
3519
+ logger.error("Failed to restore previous delay condition mode after setConditionMode failure")
3425
3520
  }
3521
+ call.reject("Failed to delay update")
3522
+ return
3426
3523
  }
3524
+ call.resolve()
3427
3525
  }
3428
3526
 
3429
3527
  // Note: _setMultiDelay and _cancelDelay methods have been moved to DelayUpdateUtils class
@@ -3521,8 +3619,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
3521
3619
  }
3522
3620
 
3523
3621
  func DeferredNotifyAppReadyCheck() {
3524
- self.checkRevert()
3525
3622
  self.appReadyCheck = nil
3623
+ // A suspended app can resume with this timer already expired, before willEnterForeground
3624
+ // re-arms it: its page could not run yet, so wait for the check of the next foreground.
3625
+ if self.appInBackground {
3626
+ logger.info("App is in background, notifyAppReady check deferred to the next foreground")
3627
+ return
3628
+ }
3629
+ self.checkRevert()
3526
3630
  }
3527
3631
 
3528
3632
  func endBackGroundTask() {
@@ -4251,6 +4355,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4251
4355
  self.updateUrl = updateUrl
4252
4356
  }
4253
4357
 
4358
+ func notifyListenersOnMainForTesting(_ eventName: String, data: [String: Any]?, retainUntilConsumed: Bool) {
4359
+ self.notifyListenersOnMain(eventName, data: data, retainUntilConsumed: retainUntilConsumed)
4360
+ }
4361
+
4254
4362
  func downloadBundleForTesting(
4255
4363
  urlString: String,
4256
4364
  version: String,
@@ -4278,10 +4386,28 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4278
4386
  self.currentBuildVersion = currentBuildVersion
4279
4387
  }
4280
4388
 
4389
+ func resetStartupBundleAndReportAppLaunchStartForTesting(
4390
+ resetWhenUpdate: Bool,
4391
+ nativeBuildVersionChanged: Bool
4392
+ ) -> Bool {
4393
+ self.resetStartupBundleAndReportAppLaunchStart(
4394
+ resetWhenUpdate: resetWhenUpdate,
4395
+ nativeBuildVersionChanged: nativeBuildVersionChanged
4396
+ )
4397
+ }
4398
+
4399
+ func reportAppLaunchStartForTesting() {
4400
+ self.reportAppLaunchStart()
4401
+ }
4402
+
4281
4403
  func setAppReadyTimeoutForTesting(_ timeout: Int) {
4282
4404
  self.appReadyTimeout = timeout
4283
4405
  }
4284
4406
 
4407
+ func setDelayUpdateUtilsForTesting(_ delayUpdateUtils: DelayUpdateUtils) {
4408
+ self.delayUpdateUtils = delayUpdateUtils
4409
+ }
4410
+
4285
4411
  func armPendingNotifyAppReadyForTesting() {
4286
4412
  pendingNotifyAppReady = true
4287
4413
  }
@@ -4324,11 +4450,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4324
4450
  }
4325
4451
 
4326
4452
  private func shouldNotifyBreakingEvents(response: AppVersion) -> Bool {
4327
- if response.breaking == true {
4328
- return true
4329
- }
4330
-
4331
- return response.error == "disable_auto_update_to_major" || response.message == "store_update_required"
4453
+ NativeUpdatePromptCoordinator.isNativeStoreUpdateBlock(response: response)
4332
4454
  }
4333
4455
 
4334
4456
  private func notifyBreakingEventsIfNeeded(response: AppVersion, version: String) {
@@ -4336,6 +4458,51 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4336
4458
  let eventVersion = version.isEmpty ? self.implementation.getCurrentBundle().getVersionName() : version
4337
4459
  self.notifyBreakingEvents(version: eventVersion)
4338
4460
  }
4461
+ self.nativeUpdatePromptCoordinator?.maybeShowForUpdateBlock(response: response)
4462
+ }
4463
+
4464
+ func currentBuildVersionForNativeUpdatePrompt() -> String {
4465
+ currentBuildVersion
4466
+ }
4467
+
4468
+ func openAppStoreFromNativeUpdatePrompt() {
4469
+ let bundleId = implementation.appId
4470
+ let lookupUrl = "https://itunes.apple.com/lookup?bundleId=\(bundleId)"
4471
+ DispatchQueue.global(qos: .background).async {
4472
+ guard let url = URL(string: lookupUrl) else {
4473
+ self.logger.error("Invalid App Store lookup URL from native update prompt")
4474
+ return
4475
+ }
4476
+
4477
+ let task = URLSession.shared.dataTask(with: url) { data, _, error in
4478
+ if let error = error {
4479
+ self.logger.error("App Store lookup from native update prompt failed: \(error.localizedDescription)")
4480
+ return
4481
+ }
4482
+
4483
+ guard let data = data,
4484
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
4485
+ let results = json["results"] as? [[String: Any]],
4486
+ let appInfo = results.first,
4487
+ let trackId = appInfo["trackId"] as? Int else {
4488
+ self.logger.error("App Store lookup from native update prompt did not return a trackId for bundleId \(bundleId)")
4489
+ return
4490
+ }
4491
+
4492
+ self.openAppStorePageFromNativeUpdatePrompt(urlString: "https://apps.apple.com/app/id\(trackId)")
4493
+ }
4494
+ task.resume()
4495
+ }
4496
+ }
4497
+
4498
+ private func openAppStorePageFromNativeUpdatePrompt(urlString: String) {
4499
+ guard let url = URL(string: urlString) else {
4500
+ logger.error("Invalid App Store URL from native update prompt")
4501
+ return
4502
+ }
4503
+ DispatchQueue.main.async {
4504
+ UIApplication.shared.open(url, options: [:], completionHandler: nil)
4505
+ }
4339
4506
  }
4340
4507
 
4341
4508
  static func normalizedUpdateResponseKind(kind: String?) -> String {
@@ -4349,13 +4516,13 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4349
4516
  Self.normalizedUpdateResponseKind(kind: kind)
4350
4517
  }
4351
4518
 
4352
- private func endBackgroundDownloadAfterLatestError(
4519
+ /// Emits `updateCheckResult` for an error / kind response and logs it.
4520
+ @discardableResult
4521
+ private func notifyUpdateCheckResult(
4353
4522
  backendError: String,
4354
4523
  res: AppVersion,
4355
- current: BundleInfo,
4356
- plannedDirectUpdate: Bool
4357
- ) {
4358
- let statusCode = res.statusCode
4524
+ current: BundleInfo
4525
+ ) -> (kind: String, message: String, latestVersionName: String) {
4359
4526
  let responseKind = self.updateResponseKind(kind: res.kind)
4360
4527
  let responseMessage = res.message?.isEmpty == false ? res.message : nil
4361
4528
  let message = responseMessage ?? (backendError.isEmpty ? "server did not provide a message" : backendError)
@@ -4364,11 +4531,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4364
4531
  "kind": responseKind,
4365
4532
  "error": backendError,
4366
4533
  "message": message,
4367
- "statusCode": statusCode,
4534
+ "statusCode": res.statusCode,
4368
4535
  "version": latestVersionName,
4369
4536
  "bundle": current.toJSON()
4370
4537
  ])
4371
- self.notifyBreakingEventsIfNeeded(response: res, version: res.version)
4372
4538
 
4373
4539
  if responseKind == "up_to_date" {
4374
4540
  self.logger.info("No new version available")
@@ -4377,15 +4543,39 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4377
4543
  } else {
4378
4544
  self.logger.error("getLatest failed with error: \(backendError)")
4379
4545
  }
4546
+ return (responseKind, message, latestVersionName)
4547
+ }
4548
+
4549
+ private func endBackgroundDownloadAfterLatestError(
4550
+ backendError: String,
4551
+ res: AppVersion,
4552
+ current: BundleInfo,
4553
+ plannedDirectUpdate: Bool
4554
+ ) {
4555
+ let (responseKind, message, latestVersionName) = self.notifyUpdateCheckResult(
4556
+ backendError: backendError,
4557
+ res: res,
4558
+ current: current
4559
+ )
4560
+ self.notifyBreakingEventsIfNeeded(response: res, version: res.version)
4380
4561
 
4381
4562
  let isFailure = responseKind == "failed"
4563
+ if isFailure {
4564
+ // The check itself failed: nothing was downloaded, so report it apart from download_fail.
4565
+ self.implementation.sendStats(
4566
+ action: CapacitorUpdaterPlugin.updateCheckErrorAction,
4567
+ versionName: current.getVersionName(),
4568
+ oldVersionName: "",
4569
+ metadata: CapacitorUpdaterPlugin.updateCheckErrorMetadata(error: backendError, statusCode: res.statusCode)
4570
+ )
4571
+ }
4382
4572
  self.endBackGroundTaskWithNotif(
4383
4573
  msg: message,
4384
4574
  latestVersionName: latestVersionName,
4385
4575
  current: current,
4386
4576
  error: isFailure,
4387
4577
  plannedDirectUpdate: plannedDirectUpdate,
4388
- sendStats: isFailure
4578
+ sendStats: false
4389
4579
  )
4390
4580
  }
4391
4581
 
@@ -4458,7 +4648,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4458
4648
  DispatchQueue.global(qos: .userInitiated).async(execute: work)
4459
4649
  }
4460
4650
 
4461
- private func beginDownloadBackgroundTask() {
4651
+ func beginDownloadBackgroundTask() {
4462
4652
  let registerTask = {
4463
4653
  self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Finish Download Tasks") {
4464
4654
  self.endBackGroundTask()
@@ -4641,7 +4831,14 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4641
4831
  )
4642
4832
  return
4643
4833
  }
4644
- nextImpl = try self.implementation.download(url: downloadUrl, version: latestVersionName, sessionKey: sessionKey, link: res.link, comment: res.comment)
4834
+ nextImpl = try self.implementation.downloadVerified(
4835
+ url: downloadUrl,
4836
+ version: latestVersionName,
4837
+ sessionKey: sessionKey,
4838
+ expectedChecksum: res.checksum,
4839
+ link: res.link,
4840
+ comment: res.comment
4841
+ )
4645
4842
  }
4646
4843
  }
4647
4844
  guard let next = nextImpl else {
@@ -4698,11 +4895,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4698
4895
  let directUpdateAllowed = plannedDirectUpdate && !self.autoSplashscreenTimedOut
4699
4896
  if directUpdateAllowed {
4700
4897
  let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
4701
- let delayConditionList: [DelayCondition] = self.fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
4702
- let kind: String = obj.value(forKey: "kind") as! String
4703
- let value: String? = obj.value(forKey: "value") as? String
4704
- return DelayCondition(kind: kind, value: value)
4705
- }
4898
+ let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
4706
4899
  if !delayConditionList.isEmpty {
4707
4900
  self.logger.info("Update delayed until delay conditions met")
4708
4901
  self.endBackGroundTaskWithNotif(
@@ -4778,7 +4971,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4778
4971
  self.logger.error("Error downloading file \(error.localizedDescription)")
4779
4972
  let current: BundleInfo = self.implementation.getCurrentBundle()
4780
4973
  self.endBackGroundTaskWithNotif(
4781
- msg: "Error downloading file",
4974
+ msg: (error as? ObjectSavableError) == .checksum ? "Error checksum" : "Error downloading file",
4782
4975
  latestVersionName: latestVersionName,
4783
4976
  current: current,
4784
4977
  plannedDirectUpdate: plannedDirectUpdate
@@ -4804,11 +4997,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4804
4997
  return
4805
4998
  }
4806
4999
  let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
4807
- let delayConditionList: [DelayCondition] = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
4808
- let kind: String = obj.value(forKey: "kind") as! String
4809
- let value: String? = obj.value(forKey: "value") as? String
4810
- return DelayCondition(kind: kind, value: value)
4811
- }
5000
+ let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
4812
5001
  if !delayConditionList.isEmpty {
4813
5002
  logger.info("Update delayed until delay conditions met")
4814
5003
  return
@@ -4835,18 +5024,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4835
5024
  return String(data: data, encoding: String.Encoding.utf8) ?? ""
4836
5025
  }
4837
5026
 
4838
- @objc private func fromJsonArr(json: String) -> [NSObject] {
4839
- guard let jsonData = json.data(using: .utf8) else {
4840
- return []
4841
- }
4842
- let object = try? JSONSerialization.jsonObject(
4843
- with: jsonData,
4844
- options: .mutableContainers
4845
- ) as? [NSObject]
4846
- return object ?? []
4847
- }
4848
-
4849
5027
  @objc func appMovedToForeground() {
5028
+ self.appInBackground = false
4850
5029
  appHealthTracker?.markForeground(true)
4851
5030
  let current: BundleInfo = self.implementation.getCurrentBundle()
4852
5031
  self.implementation.sendStats(action: "app_moved_to_foreground", versionName: current.getVersionName())
@@ -4894,30 +5073,43 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4894
5073
  return
4895
5074
  }
4896
5075
  DispatchQueue.global(qos: .utility).async {
4897
- if self.shouldBlockAutoUpdateForPreviewSession() {
4898
- return
4899
- }
4900
- let res = self.implementation.getLatest(url: url, channel: nil)
4901
- let current = self.implementation.getCurrentBundle()
4902
- if self.shouldBlockAutoUpdateForPreviewSession() {
4903
- return
4904
- }
4905
-
4906
- if res.version != current.getVersionName() {
4907
- self.logger.info("New version found: \(res.version)")
4908
- // Check if download is already in progress (with timeout protection)
4909
- if !self.isDownloadStuckOrTimedOut() {
4910
- self.backgroundDownload()
4911
- } else {
4912
- self.logger.info("Download already in progress, skipping duplicate download request")
4913
- }
4914
- }
5076
+ self.runPeriodicUpdateCheck(url: url)
4915
5077
  }
4916
5078
  }
4917
5079
  RunLoop.current.add(periodicUpdateTimer!, forMode: .default)
4918
5080
  }
4919
5081
 
5082
+ func runPeriodicUpdateCheck(url: URL) {
5083
+ if self.shouldBlockAutoUpdateForPreviewSession() {
5084
+ return
5085
+ }
5086
+ let res = self.implementation.getLatest(url: url, channel: nil)
5087
+ let current = self.implementation.getCurrentBundle()
5088
+ if self.shouldBlockAutoUpdateForPreviewSession() {
5089
+ return
5090
+ }
5091
+
5092
+ // Error / kind responses carry no downloadable bundle: report them, like Android.
5093
+ let backendError = res.error ?? ""
5094
+ let backendKind = res.kind ?? ""
5095
+ if !backendError.isEmpty || !backendKind.isEmpty {
5096
+ self.notifyUpdateCheckResult(backendError: backendError, res: res, current: current)
5097
+ return
5098
+ }
5099
+
5100
+ if !res.version.isEmpty && res.version != current.getVersionName() {
5101
+ self.logger.info("New version found: \(res.version)")
5102
+ // Check if download is already in progress (with timeout protection)
5103
+ if !self.isDownloadStuckOrTimedOut() {
5104
+ self.backgroundDownload()
5105
+ } else {
5106
+ self.logger.info("Download already in progress, skipping duplicate download request")
5107
+ }
5108
+ }
5109
+ }
5110
+
4920
5111
  @objc func appMovedToBackground() {
5112
+ self.appInBackground = true
4921
5113
  // Reset timeout flag at start of each background cycle
4922
5114
  self.autoSplashscreenTimedOut = false
4923
5115
  appHealthTracker?.markForeground(false)
@@ -4958,6 +5150,8 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
4958
5150
  }
4959
5151
 
4960
5152
  @objc func getNextBundle(_ call: CAPPluginCall) {
5153
+ // Heals a next bundle left stored after it was activated (set() did not clear it before).
5154
+ self.implementation.clearNextBundleIfCurrent()
4961
5155
  let bundle = self.implementation.getNextBundle()
4962
5156
  if bundle == nil || bundle?.isUnknown() == true {
4963
5157
  call.resolve()
@@ -5137,6 +5331,10 @@ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
5137
5331
  }
5138
5332
 
5139
5333
  self.resolveCall(call, data: result)
5334
+ if let availability = result["updateAvailability"] as? Int,
5335
+ availability == AppUpdateAvailability.updateAvailable.rawValue {
5336
+ self.nativeUpdatePromptCoordinator?.maybeShowForStoreUpdateAvailable()
5337
+ }
5140
5338
  } catch {
5141
5339
  self.logger.error("Failed to parse App Store response: \(error.localizedDescription)")
5142
5340
  self.rejectCall(call, message: "Failed to parse App Store response: \(error.localizedDescription)")