@capgo/capacitor-updater 8.52.1 → 8.53.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 (25) 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 +414 -150
  4. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +693 -217
  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 +324 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +34 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  11. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +4 -4
  12. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +1 -1
  13. package/dist/docs.json +378 -27
  14. package/dist/esm/definitions.d.ts +206 -7
  15. package/dist/esm/definitions.js.map +1 -1
  16. package/dist/plugin.cjs.js.map +1 -1
  17. package/dist/plugin.js.map +1 -1
  18. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +360 -104
  20. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +166 -10
  21. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +2 -1
  22. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +202 -90
  23. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  24. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +5 -2
  25. package/package.json +7 -3
@@ -11,8 +11,11 @@ import android.content.Context;
11
11
  import android.content.SharedPreferences;
12
12
  import android.content.pm.PackageManager;
13
13
  import android.os.Build;
14
+ import android.os.Handler;
15
+ import android.os.Looper;
14
16
  import androidx.annotation.NonNull;
15
- import androidx.lifecycle.LifecycleOwner;
17
+ import androidx.lifecycle.LiveData;
18
+ import androidx.lifecycle.Observer;
16
19
  import androidx.work.Constraints;
17
20
  import androidx.work.Data;
18
21
  import androidx.work.ExistingPeriodicWorkPolicy;
@@ -24,15 +27,14 @@ import androidx.work.PeriodicWorkRequest;
24
27
  import androidx.work.WorkInfo;
25
28
  import androidx.work.WorkManager;
26
29
  import java.io.BufferedInputStream;
27
- import java.io.BufferedReader;
28
30
  import java.io.File;
29
31
  import java.io.FileInputStream;
30
32
  import java.io.FileNotFoundException;
31
33
  import java.io.FileOutputStream;
32
34
  import java.io.FilenameFilter;
33
35
  import java.io.IOException;
34
- import java.io.InputStreamReader;
35
36
  import java.nio.charset.StandardCharsets;
37
+ import java.nio.file.Files;
36
38
  import java.security.SecureRandom;
37
39
  import java.util.ArrayList;
38
40
  import java.util.Date;
@@ -49,8 +51,10 @@ import java.util.concurrent.ConcurrentHashMap;
49
51
  import java.util.concurrent.CopyOnWriteArrayList;
50
52
  import java.util.concurrent.ExecutorService;
51
53
  import java.util.concurrent.Executors;
54
+ import java.util.concurrent.LinkedBlockingQueue;
52
55
  import java.util.concurrent.ScheduledExecutorService;
53
56
  import java.util.concurrent.ScheduledFuture;
57
+ import java.util.concurrent.ThreadPoolExecutor;
54
58
  import java.util.concurrent.TimeUnit;
55
59
  import java.util.concurrent.atomic.AtomicBoolean;
56
60
  import java.util.zip.ZipEntry;
@@ -76,9 +80,11 @@ public class CapgoUpdater {
76
80
  private static final String PENDING_DELETE_IDS = "pendingDeleteIds";
77
81
  private static final String bundleDirectory = "versions";
78
82
  private static final String TEMP_UNZIP_PREFIX = "capgo_unzip_";
83
+ static final String MANIFEST_STAGING_PREFIX = "capgo_manifest_";
84
+ static final String MANIFEST_DEST_SUFFIX = "_manifest_dest";
85
+ private static final String LEGACY_MANIFEST_STAGING_FOLDER_PATTERN = "^[0-9A-Za-z]{10}$";
79
86
  private static final long DELETE_PACE_MS = 75L;
80
87
  private final Object deleteLock = new Object();
81
- private static final String CAPACITOR_CONFIG_ASSET = "capacitor.config.json";
82
88
  private static final String BACKGROUND_RUNNER_CONFIG_KEY = "BackgroundRunner";
83
89
  private static final String BACKGROUND_RUNNER_WORKER_CLASS = "io.ionic.backgroundrunner.plugin.RunnerWorker";
84
90
 
@@ -93,6 +99,9 @@ public class CapgoUpdater {
93
99
  public File noBackupDir;
94
100
  public Boolean directUpdate = false;
95
101
  public Activity activity;
102
+ // Application context: lets downloads run and finish without an Activity (app in the
103
+ // background, or a process woken by a push with no UI at all).
104
+ public Context appContext;
96
105
  public String pluginVersion = "";
97
106
  public String versionBuild = "";
98
107
  public String versionCode = "";
@@ -137,23 +146,52 @@ public class CapgoUpdater {
137
146
  private static final long STATS_FLUSH_INTERVAL_MS = 1000;
138
147
  private static final String PENDING_STATS_FILE = "capgo_pending_stats.json";
139
148
  private static final int MAX_PENDING_STATS = 200;
149
+ // The live plugin instance owns the stats file. A headless worker hands its unsent events to it
150
+ // instead of writing the file; events handed over before the plugin claims ownership wait here.
151
+ private static final Object statsOwnerLock = new Object();
152
+ private static CapgoUpdater statsOwner = null;
153
+ private static final List<JSONObject> orphanedStats = new ArrayList<>();
140
154
 
141
155
  private static final class QueuedStatsEvent {
142
156
 
143
157
  private final JSONObject event;
144
158
  private final Runnable onSent;
159
+ /** True when the event was loaded from the shared pending-stats file (not created by this instance). */
160
+ private final boolean restored;
145
161
 
146
162
  private QueuedStatsEvent(final JSONObject event, final Runnable onSent) {
163
+ this(event, onSent, false);
164
+ }
165
+
166
+ private QueuedStatsEvent(final JSONObject event, final Runnable onSent, final boolean restored) {
147
167
  this.event = event;
148
168
  this.onSent = onSent;
169
+ this.restored = restored;
149
170
  }
150
171
  }
151
172
 
152
173
  private final Map<String, CompletableFuture<BundleInfo>> downloadFutures = new ConcurrentHashMap<>();
174
+
175
+ /** A download failure whose downloadFailed event and stats were already sent by the updater. */
176
+ static final class ReportedDownloadFailureException extends IOException {
177
+
178
+ ReportedDownloadFailureException(final String message) {
179
+ super(message);
180
+ }
181
+ }
182
+
153
183
  // Versions whose WorkManager download is observed by this process. WorkManager persists work across a
154
184
  // process kill, but the observer that finishes the download does not survive it.
155
185
  private final Set<String> observedDownloadVersions = ConcurrentHashMap.newKeySet();
156
- private final ExecutorService io = Executors.newSingleThreadExecutor();
186
+ private final ExecutorService io = createIoExecutor();
187
+
188
+ private static ExecutorService createIoExecutor() {
189
+ final ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
190
+ executor.allowCoreThreadTimeOut(true);
191
+ return executor;
192
+ }
193
+
194
+ private volatile Handler mainHandler;
157
195
 
158
196
  public CapgoUpdater(Logger logger) {
159
197
  this.logger = logger;
@@ -164,12 +202,22 @@ public class CapgoUpdater {
164
202
  return !name.startsWith("__MACOSX") && !name.startsWith(".") && !name.startsWith(".DS_Store");
165
203
  };
166
204
 
205
+ /** The Activity when the app has one, otherwise the application context. */
206
+ Context context() {
207
+ final Activity current = this.activity;
208
+ if (current != null) {
209
+ return current;
210
+ }
211
+ return this.appContext;
212
+ }
213
+
167
214
  private boolean isProd() {
168
215
  try {
169
- if (activity == null) {
170
- return true; // Default to production if no activity context
216
+ final Context context = this.context();
217
+ if (context == null) {
218
+ return true; // Default to production if no context
171
219
  }
172
- return (activity.getApplicationInfo().flags & android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) == 0;
220
+ return (context.getApplicationInfo().flags & android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) == 0;
173
221
  } catch (Exception e) {
174
222
  return true; // Default to production if we can't determine
175
223
  }
@@ -197,13 +245,14 @@ public class CapgoUpdater {
197
245
 
198
246
  @SuppressWarnings("deprecation")
199
247
  private String getInstallSource() {
200
- if (activity == null) {
248
+ final Context context = this.context();
249
+ if (context == null) {
201
250
  return "";
202
251
  }
203
252
 
204
253
  try {
205
- PackageManager packageManager = activity.getPackageManager();
206
- String packageName = activity.getPackageName();
254
+ PackageManager packageManager = context.getPackageManager();
255
+ String packageName = context.getPackageName();
207
256
  String installerPackageName;
208
257
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
209
258
  android.content.pm.InstallSourceInfo installSourceInfo = packageManager.getInstallSourceInfo(packageName);
@@ -263,6 +312,9 @@ public class CapgoUpdater {
263
312
 
264
313
  void notifyListeners(final String id, final Map<String, Object> res) {}
265
314
 
315
+ /** A downloaded bundle was stored as next bundle and waits for its install moment. */
316
+ void nextBundleReady(final BundleInfo bundle) {}
317
+
266
318
  static boolean shouldNotifyLaunchDownloadReady(
267
319
  final boolean awaitedByCaller,
268
320
  final boolean success,
@@ -307,6 +359,249 @@ public class CapgoUpdater {
307
359
  return sb.toString();
308
360
  }
309
361
 
362
+ static boolean isManifestStagingFolderName(final String name) {
363
+ if (name == null || !name.startsWith(MANIFEST_STAGING_PREFIX)) {
364
+ return false;
365
+ }
366
+ final String suffix = name.substring(MANIFEST_STAGING_PREFIX.length());
367
+ return suffix.length() == 10 && suffix.matches("[0-9A-Za-z]{10}");
368
+ }
369
+
370
+ String manifestStagingDest() {
371
+ return MANIFEST_STAGING_PREFIX + this.randomString();
372
+ }
373
+
374
+ private static boolean isLegacyBareManifestStagingFolderName(final String name) {
375
+ return name != null && name.matches(LEGACY_MANIFEST_STAGING_FOLDER_PATTERN);
376
+ }
377
+
378
+ private static boolean isSymbolicLinkEntry(final File file) {
379
+ return Files.isSymbolicLink(file.toPath());
380
+ }
381
+
382
+ private static boolean isRegularFileEntry(final File file) {
383
+ return file.isFile() && !isSymbolicLinkEntry(file);
384
+ }
385
+
386
+ private static boolean isRegularDirectoryEntry(final File file) {
387
+ return file.isDirectory() && !isSymbolicLinkEntry(file);
388
+ }
389
+
390
+ private static final long LEGACY_MANIFEST_STAGING_MIN_AGE_MS = 24L * 60L * 60L * 1000L;
391
+
392
+ private static boolean looksLikeLeakedManifestStaging(final File dir) {
393
+ if (dir == null || !isRegularDirectoryEntry(dir)) {
394
+ return false;
395
+ }
396
+ if (isRegularFileEntry(new File(dir, "index.html"))) {
397
+ return true;
398
+ }
399
+ if (isRegularDirectoryEntry(new File(dir, "assets"))) {
400
+ return true;
401
+ }
402
+ return isRegularDirectoryEntry(new File(dir, "www"));
403
+ }
404
+
405
+ private static boolean isOldEnoughForLegacyManifestCleanup(final File dir) {
406
+ final long ageMs = System.currentTimeMillis() - dir.lastModified();
407
+ return ageMs >= LEGACY_MANIFEST_STAGING_MIN_AGE_MS;
408
+ }
409
+
410
+ void saveManifestStagingDest(final String bundleId, final String dest) {
411
+ if (this.editor == null || bundleId == null || dest == null || dest.isEmpty()) {
412
+ return;
413
+ }
414
+ this.editor.putString(bundleId + MANIFEST_DEST_SUFFIX, dest);
415
+ this.editor.commit();
416
+ }
417
+
418
+ void clearManifestStagingDest(final String bundleId) {
419
+ if (this.editor == null || bundleId == null) {
420
+ return;
421
+ }
422
+ this.editor.remove(bundleId + MANIFEST_DEST_SUFFIX);
423
+ this.editor.commit();
424
+ }
425
+
426
+ void cleanupManifestStagingAfterDownloadFailed(final String bundleId, final String failedDest, final boolean failedManifest) {
427
+ if (failedManifest) {
428
+ this.deleteManifestStagingFolder(failedDest);
429
+ }
430
+ this.clearManifestStagingDest(bundleId);
431
+ }
432
+
433
+ void cleanupManifestStagingAfterDownloadCancelled(final String bundleId) {
434
+ final String cancelledDest = this.prefs != null ? this.prefs.getString(bundleId + MANIFEST_DEST_SUFFIX, null) : null;
435
+ this.deleteManifestStagingFolder(cancelledDest);
436
+ this.clearManifestStagingDest(bundleId);
437
+ }
438
+
439
+ Set<String> activeManifestStagingDests() {
440
+ final Set<String> activeDests = new HashSet<>();
441
+ if (this.prefs == null) {
442
+ return activeDests;
443
+ }
444
+ for (final BundleInfo info : this.list(true)) {
445
+ if (info == null || info.getId() == null || info.getId().isEmpty()) {
446
+ continue;
447
+ }
448
+ if (info.getStatus() != BundleStatus.DOWNLOADING) {
449
+ continue;
450
+ }
451
+ final String dest = this.prefs.getString(info.getId() + MANIFEST_DEST_SUFFIX, null);
452
+ if (dest != null && !dest.isEmpty()) {
453
+ activeDests.add(dest);
454
+ }
455
+ }
456
+ return activeDests;
457
+ }
458
+
459
+ public void deleteManifestStagingFolder(final String dest) {
460
+ if (this.documentsDir == null || dest == null || dest.isEmpty() || !isManifestStagingFolderName(dest)) {
461
+ return;
462
+ }
463
+ final File folder = new File(this.documentsDir, dest);
464
+ try {
465
+ this.assertPathInsideDocumentsDir(folder);
466
+ deleteManifestStagingTree(folder);
467
+ } catch (IOException e) {
468
+ logger.warn("Failed to delete manifest staging folder: " + e.getMessage());
469
+ }
470
+ }
471
+
472
+ static void deleteManifestStagingFolderAt(final File documentsDir, final String dest, final Logger log) {
473
+ if (documentsDir == null || dest == null || dest.isEmpty() || !isManifestStagingFolderName(dest)) {
474
+ return;
475
+ }
476
+ final File folder = new File(documentsDir, dest);
477
+ if (!folder.exists()) {
478
+ return;
479
+ }
480
+ try {
481
+ final File canonicalBase = documentsDir.getCanonicalFile();
482
+ final File canonicalTarget = folder.getCanonicalFile();
483
+ final String basePath = canonicalBase.getPath();
484
+ final String normalizedBasePath = basePath.endsWith(File.separator) ? basePath : basePath + File.separator;
485
+ final String targetPath = canonicalTarget.getPath();
486
+ if (!targetPath.equals(basePath) && !targetPath.startsWith(normalizedBasePath)) {
487
+ if (log != null) {
488
+ log.warn("Refusing unsafe manifest staging delete: " + folder.getAbsolutePath());
489
+ }
490
+ return;
491
+ }
492
+ if (canonicalTarget.isDirectory()) {
493
+ deleteManifestStagingTree(canonicalTarget);
494
+ } else if (!canonicalTarget.delete()) {
495
+ if (log != null) {
496
+ log.warn("Failed to delete manifest staging file: " + canonicalTarget.getAbsolutePath());
497
+ }
498
+ }
499
+ } catch (IOException e) {
500
+ if (log != null) {
501
+ log.warn("Failed to delete manifest staging folder: " + e.getMessage());
502
+ }
503
+ }
504
+ }
505
+
506
+ private static void deleteManifestStagingTree(final File file) throws IOException {
507
+ if (isSymbolicLinkEntry(file)) {
508
+ if (!file.delete()) {
509
+ throw new IOException("Failed to delete symlink: " + file);
510
+ }
511
+ return;
512
+ }
513
+ if (file.isDirectory()) {
514
+ final File[] entries = file.listFiles();
515
+ if (entries != null) {
516
+ for (final File entry : entries) {
517
+ deleteManifestStagingTree(entry);
518
+ }
519
+ }
520
+ }
521
+ if (!file.delete()) {
522
+ throw new IOException("Failed to delete: " + file);
523
+ }
524
+ }
525
+
526
+ public void cleanupOrphanedManifestStagingFolders(final Thread threadToCheck) {
527
+ if (this.documentsDir == null) {
528
+ logger.warn("Documents directory is null, skipping manifest staging cleanup");
529
+ return;
530
+ }
531
+
532
+ final File[] entries = this.documentsDir.listFiles();
533
+ if (entries == null) {
534
+ return;
535
+ }
536
+
537
+ final Set<String> protectedDests = this.activeManifestStagingDests();
538
+
539
+ for (final File entry : entries) {
540
+ if (threadToCheck != null && threadToCheck.isInterrupted()) {
541
+ logger.warn("cleanupOrphanedManifestStagingFolders was cancelled");
542
+ return;
543
+ }
544
+ if (!entry.isDirectory()) {
545
+ continue;
546
+ }
547
+ final String folderName = entry.getName();
548
+ if (!isManifestStagingFolderName(folderName)) {
549
+ continue;
550
+ }
551
+ if (protectedDests.contains(folderName)) {
552
+ continue;
553
+ }
554
+ try {
555
+ deleteManifestStagingTree(entry);
556
+ logger.info("Deleted orphaned manifest staging folder");
557
+ logger.debug("Folder: " + folderName);
558
+ } catch (IOException e) {
559
+ logger.error("Failed to delete orphaned manifest staging folder");
560
+ logger.debug("Folder: " + folderName + ", Error: " + e.getMessage());
561
+ }
562
+ }
563
+
564
+ this.cleanupLegacyBareManifestStagingFolders(threadToCheck, protectedDests);
565
+ }
566
+
567
+ private void cleanupLegacyBareManifestStagingFolders(final Thread threadToCheck, final Set<String> protectedDests) {
568
+ final File[] entries = this.documentsDir.listFiles();
569
+ if (entries == null) {
570
+ return;
571
+ }
572
+
573
+ for (final File entry : entries) {
574
+ if (threadToCheck != null && threadToCheck.isInterrupted()) {
575
+ logger.warn("cleanupLegacyBareManifestStagingFolders was cancelled");
576
+ return;
577
+ }
578
+ if (!entry.isDirectory()) {
579
+ continue;
580
+ }
581
+ final String folderName = entry.getName();
582
+ if (!isLegacyBareManifestStagingFolderName(folderName)) {
583
+ continue;
584
+ }
585
+ if (protectedDests.contains(folderName)) {
586
+ continue;
587
+ }
588
+ if (!looksLikeLeakedManifestStaging(entry)) {
589
+ continue;
590
+ }
591
+ if (!isOldEnoughForLegacyManifestCleanup(entry)) {
592
+ continue;
593
+ }
594
+ try {
595
+ deleteManifestStagingTree(entry);
596
+ logger.info("Deleted legacy bare manifest staging folder");
597
+ logger.debug("Folder: " + folderName);
598
+ } catch (IOException e) {
599
+ logger.error("Failed to delete legacy bare manifest staging folder");
600
+ logger.debug("Folder: " + folderName + ", Error: " + e.getMessage());
601
+ }
602
+ }
603
+ }
604
+
310
605
  public void setPublicKey(String publicKey) {
311
606
  // Empty string means no encryption - proceed normally
312
607
  if (publicKey == null || publicKey.isEmpty()) {
@@ -481,8 +776,8 @@ public class CapgoUpdater {
481
776
  }
482
777
 
483
778
  void cacheBundleFiles(final String id) {
484
- if (this.activity == null) {
485
- logger.debug("Skip delta cache population: activity is null");
779
+ if (this.context() == null) {
780
+ logger.debug("Skip delta cache population: no context");
486
781
  return;
487
782
  }
488
783
 
@@ -498,7 +793,7 @@ public class CapgoUpdater {
498
793
  return;
499
794
  }
500
795
 
501
- final File cacheDir = new File(this.activity.getCacheDir(), "capgo_downloads");
796
+ final File cacheDir = new File(this.context().getCacheDir(), "capgo_downloads");
502
797
  if (cacheDir.exists() && !cacheDir.isDirectory()) {
503
798
  logger.debug("Skip delta cache population: cache dir is not a directory");
504
799
  return;
@@ -508,7 +803,7 @@ public class CapgoUpdater {
508
803
  return;
509
804
  }
510
805
 
511
- final File builtinFolder = new File(this.activity.getFilesDir(), "public");
806
+ final File builtinFolder = new File(this.context().getFilesDir(), "public");
512
807
 
513
808
  final List<File> files = new ArrayList<>();
514
809
  collectFiles(bundleDir, files);
@@ -598,16 +893,16 @@ public class CapgoUpdater {
598
893
  private boolean isManifestEntryAvailableLocally(final JSONObject entry, final String sessionKey) {
599
894
  final String fileName = entry.optString("file_name", "");
600
895
  final String fileHash = resolveManifestFileHash(entry, sessionKey);
601
- if (fileName.isEmpty() || fileHash.isEmpty() || this.activity == null) {
896
+ if (fileName.isEmpty() || fileHash.isEmpty() || this.context() == null) {
602
897
  return false;
603
898
  }
604
899
 
605
- if (DownloadService.builtinAssetMatches(this.activity.getAssets(), fileName, fileHash)) {
900
+ if (DownloadService.builtinAssetMatches(this.context().getAssets(), fileName, fileHash)) {
606
901
  return true;
607
902
  }
608
903
 
609
904
  try {
610
- final File builtinFile = DownloadService.resolveManifestBuiltinFile(new File(this.activity.getFilesDir(), "public"), fileName);
905
+ final File builtinFile = DownloadService.resolveManifestBuiltinFile(new File(this.context().getFilesDir(), "public"), fileName);
611
906
  if (verifyChecksum(builtinFile, fileHash)) {
612
907
  return true;
613
908
  }
@@ -619,7 +914,7 @@ public class CapgoUpdater {
619
914
  final String fileNameWithoutPath = new File(fileName).getName();
620
915
  final String cacheBaseName = isBrotli ? fileNameWithoutPath.substring(0, fileNameWithoutPath.length() - 3) : fileNameWithoutPath;
621
916
  if (isSafeCacheHash(fileHash)) {
622
- final File cacheFolder = new File(this.activity.getCacheDir(), "capgo_downloads");
917
+ final File cacheFolder = new File(this.context().getCacheDir(), "capgo_downloads");
623
918
  final File cacheFile = new File(cacheFolder, fileHash + "_" + cacheBaseName);
624
919
  // Cache files are named `{hash}_{filename}` and were checksum-verified
625
920
  // when written. Re-hashing every hit re-reads the whole bundle and
@@ -762,155 +1057,168 @@ public class CapgoUpdater {
762
1057
  this.backgroundDownloadSettled(readyBundle, launchDownloadReadyStatus(success, setNext));
763
1058
  }
764
1059
 
765
- private void observeWorkProgress(Context context, String id, String observedVersion, boolean setNext) {
766
- if (!(context instanceof LifecycleOwner)) {
767
- logger.error("Context is not a LifecycleOwner, cannot observe work progress");
768
- return;
1060
+ // Created on first use: plain JVM unit tests construct CapgoUpdater without a main Looper.
1061
+ private Handler mainHandler() {
1062
+ Handler handler = this.mainHandler;
1063
+ if (handler == null) {
1064
+ handler = new Handler(Looper.getMainLooper());
1065
+ this.mainHandler = handler;
769
1066
  }
1067
+ return handler;
1068
+ }
770
1069
 
1070
+ @SuppressWarnings("unchecked")
1071
+ private void observeWorkProgress(Context context, String id, String observedVersion, boolean setNext) {
771
1072
  final AtomicBoolean terminalHandled = new AtomicBoolean(false);
772
1073
  final AtomicBoolean launchReleasedWhileRetrying = new AtomicBoolean(false);
773
- activity.runOnUiThread(() -> {
774
- WorkManager.getInstance(context)
775
- .getWorkInfosByTagLiveData(id)
776
- .observe((LifecycleOwner) context, (workInfos) -> {
777
- if (workInfos == null || workInfos.isEmpty()) return;
778
-
779
- WorkInfo workInfo = workInfos.get(0);
780
- Data progress = workInfo.getProgress();
781
-
782
- switch (workInfo.getState()) {
783
- case ENQUEUED:
784
- // A run attempt already happened, so WorkManager scheduled a retry (network lost midway,
785
- // 5xx, ...). Retries back off without limit, so a direct install must not keep the launch
786
- // (and its splashscreen) blocked until the network comes back.
787
- if (
788
- workInfo.getRunAttemptCount() > 0 &&
789
- shouldReleaseLaunchWhileRetrying(
790
- downloadFutures.containsKey(id),
791
- setNext,
792
- Boolean.TRUE.equals(CapgoUpdater.this.directUpdate),
793
- CapgoUpdater.this.previewSession
794
- ) &&
795
- launchReleasedWhileRetrying.compareAndSet(false, true)
796
- ) {
797
- logger.warn("Direct update download is retrying, continuing launch on the current bundle");
798
- // Same fallback as the autoSplashscreen timeout: a later success installs on next background.
799
- CapgoUpdater.this.directUpdate = false;
800
- io.execute(() -> backgroundDownloadSettled(getCurrentBundle(), launchDownloadReadyStatus(false, false)));
1074
+ final LiveData<List<WorkInfo>> workInfosLiveData = WorkManager.getInstance(
1075
+ context.getApplicationContext()
1076
+ ).getWorkInfosByTagLiveData(id);
1077
+ // observeForever, not observe(activity): a stopped Activity pauses LiveData, so a download
1078
+ // that completes while the app is in the background would only be finished once the user
1079
+ // opens the app again. The observer removes itself on a terminal state.
1080
+ final Observer<List<WorkInfo>>[] observerRef = new Observer[1];
1081
+ final Runnable removeObserver = () -> mainHandler().post(() -> workInfosLiveData.removeObserver(observerRef[0]));
1082
+ mainHandler().post(() -> {
1083
+ observerRef[0] = (workInfos) -> {
1084
+ if (workInfos == null || workInfos.isEmpty()) return;
1085
+
1086
+ WorkInfo workInfo = workInfos.get(0);
1087
+ Data progress = workInfo.getProgress();
1088
+
1089
+ switch (workInfo.getState()) {
1090
+ case ENQUEUED:
1091
+ // A run attempt already happened, so WorkManager scheduled a retry (network lost midway,
1092
+ // 5xx, ...). Retries back off without limit, so a direct install must not keep the launch
1093
+ // (and its splashscreen) blocked until the network comes back.
1094
+ if (
1095
+ workInfo.getRunAttemptCount() > 0 &&
1096
+ shouldReleaseLaunchWhileRetrying(
1097
+ downloadFutures.containsKey(id),
1098
+ setNext,
1099
+ Boolean.TRUE.equals(CapgoUpdater.this.directUpdate),
1100
+ CapgoUpdater.this.previewSession
1101
+ ) &&
1102
+ launchReleasedWhileRetrying.compareAndSet(false, true)
1103
+ ) {
1104
+ logger.warn("Direct update download is retrying, continuing launch on the current bundle");
1105
+ // Same fallback as the autoSplashscreen timeout: a later success installs on next background.
1106
+ CapgoUpdater.this.directUpdate = false;
1107
+ io.execute(() -> backgroundDownloadSettled(getCurrentBundle(), launchDownloadReadyStatus(false, false)));
1108
+ }
1109
+ break;
1110
+ case RUNNING:
1111
+ int percent = progress.getInt(DownloadService.PERCENT, 0);
1112
+ notifyDownload(id, percent);
1113
+ break;
1114
+ case SUCCEEDED:
1115
+ if (!terminalHandled.compareAndSet(false, true)) break;
1116
+ removeObserver.run();
1117
+ observedDownloadVersions.remove(observedVersion);
1118
+ logger.info("Download succeeded: " + workInfo.getState());
1119
+ Data outputData = workInfo.getOutputData();
1120
+ String dest = outputData.getString(DownloadService.FILEDEST);
1121
+ String version = outputData.getString(DownloadService.VERSION);
1122
+ String sessionKey = outputData.getString(DownloadService.SESSIONKEY);
1123
+ String checksum = outputData.getString(DownloadService.CHECKSUM);
1124
+ boolean isManifest = outputData.getBoolean(DownloadService.IS_MANIFEST, false);
1125
+
1126
+ io.execute(() -> {
1127
+ // finishDownload clears directUpdate, so read the install plan first.
1128
+ final boolean directInstall =
1129
+ setNext && Boolean.TRUE.equals(CapgoUpdater.this.directUpdate) && !CapgoUpdater.this.previewSession;
1130
+ final boolean previewSession = CapgoUpdater.this.previewSession;
1131
+ boolean success = finishDownload(id, dest, version, sessionKey, checksum, setNext, isManifest);
1132
+ BundleInfo resultBundle;
1133
+ if (!success) {
1134
+ logger.error("Finish download failed");
1135
+ logger.debug("Version: " + version);
1136
+ resultBundle = new BundleInfo(id, version, BundleStatus.ERROR, new Date(System.currentTimeMillis()), "");
1137
+ saveBundleInfo(id, resultBundle);
1138
+ // Cleanup download tracking
1139
+ DownloadWorkerManager.cancelBundleDownload(context, id, version);
1140
+ sendStats("finish_download_fail", version);
1141
+ // finishDownload already emitted downloadFailed for this failure.
1142
+ } else {
1143
+ // Successful download - cleanup tracking
1144
+ DownloadWorkerManager.cancelBundleDownload(context, id, version);
1145
+ resultBundle = getBundleInfo(id);
801
1146
  }
802
- break;
803
- case RUNNING:
804
- int percent = progress.getInt(DownloadService.PERCENT, 0);
805
- notifyDownload(id, percent);
806
- break;
807
- case SUCCEEDED:
808
- if (!terminalHandled.compareAndSet(false, true)) break;
809
- observedDownloadVersions.remove(observedVersion);
810
- logger.info("Download succeeded: " + workInfo.getState());
811
- Data outputData = workInfo.getOutputData();
812
- String dest = outputData.getString(DownloadService.FILEDEST);
813
- String version = outputData.getString(DownloadService.VERSION);
814
- String sessionKey = outputData.getString(DownloadService.SESSIONKEY);
815
- String checksum = outputData.getString(DownloadService.CHECKSUM);
816
- boolean isManifest = outputData.getBoolean(DownloadService.IS_MANIFEST, false);
817
-
818
- io.execute(() -> {
819
- // finishDownload clears directUpdate, so read the install plan first.
820
- final boolean directInstall =
821
- setNext && Boolean.TRUE.equals(CapgoUpdater.this.directUpdate) && !CapgoUpdater.this.previewSession;
822
- final boolean previewSession = CapgoUpdater.this.previewSession;
823
- boolean success = finishDownload(id, dest, version, sessionKey, checksum, setNext, isManifest);
824
- BundleInfo resultBundle;
825
- if (!success) {
826
- logger.error("Finish download failed");
827
- logger.debug("Version: " + version);
828
- resultBundle = new BundleInfo(
829
- id,
830
- version,
831
- BundleStatus.ERROR,
832
- new Date(System.currentTimeMillis()),
833
- ""
834
- );
835
- saveBundleInfo(id, resultBundle);
836
- // Cleanup download tracking
837
- DownloadWorkerManager.cancelBundleDownload(activity, id, version);
838
- Map<String, Object> ret = new HashMap<>();
839
- ret.put("version", version);
840
- ret.put("error", "finish_download_fail");
841
- sendStats("finish_download_fail", version);
842
- notifyListeners("downloadFailed", ret);
843
- } else {
844
- // Successful download - cleanup tracking
845
- DownloadWorkerManager.cancelBundleDownload(activity, id, version);
846
- resultBundle = getBundleInfo(id);
847
- }
848
1147
 
849
- // Complete the future if it exists. download() waits on it.
850
- // downloadBackground does not, so the launch check must emit appReady here.
851
- CompletableFuture<BundleInfo> future = downloadFutures.remove(id);
852
- if (future != null) {
853
- future.complete(resultBundle);
854
- }
855
- final BundleInfo readyBundle = success && setNext ? resultBundle : null;
856
- if (!launchReleasedWhileRetrying.get()) {
857
- notifyLaunchDownloadReady(future != null, success, directInstall, previewSession, setNext, readyBundle);
858
- }
859
- });
860
- break;
861
- case FAILED:
862
- if (!terminalHandled.compareAndSet(false, true)) break;
863
- observedDownloadVersions.remove(observedVersion);
864
- Data failedData = workInfo.getOutputData();
865
- String error = failedData.getString(DownloadService.ERROR);
866
- logger.error("Download failed");
867
- logger.debug("Error: " + error + ", State: " + workInfo.getState());
868
- String failedVersion = failedData.getString(DownloadService.VERSION);
869
-
870
- io.execute(() -> {
871
- BundleInfo failedBundle = new BundleInfo(
872
- id,
873
- failedVersion,
874
- BundleStatus.ERROR,
875
- new Date(System.currentTimeMillis()),
876
- ""
877
- );
878
- saveBundleInfo(id, failedBundle);
879
- // Cleanup download tracking for failed downloads
880
- DownloadWorkerManager.cancelBundleDownload(activity, id, failedVersion);
881
- Map<String, Object> ret = new HashMap<>();
882
- ret.put("version", failedVersion);
883
- if ("low_mem_fail".equals(error)) {
884
- sendStats("low_mem_fail", failedVersion);
885
- }
886
- if ("insufficient_disk_space".equals(error)) {
887
- sendStats("insufficient_disk_space", failedVersion);
888
- }
889
- ret.put("error", error != null ? error : "download_fail");
890
- sendStats("download_fail", failedVersion);
891
- notifyListeners("downloadFailed", ret);
892
-
893
- // Complete the future with error status
894
- CompletableFuture<BundleInfo> failedFuture = downloadFutures.remove(id);
895
- if (failedFuture != null) {
896
- failedFuture.complete(failedBundle);
897
- }
898
- if (!launchReleasedWhileRetrying.get()) {
899
- notifyLaunchDownloadReady(failedFuture != null, false, false, false, false, null);
900
- }
901
- });
902
- break;
903
- case CANCELLED:
904
- if (!terminalHandled.compareAndSet(false, true)) break;
905
- observedDownloadVersions.remove(observedVersion);
906
- DataManager.getInstance().clearManifest(id);
907
- CompletableFuture<BundleInfo> cancelledFuture = downloadFutures.remove(id);
908
- if (cancelledFuture != null) {
909
- cancelledFuture.cancel(true);
1148
+ CapgoUpdater.this.clearManifestStagingDest(id);
1149
+
1150
+ // Complete the future if it exists. download() waits on it.
1151
+ // downloadBackground does not, so the launch check must emit appReady here.
1152
+ CompletableFuture<BundleInfo> future = downloadFutures.remove(id);
1153
+ if (future != null) {
1154
+ future.complete(resultBundle);
910
1155
  }
911
- break;
912
- }
913
- });
1156
+ final BundleInfo readyBundle = success && setNext ? resultBundle : null;
1157
+ if (!launchReleasedWhileRetrying.get()) {
1158
+ notifyLaunchDownloadReady(future != null, success, directInstall, previewSession, setNext, readyBundle);
1159
+ }
1160
+ });
1161
+ break;
1162
+ case FAILED:
1163
+ if (!terminalHandled.compareAndSet(false, true)) break;
1164
+ removeObserver.run();
1165
+ observedDownloadVersions.remove(observedVersion);
1166
+ Data failedData = workInfo.getOutputData();
1167
+ String error = failedData.getString(DownloadService.ERROR);
1168
+ logger.error("Download failed");
1169
+ logger.debug("Error: " + error + ", State: " + workInfo.getState());
1170
+ String failedVersion = failedData.getString(DownloadService.VERSION);
1171
+ final String failedDest = failedData.getString(DownloadService.FILEDEST);
1172
+ final boolean failedManifest = failedData.getBoolean(DownloadService.IS_MANIFEST, false);
1173
+
1174
+ io.execute(() -> {
1175
+ CapgoUpdater.this.cleanupManifestStagingAfterDownloadFailed(id, failedDest, failedManifest);
1176
+ BundleInfo failedBundle = new BundleInfo(
1177
+ id,
1178
+ failedVersion,
1179
+ BundleStatus.ERROR,
1180
+ new Date(System.currentTimeMillis()),
1181
+ ""
1182
+ );
1183
+ saveBundleInfo(id, failedBundle);
1184
+ // Cleanup download tracking for failed downloads
1185
+ DownloadWorkerManager.cancelBundleDownload(context, id, failedVersion);
1186
+ Map<String, Object> ret = new HashMap<>();
1187
+ ret.put("version", failedVersion);
1188
+ if ("low_mem_fail".equals(error)) {
1189
+ sendStats("low_mem_fail", failedVersion);
1190
+ }
1191
+ if ("insufficient_disk_space".equals(error)) {
1192
+ sendStats("insufficient_disk_space", failedVersion);
1193
+ }
1194
+ ret.put("error", error != null ? error : "download_fail");
1195
+ sendStats("download_fail", failedVersion);
1196
+ notifyListeners("downloadFailed", ret);
1197
+
1198
+ // Complete the future with error status
1199
+ CompletableFuture<BundleInfo> failedFuture = downloadFutures.remove(id);
1200
+ if (failedFuture != null) {
1201
+ failedFuture.complete(failedBundle);
1202
+ }
1203
+ if (!launchReleasedWhileRetrying.get()) {
1204
+ notifyLaunchDownloadReady(failedFuture != null, false, false, false, false, null);
1205
+ }
1206
+ });
1207
+ break;
1208
+ case CANCELLED:
1209
+ if (!terminalHandled.compareAndSet(false, true)) break;
1210
+ removeObserver.run();
1211
+ observedDownloadVersions.remove(observedVersion);
1212
+ DataManager.getInstance().clearManifest(id);
1213
+ io.execute(() -> CapgoUpdater.this.cleanupManifestStagingAfterDownloadCancelled(id));
1214
+ CompletableFuture<BundleInfo> cancelledFuture = downloadFutures.remove(id);
1215
+ if (cancelledFuture != null) {
1216
+ cancelledFuture.cancel(true);
1217
+ }
1218
+ break;
1219
+ }
1220
+ };
1221
+ workInfosLiveData.observeForever(observerRef[0]);
914
1222
  });
915
1223
  }
916
1224
 
@@ -924,19 +1232,21 @@ public class CapgoUpdater {
924
1232
  final JSONArray manifest,
925
1233
  final boolean setNext
926
1234
  ) {
927
- if (this.activity == null) {
928
- logger.error("Activity is null, cannot observe work progress");
1235
+ final Context context = this.context();
1236
+ if (context == null) {
1237
+ logger.error("No context, cannot observe work progress");
929
1238
  return;
930
1239
  }
931
1240
  observedDownloadVersions.add(version);
932
- observeWorkProgress(this.activity, id, version, setNext);
1241
+ observeWorkProgress(context, id, version, setNext);
933
1242
 
934
1243
  if (manifest != null) {
935
1244
  DataManager.getInstance().setManifest(id, manifest);
1245
+ this.saveManifestStagingDest(id, dest);
936
1246
  }
937
1247
 
938
1248
  DownloadWorkerManager.enqueueDownload(
939
- this.activity,
1249
+ context,
940
1250
  url,
941
1251
  id,
942
1252
  this.documentsDir.getAbsolutePath(),
@@ -999,9 +1309,7 @@ public class CapgoUpdater {
999
1309
  }
1000
1310
  // Remove the decryption for manifest downloads
1001
1311
  } catch (Exception e) {
1002
- if (!isManifest) {
1003
- safeDelete(downloaded);
1004
- }
1312
+ safeDelete(downloaded);
1005
1313
  final Boolean res = this.delete(id);
1006
1314
  if (!res) {
1007
1315
  logger.info("Failed to cleanup after error");
@@ -1048,14 +1356,14 @@ public class CapgoUpdater {
1048
1356
  this.directUpdate = false;
1049
1357
  } else {
1050
1358
  logger.info("directUpdate: " + this.directUpdate);
1051
- this.setNextBundle(next.getId());
1359
+ if (this.setNextBundle(next.getId())) {
1360
+ this.nextBundleReady(next);
1361
+ }
1052
1362
  }
1053
1363
  }
1054
1364
  } catch (IOException e) {
1055
- if (!isManifest) {
1056
- safeDelete(extractedDir);
1057
- safeDelete(downloaded);
1058
- }
1365
+ safeDelete(extractedDir);
1366
+ safeDelete(downloaded);
1059
1367
  e.printStackTrace();
1060
1368
  final Map<String, Object> ret = new HashMap<>();
1061
1369
  ret.put("version", version);
@@ -1097,11 +1405,11 @@ public class CapgoUpdater {
1097
1405
  }
1098
1406
 
1099
1407
  public void cleanupDeltaCache(final Thread threadToCheck) {
1100
- if (this.activity == null) {
1408
+ if (this.context() == null) {
1101
1409
  logger.warn("Activity is null, skipping delta cache cleanup");
1102
1410
  return;
1103
1411
  }
1104
- final File cacheFolder = new File(this.activity.getCacheDir(), "capgo_downloads");
1412
+ final File cacheFolder = new File(this.context().getCacheDir(), "capgo_downloads");
1105
1413
  if (!cacheFolder.exists()) {
1106
1414
  return;
1107
1415
  }
@@ -1363,21 +1671,6 @@ public class CapgoUpdater {
1363
1671
  return config == null ? null : config.label;
1364
1672
  }
1365
1673
 
1366
- private String readAssetAsString(final String assetPath) throws IOException {
1367
- final StringBuilder buffer = new StringBuilder();
1368
- try (
1369
- final BufferedReader reader = new BufferedReader(
1370
- new InputStreamReader(this.activity.getAssets().open(assetPath), StandardCharsets.UTF_8)
1371
- )
1372
- ) {
1373
- String line;
1374
- while ((line = reader.readLine()) != null) {
1375
- buffer.append(line).append('\n');
1376
- }
1377
- }
1378
- return buffer.toString();
1379
- }
1380
-
1381
1674
  private void copyFileAtomically(final File source, final File dest) throws IOException {
1382
1675
  final File parent = dest.getParentFile();
1383
1676
  if (parent != null && !parent.exists() && !parent.mkdirs()) {
@@ -1405,7 +1698,7 @@ public class CapgoUpdater {
1405
1698
  }
1406
1699
 
1407
1700
  private void syncBackgroundRunnerScriptFromBundle(final File bundle, final BackgroundRunnerWorkConfig config) {
1408
- if (this.activity == null || bundle == null || config == null || config.src == null || config.src.isEmpty()) {
1701
+ if (this.context() == null || bundle == null || config == null || config.src == null || config.src.isEmpty()) {
1409
1702
  return;
1410
1703
  }
1411
1704
 
@@ -1419,7 +1712,7 @@ public class CapgoUpdater {
1419
1712
  return;
1420
1713
  }
1421
1714
 
1422
- final File publicDir = new File(this.activity.getFilesDir(), "public");
1715
+ final File publicDir = new File(this.context().getFilesDir(), "public");
1423
1716
  final File dest = resolvePathInsideDirectory(publicDir, config.src);
1424
1717
  this.copyFileAtomically(source, dest);
1425
1718
  logger.info("Synced Background Runner script into native public storage before bundle switch.");
@@ -1430,13 +1723,15 @@ public class CapgoUpdater {
1430
1723
  }
1431
1724
 
1432
1725
  private void resetBackgroundRunnerWorkForBundleSwitch(final File bundle) {
1433
- if (this.activity == null) {
1726
+ if (this.context() == null) {
1434
1727
  return;
1435
1728
  }
1436
1729
 
1437
1730
  final BackgroundRunnerWorkConfig config;
1438
1731
  try {
1439
- config = getBackgroundRunnerWorkConfigFromConfig(this.readAssetAsString(CAPACITOR_CONFIG_ASSET));
1732
+ config = getBackgroundRunnerWorkConfigFromConfig(
1733
+ InternalUtils.readAssetAsString(this.context(), InternalUtils.CAPACITOR_CONFIG_ASSET)
1734
+ );
1440
1735
  } catch (IOException ignored) {
1441
1736
  return;
1442
1737
  }
@@ -1446,7 +1741,7 @@ public class CapgoUpdater {
1446
1741
  }
1447
1742
 
1448
1743
  try {
1449
- final WorkManager workManager = WorkManager.getInstance(this.activity.getApplicationContext());
1744
+ final WorkManager workManager = WorkManager.getInstance(this.context().getApplicationContext());
1450
1745
  workManager.cancelUniqueWork(config.label);
1451
1746
  workManager.cancelAllWorkByTag(config.label);
1452
1747
  logger.info("Cancelled Background Runner work before bundle switch.");
@@ -1476,7 +1771,7 @@ public class CapgoUpdater {
1476
1771
  .putString("event", config.event)
1477
1772
  .build();
1478
1773
  final Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
1479
- final WorkManager workManager = WorkManager.getInstance(this.activity.getApplicationContext());
1774
+ final WorkManager workManager = WorkManager.getInstance(this.context().getApplicationContext());
1480
1775
 
1481
1776
  if (!config.repeat) {
1482
1777
  final OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(workerClass)
@@ -1546,7 +1841,7 @@ public class CapgoUpdater {
1546
1841
  downloadBackground(url, version, sessionKey, checksum, manifest, true);
1547
1842
  }
1548
1843
 
1549
- public void downloadBackground(
1844
+ public String downloadBackground(
1550
1845
  final String url,
1551
1846
  final String version,
1552
1847
  final String sessionKey,
@@ -1561,34 +1856,45 @@ public class CapgoUpdater {
1561
1856
  }
1562
1857
  } catch (final IOException e) {
1563
1858
  logger.error("Download blocked: " + e.getMessage());
1564
- return;
1859
+ return null;
1565
1860
  }
1566
1861
  if (!this.runDownloadGateQuiet()) {
1567
- return;
1862
+ return null;
1568
1863
  }
1569
1864
  final String id = this.randomString();
1570
1865
 
1571
1866
  // Check if version is already downloading, but allow retry if previous download failed
1572
- if (this.activity != null && DownloadWorkerManager.isVersionDownloading(this.activity, version)) {
1867
+ if (this.context() != null && DownloadWorkerManager.isVersionDownloading(this.context(), version)) {
1573
1868
  // Check if there's an existing bundle with error status that we can retry
1574
1869
  BundleInfo existingBundle = this.getBundleInfoByName(version);
1575
1870
  if (existingBundle != null && existingBundle.isErrorStatus()) {
1576
1871
  // Cancel the failed download and allow retry
1577
- if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, version)) {
1872
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), version)) {
1578
1873
  logger.error("Failed to cancel previous download before retry");
1579
- return;
1874
+ return null;
1580
1875
  }
1581
1876
  logger.info("Retrying failed download for version: " + version);
1582
1877
  } else if (shouldRestartOrphanedDownload(observedDownloadVersions.contains(version))) {
1583
1878
  // Left over from a killed process: nothing would finish it or release the launch, so start over.
1584
- if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, version)) {
1879
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), version)) {
1585
1880
  logger.error("Failed to cancel orphaned download before restarting it");
1586
- return;
1881
+ return null;
1882
+ }
1883
+ BundleInfo orphanedBundle = null;
1884
+ for (final BundleInfo info : this.list(true)) {
1885
+ if (info != null && info.getStatus() == BundleStatus.DOWNLOADING && version.equals(info.getVersionName())) {
1886
+ orphanedBundle = info;
1887
+ break;
1888
+ }
1889
+ }
1890
+ if (orphanedBundle != null) {
1891
+ this.cleanupManifestStagingAfterDownloadCancelled(orphanedBundle.getId());
1892
+ this.saveBundleInfo(orphanedBundle.getId(), orphanedBundle.setStatus(BundleStatus.ERROR));
1587
1893
  }
1588
1894
  logger.info("Restarting download orphaned by a previous process for version: " + version);
1589
1895
  } else {
1590
1896
  logger.info("Version already downloading: " + version);
1591
- return;
1897
+ return null;
1592
1898
  }
1593
1899
  }
1594
1900
 
@@ -1596,7 +1902,9 @@ public class CapgoUpdater {
1596
1902
  this.notifyDownload(id, 0);
1597
1903
  this.notifyDownload(id, 5);
1598
1904
 
1599
- this.download(id, url, this.randomString(), version, sessionKey, checksum, manifest, setNext);
1905
+ final String dest = manifest != null ? this.manifestStagingDest() : this.randomString();
1906
+ this.download(id, url, dest, version, sessionKey, checksum, manifest, setNext);
1907
+ return id;
1600
1908
  }
1601
1909
 
1602
1910
  public BundleInfo download(final String url, final String version, final String sessionKey, final String checksum) throws IOException {
@@ -1629,7 +1937,8 @@ public class CapgoUpdater {
1629
1937
  try {
1630
1938
  BundleInfo result = downloadFuture.get();
1631
1939
  if (result.isErrorStatus()) {
1632
- throw new IOException("Download failed with status: " + result.getStatus());
1940
+ // The download observer already emitted downloadFailed and its stats.
1941
+ throw new ReportedDownloadFailureException("Download failed with status: " + result.getStatus());
1633
1942
  }
1634
1943
  return result;
1635
1944
  } catch (Exception e) {
@@ -1672,7 +1981,7 @@ public class CapgoUpdater {
1672
1981
  saveBundleInfo(id, new BundleInfo(id, version, BundleStatus.DOWNLOADING, new Date(System.currentTimeMillis()), ""));
1673
1982
  this.notifyDownload(id, 0);
1674
1983
  this.notifyDownload(id, 5);
1675
- final String dest = this.randomString();
1984
+ final String dest = this.manifestStagingDest();
1676
1985
 
1677
1986
  // Create a CompletableFuture to track download completion
1678
1987
  CompletableFuture<BundleInfo> downloadFuture = new CompletableFuture<>();
@@ -1685,7 +1994,8 @@ public class CapgoUpdater {
1685
1994
  try {
1686
1995
  BundleInfo result = downloadFuture.get();
1687
1996
  if (result.isErrorStatus()) {
1688
- throw new IOException("Download failed with status: " + result.getStatus());
1997
+ // The download observer already emitted downloadFailed and its stats.
1998
+ throw new ReportedDownloadFailureException("Download failed with status: " + result.getStatus());
1689
1999
  }
1690
2000
  return result;
1691
2001
  } catch (Exception e) {
@@ -1786,8 +2096,8 @@ public class CapgoUpdater {
1786
2096
  }
1787
2097
 
1788
2098
  // Cancel download for this version if active
1789
- if (cancelActiveDownload && this.activity != null) {
1790
- if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, deleted.getVersionName())) {
2099
+ if (cancelActiveDownload && this.context() != null) {
2100
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), deleted.getVersionName())) {
1791
2101
  logger.error("Failed to cancel active download before delete");
1792
2102
  return false;
1793
2103
  }
@@ -1980,8 +2290,8 @@ public class CapgoUpdater {
1980
2290
  }
1981
2291
 
1982
2292
  void finalizeResetTransition(final String previousBundleName, final boolean internal) {
1983
- if (this.activity != null) {
1984
- DownloadWorkerManager.cancelAllDownloads(this.activity);
2293
+ if (this.context() != null) {
2294
+ DownloadWorkerManager.cancelAllDownloads(this.context());
1985
2295
  }
1986
2296
  if (!internal) {
1987
2297
  this.sendStats("reset", this.getCurrentBundle().getVersionName(), previousBundleName);
@@ -2159,8 +2469,8 @@ public class CapgoUpdater {
2159
2469
  final String asyncPreviousFallbackId = previousFallbackId;
2160
2470
  final String asyncPreviousFallbackVersion = previousFallbackVersion;
2161
2471
  io.execute(() -> {
2162
- if (this.activity != null) {
2163
- if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.activity, asyncPreviousFallbackVersion)) {
2472
+ if (this.context() != null) {
2473
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), asyncPreviousFallbackVersion)) {
2164
2474
  logger.error("Failed to cancel previous version download before delete");
2165
2475
  return;
2166
2476
  }
@@ -3113,7 +3423,7 @@ public class CapgoUpdater {
3113
3423
  if (statsQueue.size() >= MAX_PENDING_STATS) {
3114
3424
  break;
3115
3425
  }
3116
- statsQueue.add(new QueuedStatsEvent(arr.getJSONObject(i), null));
3426
+ statsQueue.add(new QueuedStatsEvent(arr.getJSONObject(i), null, true));
3117
3427
  }
3118
3428
  }
3119
3429
  if (backup.exists() && !backup.delete()) {
@@ -3135,6 +3445,147 @@ public class CapgoUpdater {
3135
3445
  }
3136
3446
  }
3137
3447
 
3448
+ /** Makes this instance the stats file owner and adopts events handed over before it loaded. */
3449
+ public void claimStatsOwnership() {
3450
+ final List<JSONObject> adopted;
3451
+ synchronized (statsOwnerLock) {
3452
+ statsOwner = this;
3453
+ adopted = new ArrayList<>(orphanedStats);
3454
+ orphanedStats.clear();
3455
+ }
3456
+ if (!adoptPendingStats(adopted)) {
3457
+ parkOrphanedStats(adopted);
3458
+ }
3459
+ }
3460
+
3461
+ public void releaseStatsOwnership() {
3462
+ synchronized (statsOwnerLock) {
3463
+ if (statsOwner == this) {
3464
+ statsOwner = null;
3465
+ }
3466
+ }
3467
+ }
3468
+
3469
+ /** Moves this instance's unsent events to the stats file owner (or parks them until one claims). */
3470
+ void handOverPendingStats() {
3471
+ // Stop first so a flush finishing later cannot requeue or persist what we hand over.
3472
+ statsStopped.set(true);
3473
+ final CapgoUpdater owner;
3474
+ synchronized (statsOwnerLock) {
3475
+ owner = statsOwner == this ? null : statsOwner;
3476
+ }
3477
+ final List<JSONObject> events = new ArrayList<>();
3478
+ synchronized (statsQueue) {
3479
+ collectHandoverEvents(statsInFlight, events, owner);
3480
+ statsInFlight.clear();
3481
+ collectHandoverEvents(statsQueue, events, owner);
3482
+ statsQueue.clear();
3483
+ }
3484
+ if (events.isEmpty()) {
3485
+ return;
3486
+ }
3487
+ // adoptPendingStats persists; never call it while holding statsOwnerLock (lock order).
3488
+ if (owner != null && owner.adoptPendingStats(events)) {
3489
+ return;
3490
+ }
3491
+ List<JSONObject> retryEvents = null;
3492
+ CapgoUpdater retryOwner = null;
3493
+ synchronized (statsOwnerLock) {
3494
+ addOrphanedStats(events);
3495
+ retryOwner = statsOwner == this ? null : statsOwner;
3496
+ if (retryOwner != null && !orphanedStats.isEmpty()) {
3497
+ retryEvents = new ArrayList<>(orphanedStats);
3498
+ orphanedStats.clear();
3499
+ }
3500
+ }
3501
+ if (retryOwner != null && retryEvents != null) {
3502
+ if (retryOwner.adoptPendingStats(retryEvents)) {
3503
+ return;
3504
+ }
3505
+ parkOrphanedStats(retryEvents);
3506
+ }
3507
+ }
3508
+
3509
+ private void collectHandoverEvents(final List<QueuedStatsEvent> source, final List<JSONObject> events, final CapgoUpdater owner) {
3510
+ for (final QueuedStatsEvent queued : source) {
3511
+ if (shouldHandOverQueuedEvent(queued, owner)) {
3512
+ events.add(queued.event);
3513
+ }
3514
+ }
3515
+ }
3516
+
3517
+ /**
3518
+ * Restored file events are not re-sent to an owner that shares the same pending-stats path
3519
+ * (the owner already loaded them from disk). They are still handed over when the paths differ.
3520
+ */
3521
+ private boolean shouldHandOverQueuedEvent(final QueuedStatsEvent queued, final CapgoUpdater owner) {
3522
+ if (!queued.restored) {
3523
+ return true;
3524
+ }
3525
+ if (owner == null) {
3526
+ return true;
3527
+ }
3528
+ return !sharesPendingStatsFileWith(owner);
3529
+ }
3530
+
3531
+ private boolean sharesPendingStatsFileWith(final CapgoUpdater other) {
3532
+ final File mine = pendingStatsFile();
3533
+ final File theirs = other.pendingStatsFile();
3534
+ return mine != null && theirs != null && mine.getAbsolutePath().equals(theirs.getAbsolutePath());
3535
+ }
3536
+
3537
+ private static void addOrphanedStats(final List<JSONObject> events) {
3538
+ orphanedStats.addAll(events);
3539
+ while (orphanedStats.size() > MAX_PENDING_STATS) {
3540
+ orphanedStats.remove(0);
3541
+ }
3542
+ }
3543
+
3544
+ private static void parkOrphanedStats(final List<JSONObject> events) {
3545
+ synchronized (statsOwnerLock) {
3546
+ addOrphanedStats(events);
3547
+ }
3548
+ }
3549
+
3550
+ /** Returns false (keeping nothing) when this instance has stopped and can no longer send the events. */
3551
+ private boolean adoptPendingStats(final List<JSONObject> events) {
3552
+ if (events.isEmpty()) {
3553
+ return true;
3554
+ }
3555
+ final List<QueuedStatsEvent> displaced = new ArrayList<>();
3556
+ synchronized (statsQueue) {
3557
+ if (statsStopped.get()) {
3558
+ return false;
3559
+ }
3560
+ for (final JSONObject event : events) {
3561
+ while (statsQueue.size() >= MAX_PENDING_STATS) {
3562
+ displaced.add(0, statsQueue.remove(0));
3563
+ }
3564
+ statsQueue.add(new QueuedStatsEvent(event, null));
3565
+ }
3566
+ }
3567
+ synchronized (statsOwnerLock) {
3568
+ if (statsOwner != null && statsOwner != this) {
3569
+ rollbackAdoptedEvents(events.size(), displaced);
3570
+ return false;
3571
+ }
3572
+ }
3573
+ persistStatsQueue();
3574
+ ensureStatsTimerStarted();
3575
+ return true;
3576
+ }
3577
+
3578
+ private void rollbackAdoptedEvents(final int adoptedCount, final List<QueuedStatsEvent> displaced) {
3579
+ synchronized (statsQueue) {
3580
+ for (int removed = 0; removed < adoptedCount && !statsQueue.isEmpty(); removed++) {
3581
+ statsQueue.remove(statsQueue.size() - 1);
3582
+ }
3583
+ for (int i = 0; i < displaced.size(); i++) {
3584
+ statsQueue.add(i, displaced.get(i));
3585
+ }
3586
+ }
3587
+ }
3588
+
3138
3589
  int pendingStatsCount() {
3139
3590
  return statsQueue.size();
3140
3591
  }
@@ -3161,6 +3612,11 @@ public class CapgoUpdater {
3161
3612
  return;
3162
3613
  }
3163
3614
  synchronized (pendingStatsPersistLock) {
3615
+ synchronized (statsOwnerLock) {
3616
+ if (statsOwner != null && statsOwner != this) {
3617
+ return;
3618
+ }
3619
+ }
3164
3620
  if (statsStopped.get() && !force) {
3165
3621
  return;
3166
3622
  }
@@ -3542,6 +3998,16 @@ public class CapgoUpdater {
3542
3998
  return this.getBundleInfo(id);
3543
3999
  }
3544
4000
 
4001
+ public boolean clearNextBundleIfCurrent() {
4002
+ final BundleInfo next = this.getNextBundle();
4003
+ if (next == null || !next.getId().equals(this.getCurrentBundle().getId())) {
4004
+ return false;
4005
+ }
4006
+ logger.info("Next bundle " + next.getId() + " is already the current bundle. Clearing next.");
4007
+ this.setNextBundle(null);
4008
+ return true;
4009
+ }
4010
+
3545
4011
  public BundleInfo getPreviewFallbackBundle() {
3546
4012
  final String id = this.prefs.getString(PREVIEW_FALLBACK_VERSION, null);
3547
4013
  if (id == null) return null;
@@ -3599,6 +4065,14 @@ public class CapgoUpdater {
3599
4065
  * Should be called when the plugin is destroyed to prevent resource leaks.
3600
4066
  */
3601
4067
  public void shutdown() {
4068
+ shutdown(true);
4069
+ }
4070
+
4071
+ /**
4072
+ * @param persistStats false when another live instance owns the stats file (headless worker
4073
+ * handing over to the plugin): writing this instance's queue would replace the newer file.
4074
+ */
4075
+ public void shutdown(final boolean persistStats) {
3602
4076
  statsStopped.set(true);
3603
4077
  // Cancel the scheduled task
3604
4078
  if (statsFlushTask != null) {
@@ -3607,7 +4081,9 @@ public class CapgoUpdater {
3607
4081
  }
3608
4082
 
3609
4083
  // Write once, then ignore later callbacks so they cannot delete a newer instance's file.
3610
- persistStatsQueue(true);
4084
+ if (persistStats) {
4085
+ persistStatsQueue(true);
4086
+ }
3611
4087
 
3612
4088
  // Shutdown the scheduler
3613
4089
  statsScheduler.shutdown();