@capgo/capacitor-updater 9.0.0 → 9.0.2

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 +2406 -291
  4. package/android/build.gradle +37 -17
  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 +7927 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5785 -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 +2041 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +301 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +569 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +436 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +604 -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 +963 -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 +2641 -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 +6813 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +200 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +5099 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +387 -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 +876 -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 +6533 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +156 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +314 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +653 -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 +1109 -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 +196 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +470 -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,569 @@
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
+ package ee.forgr.capacitor_updater;
8
+
9
+ import android.app.Activity;
10
+ import android.content.Context;
11
+ import android.content.SharedPreferences;
12
+ import android.content.pm.PackageInfo;
13
+ import android.content.pm.PackageManager;
14
+ import android.os.Build;
15
+ import androidx.annotation.NonNull;
16
+ import androidx.core.content.pm.PackageInfoCompat;
17
+ import androidx.work.Constraints;
18
+ import androidx.work.ExistingWorkPolicy;
19
+ import androidx.work.NetworkType;
20
+ import androidx.work.OneTimeWorkRequest;
21
+ import androidx.work.OutOfQuotaPolicy;
22
+ import androidx.work.WorkManager;
23
+ import androidx.work.Worker;
24
+ import androidx.work.WorkerParameters;
25
+ import com.getcapacitor.CapConfig;
26
+ import com.getcapacitor.PluginConfig;
27
+ import com.getcapacitor.plugin.WebView;
28
+ import java.io.IOException;
29
+ import java.util.Map;
30
+ import java.util.concurrent.CountDownLatch;
31
+ import java.util.concurrent.TimeUnit;
32
+ import java.util.concurrent.atomic.AtomicReference;
33
+ import org.json.JSONArray;
34
+ import org.json.JSONException;
35
+
36
+ /**
37
+ * Runs a live update check with no Activity and no Capacitor bridge, for example when an
38
+ * update-check push wakes a killed app. The bundle is downloaded and, when the app has no UI,
39
+ * applied as the current bundle so the next launch opens the new version (it still has to call
40
+ * notifyAppReady). Enqueued as unique expedited work so the process stays alive until the bundle
41
+ * is unzipped and stored.
42
+ *
43
+ * When a plugin instance is running in the process, use its native trigger instead
44
+ * (CapacitorUpdaterPlugin#triggerBackgroundUpdateCheck); this worker then only stores the bundle as
45
+ * next and lets that instance install it.
46
+ */
47
+ public class HeadlessUpdateWorker extends Worker {
48
+
49
+ static final String UNIQUE_WORK_NAME = "capacitor_updater_headless_update_check";
50
+ private static final long FINISH_TIMEOUT_MINUTES = 9;
51
+
52
+ public HeadlessUpdateWorker(@NonNull final Context context, @NonNull final WorkerParameters params) {
53
+ super(context, params);
54
+ }
55
+
56
+ /** Queue a headless update check. Safe to call from any thread, including an FCM service. */
57
+ public static void enqueue(@NonNull final Context context) {
58
+ final OneTimeWorkRequest.Builder builder = new OneTimeWorkRequest.Builder(HeadlessUpdateWorker.class)
59
+ .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
60
+ .addTag(UNIQUE_WORK_NAME);
61
+ // Same as downloads: expedited work starts right away on Android 12+ without a foreground service.
62
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
63
+ builder.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST);
64
+ }
65
+ WorkManager.getInstance(context.getApplicationContext()).enqueueUniqueWork(
66
+ UNIQUE_WORK_NAME,
67
+ ExistingWorkPolicy.KEEP,
68
+ builder.build()
69
+ );
70
+ }
71
+
72
+ @NonNull
73
+ @Override
74
+ public Result doWork() {
75
+ final Context context = getApplicationContext();
76
+ final Logger logger;
77
+ try {
78
+ final PluginConfig config = CapConfig.loadDefault(context).getPluginConfiguration("CapacitorUpdater");
79
+ final boolean osLogging = config.getBoolean("osLogging", true);
80
+ logger = new Logger("CapgoUpdater", new Logger.Options(osLogging));
81
+ try {
82
+ final String status = run(context, logger);
83
+ logger.info("Headless update check finished: " + status);
84
+ } catch (final Exception e) {
85
+ logger.error("Headless update check failed: " + e.getMessage());
86
+ }
87
+ } catch (final Exception e) {
88
+ final Logger fallback = new Logger("CapgoUpdater", new Logger.Options(true));
89
+ fallback.error("Headless update check skipped: invalid Capacitor config (" + e.getMessage() + ")");
90
+ }
91
+ // Never retry: the next launch or push runs a fresh check.
92
+ return Result.success();
93
+ }
94
+
95
+ static String run(final Context context, final Logger logger) throws PackageManager.NameNotFoundException {
96
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
97
+ // The running plugin instance owns downloads and installs in this process.
98
+ return "handed_over";
99
+ }
100
+ final CapConfig capConfig = CapConfig.loadDefault(context);
101
+ final PluginConfig config = capConfig.getPluginConfiguration("CapacitorUpdater");
102
+ final String serverUrl = capConfig.getServerUrl();
103
+ if (serverUrl != null && !serverUrl.isEmpty()) {
104
+ return "unavailable";
105
+ }
106
+ final String autoUpdateMode = CapacitorUpdaterPlugin.autoUpdateModeFromConfig(config, logger);
107
+ if (!CapacitorUpdaterPlugin.isAutoUpdateModeEnabled(autoUpdateMode)) {
108
+ return "unavailable";
109
+ }
110
+
111
+ final SharedPreferences prefs = context.getSharedPreferences(WebView.WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE);
112
+ final boolean allowPreview = config.getBoolean("allowPreview", false);
113
+ if (allowPreview && prefs.getBoolean(CapacitorUpdaterPlugin.PREVIEW_SESSION_PREF_KEY, false)) {
114
+ return "preview_session";
115
+ }
116
+
117
+ final PackageInfo packageInfo = getPackageInfo(context);
118
+ final String versionCode = Long.toString(PackageInfoCompat.getLongVersionCode(packageInfo));
119
+ // After a native update the launch resets bundles first (resetWhenUpdate): leave it to the launch.
120
+ if (nativeBuildChanged(prefs, versionCode)) {
121
+ return "native_update_pending";
122
+ }
123
+
124
+ final boolean setNext = CapacitorUpdaterPlugin.shouldAutoUpdateModeSetNextBundle(autoUpdateMode);
125
+ final CountDownLatch finished = new CountDownLatch(1);
126
+ final AtomicReference<String> result = new AtomicReference<>("no_update");
127
+ final CapgoUpdater updater = new CapgoUpdater(logger) {
128
+ @Override
129
+ void nextBundleReady(final BundleInfo bundle) {
130
+ result.set(applyIfNoUi(this, bundle, logger) ? "installed" : "queued");
131
+ finished.countDown();
132
+ }
133
+
134
+ @Override
135
+ void notifyListeners(final String id, final Map<String, Object> res) {
136
+ if ("downloadFailed".equals(id)) {
137
+ result.set("failed");
138
+ finished.countDown();
139
+ } else if ("updateAvailable".equals(id) && !setNext) {
140
+ result.set("downloaded");
141
+ finished.countDown();
142
+ }
143
+ }
144
+ };
145
+ configure(updater, context, config, prefs, packageInfo, versionCode, logger);
146
+ try {
147
+ String updateUrl = config.getString("updateUrl", CapacitorUpdaterPlugin.updateUrlDefault);
148
+ if (config.getBoolean("persistModifyUrl", false) && prefs.contains(CapacitorUpdaterPlugin.UPDATE_URL_PREF_KEY)) {
149
+ updateUrl = prefs.getString(CapacitorUpdaterPlugin.UPDATE_URL_PREF_KEY, updateUrl);
150
+ }
151
+ if (updateUrl == null || updateUrl.isEmpty()) {
152
+ return "unavailable";
153
+ }
154
+
155
+ final AtomicReference<Map<String, Object>> latestRef = new AtomicReference<>();
156
+ final CountDownLatch latestDone = new CountDownLatch(1);
157
+ updater.getLatest(updateUrl, null, (res) -> {
158
+ latestRef.set(res);
159
+ latestDone.countDown();
160
+ });
161
+ try {
162
+ if (!latestDone.await(updater.timeout + 5000L, TimeUnit.MILLISECONDS)) {
163
+ return "failed";
164
+ }
165
+ } catch (final InterruptedException e) {
166
+ Thread.currentThread().interrupt();
167
+ return "failed";
168
+ }
169
+ final Map<String, Object> latest = latestRef.get();
170
+ if (latest == null || latest.containsKey("error") || latest.containsKey("kind")) {
171
+ return "no_update";
172
+ }
173
+ final String version = String.valueOf(latest.get("version"));
174
+ final Object url = latest.get("url");
175
+ final BundleInfo current = updater.getCurrentBundle();
176
+ if ("builtin".equals(version) || version.isEmpty() || version.equals(current.getVersionName()) || !(url instanceof String)) {
177
+ return "no_update";
178
+ }
179
+ final String sessionKey = latest.get("sessionKey") instanceof String ? (String) latest.get("sessionKey") : "";
180
+ final String checksum = latest.get("checksum") instanceof String ? (String) latest.get("checksum") : "";
181
+
182
+ BundleInfo existing = updater.getBundleInfoByName(version);
183
+ if (existing == null) {
184
+ existing = updater.findRegistryBundleByVersionName(version);
185
+ }
186
+ boolean retryDownloadSlot = false;
187
+ final BundleInfo next = updater.getNextBundle();
188
+ final boolean isQueuedNext = existing != null && next != null && existing.getId().equals(next.getId());
189
+ final boolean isCurrent =
190
+ existing != null &&
191
+ existing.getId().equals(current.getId()) &&
192
+ BundleStatus.SUCCESS == current.getStatus() &&
193
+ version.equals(current.getVersionName());
194
+ if (existing != null) {
195
+ final boolean interrupted = updater.isInterruptedDownloadBundle(existing.getId());
196
+ final int retryCount = updater.incompleteDownloadRetryCount(version);
197
+ final boolean integrityBlocked = updater.isIntegrityBlockedVersion(version);
198
+ final boolean bundleOnDisk = updater.isBundleOnDisk(existing.getId());
199
+ if (
200
+ existing.isErrorStatus() &&
201
+ !CapgoUpdater.shouldRetryDownloadForExistingBundle(
202
+ existing,
203
+ bundleOnDisk,
204
+ retryCount,
205
+ integrityBlocked,
206
+ interrupted,
207
+ isCurrent,
208
+ isQueuedNext
209
+ )
210
+ ) {
211
+ return "failed";
212
+ }
213
+ final boolean replaceExisting = CapgoUpdater.shouldRetryDownloadForExistingBundle(
214
+ existing,
215
+ bundleOnDisk,
216
+ retryCount,
217
+ integrityBlocked,
218
+ interrupted,
219
+ isCurrent,
220
+ isQueuedNext
221
+ );
222
+ // A finished worker whose bundle is still being finalized owns this row too: deleting it now would
223
+ // cancel the finalization and discard a completed transfer.
224
+ final boolean versionDownloadActive = hasLiveDownloadOwner(updater, version, existing.getId());
225
+ if (replaceExisting && BundleStatus.DOWNLOADING != existing.getStatus() && versionDownloadActive) {
226
+ // Another live attempt (e.g. a manual download()) owns this version: deleting the older row
227
+ // would cancel its work by version. Defer to it.
228
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
229
+ updater.handOverPendingStats();
230
+ return "handed_over";
231
+ }
232
+ return "skipped";
233
+ }
234
+ if (replaceExisting && !(BundleStatus.DOWNLOADING == existing.getStatus() && versionDownloadActive)) {
235
+ // An ordinary deletion tombstone (a retired bundle) carries no retry history: removing it is
236
+ // cleanup, and the next transfer is a first download. Anything else is a charged retry.
237
+ final boolean retryHistory =
238
+ !(existing.isDeleted() || existing.isDeleting()) ||
239
+ interrupted ||
240
+ retryCount > 0 ||
241
+ integrityBlocked ||
242
+ updater.hasIncompleteDownloadRetryReservation(version);
243
+ retryDownloadSlot = retryHistory;
244
+ if (isQueuedNext) {
245
+ updater.clearNextBundleIfMatches(existing.getId());
246
+ }
247
+ if (retryHistory) {
248
+ // Persist the retry before deleting the record that proves it (survives process death).
249
+ updater.reserveIncompleteDownloadRetry(version);
250
+ }
251
+ boolean deleted = false;
252
+ try {
253
+ deleted = Boolean.TRUE.equals(updater.delete(existing.getId(), true));
254
+ } catch (final IOException e) {
255
+ logger.error("Failed to delete incomplete bundle: " + version + " " + e.getMessage());
256
+ }
257
+ if (!deleted) {
258
+ // A pending deletion of the old record can cancel same-version work when it resumes;
259
+ // do not start a replacement until it is gone (the reservation keeps the retry charged).
260
+ logger.error("Incomplete bundle still pending deletion, skipping replacement: " + version);
261
+ return "skipped";
262
+ }
263
+ final String deletedId = existing.getId();
264
+ existing = updater.getBundleInfoByName(version);
265
+ if (existing == null) {
266
+ existing = updater.findRegistryBundleByVersionName(version);
267
+ }
268
+ if (existing != null && !deletedId.equals(existing.getId()) && existing.isErrorStatus()) {
269
+ // Another failed row of this version surfaced: run the eligibility decision again for it.
270
+ final boolean refreshedEligible = CapgoUpdater.shouldRetryDownloadForExistingBundle(
271
+ existing,
272
+ updater.isBundleOnDisk(existing.getId()),
273
+ updater.incompleteDownloadRetryCount(version),
274
+ updater.isIntegrityBlockedVersion(version),
275
+ updater.isInterruptedDownloadBundle(existing.getId()),
276
+ false,
277
+ next != null && existing.getId().equals(next.getId())
278
+ );
279
+ // Eligible rows are replaced by the next check (the reservation keeps that retry charged).
280
+ return refreshedEligible ? "skipped" : "failed";
281
+ }
282
+ }
283
+ }
284
+ if (existing != null && BundleStatus.DOWNLOADING == existing.getStatus()) {
285
+ final int retryCount = updater.incompleteDownloadRetryCount(version);
286
+ final boolean interrupted = updater.isInterruptedDownloadBundle(existing.getId());
287
+ final boolean integrityBlocked = updater.isIntegrityBlockedVersion(version);
288
+ final boolean bundleOnDisk = updater.isBundleOnDisk(existing.getId());
289
+ if (
290
+ !CapgoUpdater.shouldRetryDownloadForExistingBundle(
291
+ existing,
292
+ bundleOnDisk,
293
+ retryCount,
294
+ integrityBlocked,
295
+ interrupted,
296
+ isCurrent,
297
+ isQueuedNext
298
+ )
299
+ ) {
300
+ return "failed";
301
+ }
302
+ if (hasLiveDownloadOwner(updater, version, existing.getId())) {
303
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
304
+ updater.handOverPendingStats();
305
+ return "handed_over";
306
+ }
307
+ return "skipped";
308
+ }
309
+ // The owner may have finished between the checks: reread so a finalized PENDING bundle is reused.
310
+ final BundleInfo reread = updater.getBundleInfo(existing.getId());
311
+ if (reread != null && BundleStatus.DOWNLOADING != reread.getStatus()) {
312
+ existing = reread;
313
+ }
314
+ // The stale DOWNLOADING row's owner has ended: what follows replaces that attempt, so charge it.
315
+ retryDownloadSlot = true;
316
+ }
317
+ final String reused = reuseDownloadedBundle(updater, existing, version, setNext, logger);
318
+ if (reused != null) {
319
+ return reused;
320
+ }
321
+
322
+ if (existing != null && existing.isDeleting()) {
323
+ // The old row's deletion has not finished: when it resumes it cancels same-version work, so do
324
+ // not start (or charge) a replacement yet. Any reservation keeps the retry charged.
325
+ logger.info("Bundle still pending deletion, skipping replacement: " + version);
326
+ return "skipped";
327
+ }
328
+ // downloadBackground returns null when it refuses the download (blocked encryption, gate,
329
+ // version already downloading): only wait for a download it started.
330
+ if (updater.incompleteDownloadRetryCount(version) >= CapgoUpdater.MAX_INCOMPLETE_DOWNLOAD_RETRIES) {
331
+ return "failed";
332
+ }
333
+ if (updater.incompleteDownloadRetryCount(version) > 0 || updater.isIntegrityBlockedVersion(version)) {
334
+ retryDownloadSlot = true;
335
+ }
336
+ final JSONArray manifest = manifestOf(latest);
337
+ if (
338
+ manifest == null &&
339
+ (retryDownloadSlot || updater.hasIncompleteDownloadRetryReservation(version)) &&
340
+ !updater.hasDiskSpaceForZipDownload()
341
+ ) {
342
+ // The ZIP worker would refuse before any request: do not spend a retry slot on it.
343
+ updater.sendStats("insufficient_disk_space", version);
344
+ return "failed";
345
+ }
346
+ final int retryCharge = updater.chargeIncompleteDownloadRetry(version, retryDownloadSlot);
347
+ if (retryCharge == CapgoUpdater.RETRY_REFUSED) {
348
+ return "failed";
349
+ }
350
+ final boolean retryCharged = retryCharge == CapgoUpdater.RETRY_CHARGED;
351
+ final String startedId;
352
+ try {
353
+ startedId = updater.downloadBackground((String) url, version, sessionKey, checksum, manifest, setNext);
354
+ } catch (final RuntimeException e) {
355
+ updater.settleIncompleteDownloadRetry(version, retryCharged, false, false);
356
+ throw e;
357
+ }
358
+ updater.settleIncompleteDownloadRetry(version, retryCharged, startedId != null, false);
359
+ if (startedId == null) {
360
+ return "skipped";
361
+ }
362
+ final long deadline = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(FINISH_TIMEOUT_MINUTES);
363
+ try {
364
+ // Keep the worker (and so the process) alive until the bundle is stored. If the user opens
365
+ // the app meanwhile, its plugin instance takes over the download (it restarts downloads it
366
+ // does not observe), so stop waiting.
367
+ while (!finished.await(1, TimeUnit.SECONDS)) {
368
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
369
+ return "handed_over";
370
+ }
371
+ if (System.currentTimeMillis() > deadline) {
372
+ return "timeout";
373
+ }
374
+ }
375
+ } catch (final InterruptedException e) {
376
+ Thread.currentThread().interrupt();
377
+ return "interrupted";
378
+ }
379
+ return result.get();
380
+ } finally {
381
+ // Once the plugin instance is up it owns the stats file: hand it our unsent events
382
+ // instead of overwriting its newer file.
383
+ synchronized (CapacitorUpdaterPlugin.INSTANCE_LOADED_LOCK) {
384
+ if (CapacitorUpdaterPlugin.instanceLoaded) {
385
+ updater.handOverPendingStats();
386
+ updater.shutdown(false);
387
+ } else {
388
+ updater.shutdown(true);
389
+ }
390
+ }
391
+ }
392
+ }
393
+
394
+ /**
395
+ * Whether a live owner will finish the version's download: a pending finalization, work observed by this
396
+ * process, or (with a plugin instance loaded) persisted work the plugin owns or restarts itself. Persisted
397
+ * WorkManager work that nothing in this process observes was left by a killed process: nobody would verify,
398
+ * extract or queue its result, so the headless check recovers it (downloadBackground restarts orphaned work).
399
+ */
400
+ static boolean hasLiveDownloadOwner(final CapgoUpdater updater, final String version, final String bundleId) {
401
+ if (updater.hasPendingDownloadFinalizationForBundleId(bundleId)) {
402
+ return true;
403
+ }
404
+ if (!updater.isVersionDownloadActive(version)) {
405
+ return false;
406
+ }
407
+ return CapacitorUpdaterPlugin.isInstanceLoaded() || updater.isVersionDownloadObservedInThisProcess(version);
408
+ }
409
+
410
+ /**
411
+ * With no plugin instance (no bridge, no WebView) nothing shows the current bundle, so switching
412
+ * it is the same as installing on a background transition. Delay conditions keep it as next.
413
+ */
414
+ static boolean applyIfNoUi(final CapgoUpdater updater, final BundleInfo bundle, final Logger logger) {
415
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
416
+ return false;
417
+ }
418
+ final String delays = updater.prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]");
419
+ if (delays != null && !"[]".equals(delays.trim())) {
420
+ logger.info("Update delayed until delay conditions met");
421
+ return false;
422
+ }
423
+ if (updater.set(bundle)) {
424
+ updater.setNextBundle(null);
425
+ logger.info("Installed bundle " + bundle.getVersionName() + " for the next launch");
426
+ return true;
427
+ }
428
+ return false;
429
+ }
430
+
431
+ /**
432
+ * When builtinMinimum is on, refuse an existing downloaded bundle whose version is below the native build.
433
+ * Shared by tests and {@link #run} so removing the guard breaks a unit test.
434
+ */
435
+ static boolean builtinMinimumBlocksExistingBundle(final CapgoUpdater updater, final String bundleVersion, final Logger logger) {
436
+ try {
437
+ updater.requireVersionNotBelowBuiltin(bundleVersion);
438
+ return false;
439
+ } catch (final IOException e) {
440
+ logger.error(e.getMessage() == null ? "Download blocked" : e.getMessage());
441
+ return true;
442
+ }
443
+ }
444
+
445
+ static JSONArray manifestOf(final Map<String, Object> latest) {
446
+ final Object manifest = latest.get("manifest");
447
+ if (manifest instanceof JSONArray) {
448
+ return (JSONArray) manifest;
449
+ }
450
+ if (manifest instanceof String) {
451
+ try {
452
+ return new JSONArray((String) manifest);
453
+ } catch (final JSONException e) {
454
+ return null;
455
+ }
456
+ }
457
+ return null;
458
+ }
459
+
460
+ static boolean nativeBuildChanged(final SharedPreferences prefs, final String versionCode) {
461
+ String previous = prefs.getString("LatestNativeBuildVersion", "");
462
+ if (previous == null || previous.isEmpty()) {
463
+ previous = prefs.getString("LatestVersionNative", "");
464
+ }
465
+ return previous != null && !previous.isEmpty() && !previous.equals(versionCode);
466
+ }
467
+
468
+ private static PackageInfo getPackageInfo(final Context context) throws PackageManager.NameNotFoundException {
469
+ final PackageManager packageManager = context.getPackageManager();
470
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
471
+ return packageManager.getPackageInfo(context.getPackageName(), PackageManager.PackageInfoFlags.of(0));
472
+ }
473
+ return packageManager.getPackageInfo(context.getPackageName(), 0);
474
+ }
475
+
476
+ /**
477
+ * Reuses a bundle already downloaded for {@code version}: queues it, and installs it when no UI runs, after
478
+ * the same builtinMinimum gate a fresh download goes through. Returns null when there is nothing to reuse.
479
+ */
480
+ static String reuseDownloadedBundle(
481
+ final CapgoUpdater updater,
482
+ final BundleInfo existing,
483
+ final String version,
484
+ final boolean setNext,
485
+ final Logger logger
486
+ ) {
487
+ if (existing == null || !existing.isDownloaded() || BundleStatus.DOWNLOADING == existing.getStatus()) {
488
+ return null;
489
+ }
490
+ if (builtinMinimumBlocksExistingBundle(updater, version, logger)) {
491
+ if (CapacitorUpdaterPlugin.isInstanceLoaded()) {
492
+ updater.handOverPendingStats();
493
+ }
494
+ return "skipped";
495
+ }
496
+ if (!updater.canSet(existing)) {
497
+ return null;
498
+ }
499
+ if (setNext && updater.setNextBundle(existing.getId())) {
500
+ return applyIfNoUi(updater, existing, logger) ? "installed" : "queued";
501
+ }
502
+ return "downloaded";
503
+ }
504
+
505
+ /** Mirrors the identity, URL and builtinMinimum setup of CapacitorUpdaterPlugin#load. */
506
+ private static void configure(
507
+ final CapgoUpdater updater,
508
+ final Context context,
509
+ final PluginConfig config,
510
+ final SharedPreferences prefs,
511
+ final PackageInfo packageInfo,
512
+ final String versionCode,
513
+ final Logger headlessLogger
514
+ ) {
515
+ updater.appContext = context;
516
+ updater.prefs = prefs;
517
+ updater.editor = prefs.edit();
518
+ updater.documentsDir = context.getFilesDir();
519
+ updater.noBackupDir = context.getNoBackupFilesDir();
520
+ // Shares the plugin's pending-stats file: load it first so a flush does not overwrite it.
521
+ updater.restorePendingStats();
522
+ updater.CAP_SERVER_PATH = WebView.CAP_SERVER_PATH;
523
+ updater.pluginVersion = CapacitorUpdaterPlugin.PLUGIN_VERSION;
524
+ updater.versionBuild = config.getString("version", packageInfo.versionName);
525
+ updater.versionCode = versionCode;
526
+ updater.versionOs = Build.VERSION.RELEASE;
527
+
528
+ String appId = InternalUtils.getPackageName(context.getPackageManager(), context.getPackageName());
529
+ appId = InternalUtils.getRootConfigString(context, "appId", appId);
530
+ updater.appId = config.getString("appId", appId);
531
+ updater.setPublicKey(config.getString("publicKey", ""));
532
+ // Same default as CapacitorUpdaterPlugin#load: on unless the app opts out.
533
+ updater.builtinMinimum = config.getBoolean("builtinMinimum", true);
534
+
535
+ DownloadService.setAllowHttpsToHttpRedirect(config.getBoolean("allowHttpsToHttpRedirect", false));
536
+ Http3.setEnabled(config.getBoolean("http3", true));
537
+ final boolean httpsOnly = config.getBoolean("httpsOnly", true);
538
+ updater.httpsOnly = httpsOnly;
539
+ DownloadService.setHttpsOnly(httpsOnly);
540
+ DownloadService.setLoggerIfAbsent(headlessLogger);
541
+ DownloadWorkerManager.setLoggerIfAbsent(headlessLogger);
542
+
543
+ final boolean persistModifyUrl = config.getBoolean("persistModifyUrl", false);
544
+ updater.statsUrl = config.getString("statsUrl", CapacitorUpdaterPlugin.statsUrlDefault);
545
+ updater.channelUrl = config.getString("channelUrl", CapacitorUpdaterPlugin.channelUrlDefault);
546
+ if (persistModifyUrl) {
547
+ updater.statsUrl = prefs.getString(CapacitorUpdaterPlugin.STATS_URL_PREF_KEY, updater.statsUrl);
548
+ updater.channelUrl = prefs.getString(CapacitorUpdaterPlugin.CHANNEL_URL_PREF_KEY, updater.channelUrl);
549
+ }
550
+
551
+ final String storedDefaultChannel = prefs.getString(CapacitorUpdaterPlugin.DEFAULT_CHANNEL_PREF_KEY, "");
552
+ updater.defaultChannel =
553
+ storedDefaultChannel != null && !storedDefaultChannel.isEmpty() ? storedDefaultChannel : config.getString("defaultChannel", "");
554
+
555
+ if (config.getBoolean("persistCustomId", true)) {
556
+ final String storedCustomId = prefs.getString(CapacitorUpdaterPlugin.CUSTOM_ID_PREF_KEY, "");
557
+ if (storedCustomId != null && !storedCustomId.isEmpty()) {
558
+ updater.customId = storedCustomId;
559
+ }
560
+ }
561
+ updater.deviceID = DeviceIdHelper.getOrCreateDeviceId(context, prefs);
562
+
563
+ final int responseTimeoutSeconds = config.getInt("responseTimeout", 20);
564
+ final long responseTimeoutMillis = responseTimeoutSeconds > 0 ? (long) responseTimeoutSeconds * 1000L : 20_000L;
565
+ updater.timeout = (int) Math.min(Integer.MAX_VALUE, responseTimeoutMillis);
566
+ DownloadService.applyHttpTimeouts(updater.timeout);
567
+ DownloadService.updateUserAgent(updater.appId, updater.pluginVersion, updater.versionOs);
568
+ }
569
+ }