@capgo/capacitor-updater 6.51.23 → 6.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 (29) hide show
  1. package/CapgoCapacitorUpdater.podspec +0 -3
  2. package/Package.swift +3 -11
  3. package/README.md +201 -66
  4. package/android/build.gradle +2 -3
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +593 -176
  6. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +775 -162
  7. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +2 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +226 -106
  9. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +107 -30
  10. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +325 -0
  11. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +63 -4
  12. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  14. package/dist/docs.json +394 -27
  15. package/dist/esm/definitions.d.ts +220 -7
  16. package/dist/esm/definitions.js.map +1 -1
  17. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +472 -144
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  20. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +392 -82
  21. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +2 -1
  22. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +204 -93
  23. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +75 -5
  24. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  25. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +53 -0
  26. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +5 -2
  27. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  28. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  29. package/package.json +7 -3
@@ -31,6 +31,7 @@ import com.getcapacitor.JSArray;
31
31
  import com.getcapacitor.JSObject;
32
32
  import com.getcapacitor.Plugin;
33
33
  import com.getcapacitor.PluginCall;
34
+ import com.getcapacitor.PluginConfig;
34
35
  import com.getcapacitor.PluginHandle;
35
36
  import com.getcapacitor.PluginMethod;
36
37
  import com.getcapacitor.PluginResult;
@@ -48,12 +49,10 @@ import com.google.android.play.core.install.InstallStateUpdatedListener;
48
49
  import com.google.android.play.core.install.model.AppUpdateType;
49
50
  import com.google.android.play.core.install.model.InstallStatus;
50
51
  import com.google.android.play.core.install.model.UpdateAvailability;
51
- import io.github.g00fy2.versioncompare.Version;
52
52
  import java.io.ByteArrayOutputStream;
53
53
  import java.io.File;
54
54
  import java.io.IOException;
55
55
  import java.io.InputStream;
56
- import java.net.HttpURLConnection;
57
56
  import java.net.MalformedURLException;
58
57
  import java.net.URL;
59
58
  import java.nio.charset.StandardCharsets;
@@ -75,7 +74,11 @@ import java.util.concurrent.Semaphore;
75
74
  import java.util.concurrent.TimeUnit;
76
75
  import java.util.concurrent.TimeoutException;
77
76
  import java.util.concurrent.atomic.AtomicReference;
78
- // Removed OkHttpClient and Protocol imports - using shared client in DownloadService instead
77
+ import okhttp3.HttpUrl;
78
+ import okhttp3.OkHttpClient;
79
+ import okhttp3.Request;
80
+ import okhttp3.Response;
81
+ import okhttp3.ResponseBody;
79
82
  import org.json.JSONArray;
80
83
  import org.json.JSONException;
81
84
  import org.json.JSONObject;
@@ -93,18 +96,27 @@ public class CapacitorUpdaterPlugin extends Plugin {
93
96
  private static final String AUTO_UPDATE_MODE_ALWAYS = "always";
94
97
  private static final String AUTO_UPDATE_MODE_ONLY_DOWNLOAD = "onlyDownload";
95
98
 
99
+ // Stats action for a failed update check (offline, timeout, unreadable response, 429 block).
100
+ // Nothing was downloaded, so it is reported apart from download_fail.
101
+ static final String UPDATE_CHECK_ERROR_ACTION = "update_check_error";
102
+
103
+ // Single listener that receives every plugin event as { type, data }.
104
+ static final String UPDATER_EVENT = "updaterEvent";
105
+ // Deprecated alias emitted next to breakingAvailable; not forwarded to avoid duplicates.
106
+ private static final String DEPRECATED_MAJOR_AVAILABLE_EVENT = "majorAvailable";
107
+
96
108
  private Logger logger;
97
109
 
98
- private static final String updateUrlDefault = "https://plugin.capgo.app/updates";
99
- private static final String statsUrlDefault = "https://plugin.capgo.app/stats";
100
- private static final String channelUrlDefault = "https://plugin.capgo.app/channel_self";
110
+ static final String updateUrlDefault = "https://plugin.capgo.app/updates";
111
+ static final String statsUrlDefault = "https://plugin.capgo.app/stats";
112
+ static final String channelUrlDefault = "https://plugin.capgo.app/channel_self";
101
113
  private static final String KEEP_URL_FLAG_KEY = "__capgo_keep_url_path_after_reload";
102
- private static final String CUSTOM_ID_PREF_KEY = "CapacitorUpdater.customId";
103
- private static final String UPDATE_URL_PREF_KEY = "CapacitorUpdater.updateUrl";
104
- private static final String STATS_URL_PREF_KEY = "CapacitorUpdater.statsUrl";
105
- private static final String CHANNEL_URL_PREF_KEY = "CapacitorUpdater.channelUrl";
106
- private static final String DEFAULT_CHANNEL_PREF_KEY = "CapacitorUpdater.defaultChannel";
107
- private static final String PREVIEW_SESSION_PREF_KEY = "CapacitorUpdater.previewSession";
114
+ static final String CUSTOM_ID_PREF_KEY = "CapacitorUpdater.customId";
115
+ static final String UPDATE_URL_PREF_KEY = "CapacitorUpdater.updateUrl";
116
+ static final String STATS_URL_PREF_KEY = "CapacitorUpdater.statsUrl";
117
+ static final String CHANNEL_URL_PREF_KEY = "CapacitorUpdater.channelUrl";
118
+ static final String DEFAULT_CHANNEL_PREF_KEY = "CapacitorUpdater.defaultChannel";
119
+ static final String PREVIEW_SESSION_PREF_KEY = "CapacitorUpdater.previewSession";
108
120
  private static final String DEFAULT_CHANNEL_INSTALL_MARKER_PREF_KEY = "CapacitorUpdater.defaultChannelInstallMarkerCreated";
109
121
  private static final String DEFAULT_CHANNEL_INSTALL_MARKER_FILE = "CapacitorUpdater.defaultChannelInstallMarker";
110
122
  private static final String PREVIEW_PREVIOUS_SHAKE_MENU_PREF_KEY = "CapacitorUpdater.previewPreviousShakeMenu";
@@ -146,7 +158,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
146
158
  static final int APPLICATION_EXIT_REASON_USER_REQUESTED = 10;
147
159
  static final int APPLICATION_EXIT_REASON_DEPENDENCY_DIED = 12;
148
160
 
149
- private final String pluginVersion = "6.51.23";
161
+ static final String PLUGIN_VERSION = "8.52.1";
162
+ // Set while a plugin instance (with its bridge) runs in this process. The headless update
163
+ // check then leaves installing to that instance instead of swapping bundles under it.
164
+ static volatile boolean instanceLoaded = false;
165
+ private final String pluginVersion = PLUGIN_VERSION;
150
166
  private static final String DELAY_CONDITION_PREFERENCES = "";
151
167
 
152
168
  private SharedPreferences.Editor editor;
@@ -220,8 +236,15 @@ public class CapacitorUpdaterPlugin extends Plugin {
220
236
 
221
237
  private volatile Thread backgroundDownloadTask;
222
238
  private volatile Thread appReadyCheck;
239
+ // Between appMovedToBackground and appMovedToForeground. Android freezes backgrounded apps, so the
240
+ // page cannot call notifyAppReady until the next foreground, which arms a fresh rollback check.
241
+ private volatile boolean appInBackground = false;
223
242
  // When true, sendReadyToJs should wait for notifyAppReady before hiding splash.
224
243
  private volatile boolean pendingNotifyAppReadyWait = false;
244
+ // Armed only after a reload. The next document stamps this generation into notifyAppReady.
245
+ private final Object readyGuardLock = new Object();
246
+ private volatile int readyGeneration = 0;
247
+ private volatile boolean readyGuardArmed = false;
225
248
  private volatile int pendingNotifyAppReadyPhase = -1;
226
249
  private volatile long downloadStartTimeMs = 0;
227
250
  private static final long DOWNLOAD_TIMEOUT_MS = 600000; // 10 minute timeout
@@ -241,6 +264,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
241
264
  private volatile boolean defaultChannelCleanupMustRetry = false;
242
265
 
243
266
  private int lastNotifiedStatPercent = 0;
267
+ private String lastNotifiedStatBundleId = null;
268
+ private final Object downloadStatLock = new Object();
244
269
 
245
270
  private DelayUpdateUtils delayUpdateUtils;
246
271
 
@@ -292,8 +317,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
292
317
  private AppUpdateManager appUpdateManager;
293
318
  private PluginCall pendingAppUpdateCall;
294
319
  private AppUpdateInfo cachedAppUpdateInfo;
295
- private static final int APP_UPDATE_REQUEST_CODE = 9001;
320
+ static final int APP_UPDATE_REQUEST_CODE = 9001;
296
321
  private InstallStateUpdatedListener installStateUpdatedListener;
322
+ private NativeUpdatePrompt nativeUpdatePrompt;
297
323
 
298
324
  private PackageInfo getCurrentPackageInfo() throws PackageManager.NameNotFoundException {
299
325
  final PackageManager packageManager = this.getContext().getPackageManager();
@@ -315,28 +341,21 @@ public class CapacitorUpdaterPlugin extends Plugin {
315
341
  for (final String eventName : BREAKING_EVENT_NAMES) {
316
342
  final JSObject payload = new JSObject();
317
343
  payload.put("version", version);
318
- CapacitorUpdaterPlugin.this.notifyListeners(eventName, payload);
344
+ CapacitorUpdaterPlugin.this.notifyListeners(eventName, payload, false);
319
345
  }
320
346
  }
321
347
 
322
348
  private boolean shouldNotifyBreakingEvents(final JSObject response) {
323
- if (response == null) {
324
- return false;
325
- }
326
-
327
- if (response.optBoolean("breaking", false)) {
328
- return true;
329
- }
330
-
331
- final String error = response.optString("error", "");
332
- final String message = response.optString("message", "");
333
- return "disable_auto_update_to_major".equals(error) || "store_update_required".equals(message);
349
+ return NativeUpdatePrompt.isNativeStoreUpdateBlock(response);
334
350
  }
335
351
 
336
352
  private void notifyBreakingEventsIfNeeded(final JSObject response, final String version) {
337
353
  if (shouldNotifyBreakingEvents(response)) {
338
354
  notifyBreakingEvents(version);
339
355
  }
356
+ if (this.nativeUpdatePrompt != null) {
357
+ this.nativeUpdatePrompt.maybeShowForUpdateBlock(response);
358
+ }
340
359
  }
341
360
 
342
361
  private void persistLastFailedBundle(BundleInfo bundle) {
@@ -679,9 +698,46 @@ public class CapacitorUpdaterPlugin extends Plugin {
679
698
  return startNewThread(function, 0);
680
699
  }
681
700
 
701
+ static Map<String, String> updateCheckErrorMetadata(final String error, final int statusCode) {
702
+ final Map<String, String> metadata = new HashMap<>();
703
+ metadata.put("error", error == null || error.isEmpty() ? "unknown" : error);
704
+ if (statusCode > 0) {
705
+ metadata.put("status_code", String.valueOf(statusCode));
706
+ }
707
+ return metadata;
708
+ }
709
+
710
+ static JSObject updaterEventPayload(final String eventName, final JSObject data) {
711
+ final JSObject payload = new JSObject();
712
+ payload.put("type", eventName);
713
+ payload.put("data", data != null ? data : new JSObject());
714
+ return payload;
715
+ }
716
+
717
+ static boolean shouldForwardToUpdaterEvent(final String eventName) {
718
+ return !UPDATER_EVENT.equals(eventName) && !DEPRECATED_MAJOR_AVAILABLE_EVENT.equals(eventName);
719
+ }
720
+
721
+ // Capacitor replays retained events through this overload when a listener attaches. They were
722
+ // already forwarded to updaterEvent when emitted, so skip forwarding here. Plugin code must emit
723
+ // through the three-argument overload.
724
+ @Override
725
+ protected void notifyListeners(final String eventName, final JSObject data) {
726
+ super.notifyListeners(eventName, data, false);
727
+ }
728
+
729
+ @Override
730
+ protected void notifyListeners(final String eventName, final JSObject data, final boolean retainUntilConsumed) {
731
+ super.notifyListeners(eventName, data, retainUntilConsumed);
732
+ if (shouldForwardToUpdaterEvent(eventName)) {
733
+ super.notifyListeners(UPDATER_EVENT, updaterEventPayload(eventName, data), retainUntilConsumed);
734
+ }
735
+ }
736
+
682
737
  @Override
683
738
  public void load() {
684
739
  super.load();
740
+ instanceLoaded = true;
685
741
 
686
742
  // Initialize logger with osLogging config
687
743
  // Default to true for both platforms to enable system logging by default
@@ -710,11 +766,21 @@ public class CapacitorUpdaterPlugin extends Plugin {
710
766
  CapacitorUpdaterPlugin.this.scheduleDirectUpdateFinish(latest);
711
767
  }
712
768
 
769
+ @Override
770
+ public void backgroundDownloadSettled(final BundleInfo bundle, final String status) {
771
+ CapacitorUpdaterPlugin.this.emitLaunchDownloadReady(bundle, status);
772
+ }
773
+
774
+ @Override
775
+ public void nextBundleReady(final BundleInfo bundle) {
776
+ CapacitorUpdaterPlugin.this.installNextIfInBackground();
777
+ }
778
+
713
779
  @Override
714
780
  public void notifyListeners(final String id, final Map<String, Object> res) {
715
781
  if (activity != null) {
716
782
  activity.runOnUiThread(() -> {
717
- CapacitorUpdaterPlugin.this.notifyListeners(id, InternalUtils.mapToJSObject(res));
783
+ CapacitorUpdaterPlugin.this.notifyListeners(id, InternalUtils.mapToJSObject(res), false);
718
784
  });
719
785
  } else {
720
786
  logger.warn("notifyListeners: Activity is null, skipping notification for event: " + id);
@@ -723,11 +789,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
723
789
  };
724
790
  final PackageInfo pInfo = this.getCurrentPackageInfo();
725
791
  this.implementation.activity = this.getActivity();
792
+ this.implementation.appContext = this.getContext().getApplicationContext();
726
793
  this.implementation.versionBuild = this.getConfig().getString("version", pInfo.versionName);
727
794
  this.implementation.CAP_SERVER_PATH = WebView.CAP_SERVER_PATH;
728
795
  this.implementation.pluginVersion = this.pluginVersion;
729
796
  this.implementation.versionCode = this.getVersionCode(pInfo);
730
- // Removed unused OkHttpClient creation - using shared client in DownloadService instead
731
797
  this.currentVersionNative = new Version(this.getConfig().getString("version", pInfo.versionName));
732
798
  this.currentBuildVersion = this.getVersionCode(pInfo);
733
799
  this.delayUpdateUtils = new DelayUpdateUtils(this.prefs, this.editor, this.currentVersionNative, logger);
@@ -847,6 +913,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
847
913
  // Use DeviceIdHelper to get or create device ID that persists across reinstalls
848
914
  this.implementation.deviceID = DeviceIdHelper.getOrCreateDeviceId(this.getContext(), this.prefs);
849
915
  this.implementation.restorePendingStats();
916
+ this.implementation.claimStatsOwnership();
850
917
 
851
918
  // Update User-Agent for shared OkHttpClient with OS version
852
919
  DownloadService.updateUserAgent(this.implementation.appId, this.pluginVersion, this.implementation.versionOs);
@@ -860,7 +927,6 @@ public class CapacitorUpdaterPlugin extends Plugin {
860
927
  }
861
928
  logger.info("init for device " + this.implementation.deviceID);
862
929
  logger.info("version native " + this.currentVersionNative.getOriginalString());
863
- this.reportAppLaunchStart();
864
930
  this.autoDeleteFailed = this.getConfig().getBoolean("autoDeleteFailed", true);
865
931
  this.autoDeletePrevious = this.getConfig().getBoolean("autoDeletePrevious", true);
866
932
  this.updateUrl = this.getConfig().getString("updateUrl", updateUrlDefault);
@@ -886,9 +952,46 @@ public class CapacitorUpdaterPlugin extends Plugin {
886
952
  long responseTimeoutMillis = responseTimeoutSeconds > 0 ? (long) responseTimeoutSeconds * 1000L : 20_000L;
887
953
  this.implementation.timeout = (int) Math.min(Integer.MAX_VALUE, responseTimeoutMillis);
888
954
  DownloadService.applyHttpTimeouts(this.implementation.timeout);
955
+ DownloadService.setAllowHttpsToHttpRedirect(this.getConfig().getBoolean("allowHttpsToHttpRedirect", false));
889
956
  this.shakeMenuEnabled = this.getConfig().getBoolean("shakeMenu", false);
890
957
  this.shakeChannelSelectorEnabled = this.getConfig().getBoolean("allowShakeChannelSelector", false);
891
958
  this.shakeMenuGesture = normalizedShakeMenuGesture(this.getConfig().getString("shakeMenuGesture", SHAKE_MENU_GESTURE_SHAKE));
959
+ this.nativeUpdatePrompt = new NativeUpdatePrompt(
960
+ this.getConfig(),
961
+ this.prefs,
962
+ this.logger,
963
+ new NativeUpdatePrompt.NativeUpdatePromptHost() {
964
+ @Override
965
+ public Activity getActivity() {
966
+ return CapacitorUpdaterPlugin.this.getActivity();
967
+ }
968
+
969
+ @Override
970
+ public String getNativeBuildVersion() {
971
+ return CapacitorUpdaterPlugin.this.currentBuildVersion;
972
+ }
973
+
974
+ @Override
975
+ public AppUpdateManager getAppUpdateManager() {
976
+ return CapacitorUpdaterPlugin.this.getAppUpdateManager();
977
+ }
978
+
979
+ @Override
980
+ public AppUpdateInfo getCachedAppUpdateInfo() {
981
+ return CapacitorUpdaterPlugin.this.cachedAppUpdateInfo;
982
+ }
983
+
984
+ @Override
985
+ public void setCachedAppUpdateInfo(final AppUpdateInfo info) {
986
+ CapacitorUpdaterPlugin.this.cachedAppUpdateInfo = info;
987
+ }
988
+
989
+ @Override
990
+ public String getPackageNameForStore() {
991
+ return CapacitorUpdaterPlugin.this.getContext().getPackageName();
992
+ }
993
+ }
994
+ );
892
995
  this.previewSessionEnabled = Boolean.TRUE.equals(this.allowPreview) && this.prefs.getBoolean(PREVIEW_SESSION_PREF_KEY, false);
893
996
  if (!Boolean.TRUE.equals(this.allowPreview) && this.prefs.getBoolean(PREVIEW_SESSION_PREF_KEY, false)) {
894
997
  this.clearPreviewSessionBecauseDisabled();
@@ -912,11 +1015,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
912
1015
  // Check if app was recently installed/updated BEFORE cleanupObsoleteVersions updates LatestVersionNative
913
1016
  this.wasRecentlyInstalledOrUpdated = this.checkIfRecentlyInstalledOrUpdated();
914
1017
 
915
- this.implementation.autoReset(this.currentBuildVersion, resetWhenUpdate);
916
- if (nativeBuildVersionChanged) {
917
- this.clearPreviewSessionForNativeBuildChange();
918
- }
919
- this.leavePreviewSessionForLaunchIntentIfNeeded();
1018
+ this.resetStartupBundleAndReportAppLaunchStart(resetWhenUpdate, nativeBuildVersionChanged);
920
1019
  this.reportNativeVersionStatsIfChanged();
921
1020
  this.reportPreviousAppExitReasons();
922
1021
  this.reportPreviousWebViewRenderProcessGone();
@@ -2128,33 +2227,35 @@ public class CapacitorUpdaterPlugin extends Plugin {
2128
2227
  }
2129
2228
 
2130
2229
  private void configureAutoUpdateModeFromConfig() {
2131
- final String configuredMode = this.getConfig().getString("autoUpdate", null);
2230
+ this.autoUpdateMode = autoUpdateModeFromConfig(this.getConfig(), logger);
2231
+ this.autoUpdate = isAutoUpdateModeEnabled(this.autoUpdateMode);
2232
+ this.directUpdateMode = directUpdateModeForAutoUpdateMode(this.autoUpdateMode);
2233
+ this.implementation.directUpdate = isDirectUpdateMode(this.directUpdateMode);
2234
+ }
2235
+
2236
+ /** Resolves autoUpdate (and the legacy directUpdate) from the plugin config. Shared with the headless update check. */
2237
+ static String autoUpdateModeFromConfig(final PluginConfig pluginConfig, final Logger logger) {
2238
+ final String configuredMode = pluginConfig.getString("autoUpdate", null);
2132
2239
  if (configuredMode != null && !configuredMode.isEmpty() && !"true".equals(configuredMode) && !"false".equals(configuredMode)) {
2133
- this.autoUpdateMode = normalizedAutoUpdateMode(configuredMode);
2134
- if (!this.autoUpdateMode.equals(configuredMode)) {
2240
+ final String mode = normalizedAutoUpdateMode(configuredMode);
2241
+ if (!mode.equals(configuredMode) && logger != null) {
2135
2242
  logger.error(
2136
2243
  "Invalid autoUpdate value: \"" +
2137
2244
  configuredMode +
2138
2245
  "\". Supported values are: true, false, \"off\", \"atBackground\", \"atInstall\", \"onLaunch\", \"always\", \"onlyDownload\". Defaulting to \"atBackground\"."
2139
2246
  );
2140
2247
  }
2141
- } else {
2142
- final boolean enabled =
2143
- configuredMode != null
2144
- ? "true".equals(configuredMode)
2145
- : Boolean.TRUE.equals(this.getConfig().getBoolean("autoUpdate", true));
2146
- this.autoUpdateMode = enabled
2147
- ? autoUpdateModeForLegacyDirectUpdateMode(this.resolveLegacyDirectUpdateModeFromConfig())
2148
- : AUTO_UPDATE_MODE_OFF;
2248
+ return mode;
2149
2249
  }
2150
-
2151
- this.autoUpdate = isAutoUpdateModeEnabled(this.autoUpdateMode);
2152
- this.directUpdateMode = directUpdateModeForAutoUpdateMode(this.autoUpdateMode);
2153
- this.implementation.directUpdate = isDirectUpdateMode(this.directUpdateMode);
2250
+ final boolean enabled =
2251
+ configuredMode != null ? "true".equals(configuredMode) : Boolean.TRUE.equals(pluginConfig.getBoolean("autoUpdate", true));
2252
+ return enabled
2253
+ ? autoUpdateModeForLegacyDirectUpdateMode(resolveLegacyDirectUpdateModeFromConfig(pluginConfig, logger))
2254
+ : AUTO_UPDATE_MODE_OFF;
2154
2255
  }
2155
2256
 
2156
- private String resolveLegacyDirectUpdateModeFromConfig() {
2157
- final String directUpdateConfig = this.getConfig().getString("directUpdate", null);
2257
+ private static String resolveLegacyDirectUpdateModeFromConfig(final PluginConfig pluginConfig, final Logger logger) {
2258
+ final String directUpdateConfig = pluginConfig.getString("directUpdate", null);
2158
2259
  if (directUpdateConfig != null) {
2159
2260
  if ("true".equals(directUpdateConfig)) {
2160
2261
  return AUTO_UPDATE_MODE_ALWAYS;
@@ -2162,15 +2263,17 @@ public class CapacitorUpdaterPlugin extends Plugin {
2162
2263
  if ("false".equals(directUpdateConfig) || isDirectUpdateMode(directUpdateConfig)) {
2163
2264
  return directUpdateConfig;
2164
2265
  }
2165
- logger.error(
2166
- "Invalid directUpdate value: \"" +
2167
- directUpdateConfig +
2168
- "\". Supported values are: false, true, \"always\", \"atInstall\", \"onLaunch\". Defaulting to \"false\"."
2169
- );
2266
+ if (logger != null) {
2267
+ logger.error(
2268
+ "Invalid directUpdate value: \"" +
2269
+ directUpdateConfig +
2270
+ "\". Supported values are: false, true, \"always\", \"atInstall\", \"onLaunch\". Defaulting to \"false\"."
2271
+ );
2272
+ }
2170
2273
  return "false";
2171
2274
  }
2172
2275
 
2173
- return Boolean.TRUE.equals(this.getConfig().getBoolean("directUpdate", false)) ? AUTO_UPDATE_MODE_ALWAYS : "false";
2276
+ return Boolean.TRUE.equals(pluginConfig.getBoolean("directUpdate", false)) ? AUTO_UPDATE_MODE_ALWAYS : "false";
2174
2277
  }
2175
2278
 
2176
2279
  static String normalizedAutoUpdateMode(final String value) {
@@ -2332,10 +2435,49 @@ public class CapacitorUpdaterPlugin extends Plugin {
2332
2435
  this.logger = logger;
2333
2436
  }
2334
2437
 
2438
+ void reportAppLaunchStartForTesting() {
2439
+ this.reportAppLaunchStart();
2440
+ }
2441
+
2442
+ void setCurrentBuildVersionForTesting(final String currentBuildVersion) {
2443
+ this.currentBuildVersion = currentBuildVersion;
2444
+ }
2445
+
2446
+ void resetStartupBundleAndReportAppLaunchStartForTesting(final boolean resetWhenUpdate, final boolean nativeBuildVersionChanged) {
2447
+ this.resetStartupBundleAndReportAppLaunchStart(resetWhenUpdate, nativeBuildVersionChanged);
2448
+ }
2449
+
2450
+ private void resetStartupBundleAndReportAppLaunchStart(final boolean resetWhenUpdate, final boolean nativeBuildVersionChanged) {
2451
+ this.implementation.autoReset(this.currentBuildVersion, resetWhenUpdate);
2452
+ if (nativeBuildVersionChanged) {
2453
+ this.clearPreviewSessionForNativeBuildChange();
2454
+ }
2455
+ this.leavePreviewSessionForLaunchIntentIfNeeded();
2456
+ this.reportAppLaunchStart();
2457
+ }
2458
+
2335
2459
  void completeBackgroundTaskForTesting(final BundleInfo current, final boolean plannedDirectUpdate) {
2336
2460
  this.endBackGroundTaskWithNotif("test", current.getVersionName(), current, false, plannedDirectUpdate);
2337
2461
  }
2338
2462
 
2463
+ void emitLaunchDownloadReady(final BundleInfo bundle, final String status) {
2464
+ final BundleInfo readyBundle = bundle != null ? bundle : this.implementation.getCurrentBundle();
2465
+ if (readyBundle == null) {
2466
+ return;
2467
+ }
2468
+ this.endBackGroundTaskWithNotif(
2469
+ status,
2470
+ readyBundle.getVersionName(),
2471
+ readyBundle,
2472
+ false,
2473
+ false,
2474
+ "download_fail",
2475
+ "downloadFailed",
2476
+ false,
2477
+ false
2478
+ );
2479
+ }
2480
+
2339
2481
  void scheduleDirectUpdateFinish(final BundleInfo latest) {
2340
2482
  startNewThread(() -> {
2341
2483
  try {
@@ -2377,7 +2519,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2377
2519
  this.implementation.setNextBundle(latest.getId());
2378
2520
  final JSObject ret = new JSObject();
2379
2521
  ret.put("bundle", InternalUtils.mapToJSObject(latest.toJSONMap()));
2380
- this.notifyListeners("updateAvailable", ret);
2522
+ this.notifyListeners("updateAvailable", ret, false);
2381
2523
  sendReadyToJs(
2382
2524
  this.implementation.getCurrentBundle(),
2383
2525
  "Direct update reload failed, update will install next background",
@@ -2447,6 +2589,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2447
2589
  final Set<String> allowedIds = this.implementation.allowedBundleIdsForCleanup();
2448
2590
  this.implementation.cleanupDownloadDirectories(allowedIds);
2449
2591
  this.implementation.cleanupOrphanedTempFolders(null);
2592
+ this.implementation.cleanupOrphanedManifestStagingFolders(null);
2450
2593
 
2451
2594
  this.persistCurrentNativeBuildVersion();
2452
2595
  } catch (Exception e) {
@@ -2495,24 +2638,49 @@ public class CapacitorUpdaterPlugin extends Plugin {
2495
2638
  logger.info("Cleanup finished, proceeding with download");
2496
2639
  }
2497
2640
 
2641
+ /**
2642
+ * Returns the {@code download_N} stat to send for this progress, or null. Buckets are tracked per
2643
+ * download: a new download (percent 0 or another bundle id) starts from zero again.
2644
+ */
2645
+ String nextDownloadStatAction(final String id, final int percent) {
2646
+ synchronized (this.downloadStatLock) {
2647
+ if (percent == 0 || !Objects.equals(id, this.lastNotifiedStatBundleId)) {
2648
+ this.lastNotifiedStatBundleId = id;
2649
+ this.lastNotifiedStatPercent = 0;
2650
+ }
2651
+ final int currentStatPercent = (percent / 10) * 10; // Round down to nearest 10
2652
+ if (currentStatPercent <= this.lastNotifiedStatPercent) {
2653
+ return null;
2654
+ }
2655
+ this.lastNotifiedStatPercent = currentStatPercent;
2656
+ return "download_" + currentStatPercent;
2657
+ }
2658
+ }
2659
+
2660
+ private void markDownloadStatPercent(final String id, final int percent) {
2661
+ synchronized (this.downloadStatLock) {
2662
+ this.lastNotifiedStatBundleId = id;
2663
+ this.lastNotifiedStatPercent = percent;
2664
+ }
2665
+ }
2666
+
2498
2667
  public void notifyDownload(final String id, final int percent) {
2499
2668
  try {
2500
2669
  final JSObject ret = new JSObject();
2501
2670
  ret.put("percent", percent);
2502
2671
  final BundleInfo bundleInfo = this.implementation.getBundleInfo(id);
2503
2672
  ret.put("bundle", InternalUtils.mapToJSObject(bundleInfo.toJSONMap()));
2504
- this.notifyListeners("download", ret);
2673
+ this.notifyListeners("download", ret, false);
2505
2674
 
2506
2675
  if (percent == 100) {
2507
2676
  final JSObject retDownloadComplete = new JSObject(ret, new String[] { "bundle" });
2508
- this.notifyListeners("downloadComplete", retDownloadComplete);
2677
+ this.notifyListeners("downloadComplete", retDownloadComplete, false);
2509
2678
  this.implementation.sendStats("download_complete", bundleInfo.getVersionName());
2510
- lastNotifiedStatPercent = 100;
2679
+ this.markDownloadStatPercent(id, 100);
2511
2680
  } else {
2512
- int currentStatPercent = (percent / 10) * 10; // Round down to nearest 10
2513
- if (currentStatPercent > lastNotifiedStatPercent) {
2514
- this.implementation.sendStats("download_" + currentStatPercent, bundleInfo.getVersionName());
2515
- lastNotifiedStatPercent = currentStatPercent;
2681
+ final String statAction = this.nextDownloadStatAction(id, percent);
2682
+ if (statAction != null) {
2683
+ this.implementation.sendStats(statAction, bundleInfo.getVersionName());
2516
2684
  }
2517
2685
  }
2518
2686
  } catch (final Exception e) {
@@ -2663,6 +2831,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2663
2831
  CapacitorUpdaterPlugin.this.editor,
2664
2832
  DEFAULT_CHANNEL_PREF_KEY,
2665
2833
  configDefaultChannel,
2834
+ CapacitorUpdaterPlugin.this.allowSetDefaultChannel,
2666
2835
  (res) -> {
2667
2836
  JSObject jsRes = InternalUtils.mapToJSObject(res);
2668
2837
  if (jsRes.has("error")) {
@@ -2731,7 +2900,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2731
2900
  JSObject eventData = new JSObject();
2732
2901
  eventData.put("channel", channel);
2733
2902
  eventData.put("message", errorMessage);
2734
- notifyListeners("channelPrivate", eventData);
2903
+ notifyListeners("channelPrivate", eventData, false);
2735
2904
  }
2736
2905
 
2737
2906
  JSObject errorObj = new JSObject();
@@ -2891,24 +3060,28 @@ public class CapacitorUpdaterPlugin extends Plugin {
2891
3060
  } catch (final Exception e) {
2892
3061
  logger.error("Failed to download from: " + url + " " + e.getMessage());
2893
3062
  call.reject("Failed to download from: " + url, e);
2894
- final JSObject ret = new JSObject();
2895
- ret.put("version", version);
2896
- CapacitorUpdaterPlugin.this.notifyListeners("downloadFailed", ret);
2897
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
2898
- CapacitorUpdaterPlugin.this.implementation.sendStats("download_fail", current.getVersionName());
3063
+ CapacitorUpdaterPlugin.this.notifyManualDownloadFailed(version, e);
2899
3064
  }
2900
3065
  });
2901
3066
  } catch (final Exception e) {
2902
3067
  logger.error("Failed to download from: " + url + " " + e.getMessage());
2903
3068
  call.reject("Failed to download from: " + url, e);
2904
- final JSObject ret = new JSObject();
2905
- ret.put("version", version);
2906
- CapacitorUpdaterPlugin.this.notifyListeners("downloadFailed", ret);
2907
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
2908
- CapacitorUpdaterPlugin.this.implementation.sendStats("download_fail", current.getVersionName());
3069
+ this.notifyManualDownloadFailed(version, e);
2909
3070
  }
2910
3071
  }
2911
3072
 
3073
+ /** Emits downloadFailed + download_fail once: the updater already did it for worker failures. */
3074
+ void notifyManualDownloadFailed(final String version, final Exception error) {
3075
+ if (error instanceof CapgoUpdater.ReportedDownloadFailureException) {
3076
+ return;
3077
+ }
3078
+ final JSObject ret = new JSObject();
3079
+ ret.put("version", version);
3080
+ this.notifyListeners("downloadFailed", ret, false);
3081
+ final BundleInfo current = this.implementation.getCurrentBundle();
3082
+ this.implementation.sendStats("download_fail", current.getVersionName());
3083
+ }
3084
+
2912
3085
  private void syncKeepUrlPathFlag(final boolean enabled) {
2913
3086
  if (this.bridge == null || this.bridge.getWebView() == null) {
2914
3087
  return;
@@ -2924,6 +3097,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
2924
3097
  }
2925
3098
 
2926
3099
  private void applyCurrentBundleToBridge() {
3100
+ this.stampReadyGenerationBeforeReload();
2927
3101
  final String path = this.implementation.getCurrentBundlePath();
2928
3102
  final boolean usingBuiltin = this.implementation.isUsingBuiltin();
2929
3103
  if (this.keepUrlPathAfterReload) {
@@ -3027,6 +3201,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
3027
3201
  }
3028
3202
 
3029
3203
  protected boolean _reload() {
3204
+ if (this.appInBackground) {
3205
+ return this.reloadInBackground();
3206
+ }
3030
3207
  // Drop any launch pending wait; this reload owns notifyAppReady synchronization.
3031
3208
  this.clearPendingNotifyAppReadyWait();
3032
3209
  final int phase = this.semaphoreUp();
@@ -3034,18 +3211,29 @@ public class CapacitorUpdaterPlugin extends Plugin {
3034
3211
 
3035
3212
  final long waitTimeMs = this.resolveAppReadyCheckTimeoutMs();
3036
3213
  this.checkAppReady(waitTimeMs);
3037
- this.notifyListeners("appReloaded", new JSObject());
3214
+ this.notifyListeners("appReloaded", new JSObject(), false);
3038
3215
 
3039
3216
  // Wait for the reload to complete (until notifyAppReady is called)
3040
3217
  return this.semaphoreWait(phase, waitTimeMs);
3041
3218
  }
3042
3219
 
3220
+ /**
3221
+ * A backgrounded app is frozen by Android: the reloaded page cannot call notifyAppReady before the
3222
+ * next foreground, so waiting here would only time out. Apply the bundle, and let the next appReady
3223
+ * wait for the page instead (the next foreground also arms a fresh rollback check).
3224
+ */
3225
+ private boolean reloadInBackground() {
3226
+ logger.info("App is in background, reload does not wait for notifyAppReady");
3227
+ this.armPendingNotifyAppReadyWait();
3228
+ return this.reloadWithoutWaitingForAppReady();
3229
+ }
3230
+
3043
3231
  protected boolean reloadWithoutWaitingForAppReady() {
3044
3232
  this.applyCurrentBundleToBridge();
3045
3233
 
3046
3234
  final long waitTimeMs = this.resolveAppReadyCheckTimeoutMs();
3047
3235
  this.checkAppReady(waitTimeMs);
3048
- this.notifyListeners("appReloaded", new JSObject());
3236
+ this.notifyListeners("appReloaded", new JSObject(), false);
3049
3237
  return true;
3050
3238
  }
3051
3239
 
@@ -3136,7 +3324,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
3136
3324
  if (!this.implementation.set(id)) {
3137
3325
  logger.info("No such bundle " + id);
3138
3326
  call.reject("Update failed, id " + id + " does not exist.");
3139
- } else if (Boolean.TRUE.equals(this.previewSessionEnabled)) {
3327
+ return;
3328
+ }
3329
+ // The bundle is now active: it must not stay reported as the pending next bundle.
3330
+ this.implementation.clearNextBundleIfCurrent();
3331
+ if (Boolean.TRUE.equals(this.previewSessionEnabled)) {
3140
3332
  logger.info("Preview session set active bundle " + id + " without waiting for preview app readiness");
3141
3333
  final BundleInfo bundle = this.implementation.getBundleInfo(id);
3142
3334
  this.recordPreviewBundle(bundle);
@@ -3566,7 +3758,9 @@ public class CapacitorUpdaterPlugin extends Plugin {
3566
3758
  }
3567
3759
 
3568
3760
  private void leavePreviewSessionForLaunchIntentIfNeeded() {
3569
- final Intent intent = getActivity() == null ? null : getActivity().getIntent();
3761
+ final Bridge bridge = getBridge();
3762
+ final Activity launchActivity = bridge == null ? null : bridge.getActivity();
3763
+ final Intent intent = launchActivity == null ? null : launchActivity.getIntent();
3570
3764
  if (
3571
3765
  intent == null ||
3572
3766
  !Intent.ACTION_VIEW.equals(intent.getAction()) ||
@@ -3861,17 +4055,22 @@ public class CapacitorUpdaterPlugin extends Plugin {
3861
4055
  }
3862
4056
 
3863
4057
  private JSONObject fetchPreviewPayload(final String payloadUrl) throws IOException, JSONException {
3864
- final HttpURLConnection connection = (HttpURLConnection) new URL(payloadUrl).openConnection();
3865
- connection.setRequestMethod("GET");
3866
- connection.setRequestProperty("Accept", "application/json");
3867
- connection.setConnectTimeout(30000);
3868
- connection.setReadTimeout(60000);
3869
-
3870
- try {
3871
- final int statusCode = connection.getResponseCode();
3872
- final String body = this.readResponseBody(
3873
- statusCode >= 200 && statusCode < 300 ? connection.getInputStream() : connection.getErrorStream()
3874
- );
4058
+ final HttpUrl url = payloadUrl != null ? HttpUrl.parse(payloadUrl) : null;
4059
+ if (url == null) {
4060
+ throw new MalformedURLException("Expected an http or https preview payload URL");
4061
+ }
4062
+ // Shared client: no cookies, Capgo User-Agent.
4063
+ final OkHttpClient client = DownloadService.sharedClient
4064
+ .newBuilder()
4065
+ .connectTimeout(30, TimeUnit.SECONDS)
4066
+ .readTimeout(60, TimeUnit.SECONDS)
4067
+ .build();
4068
+ final Request request = new Request.Builder().url(url).get().header("Accept", "application/json").build();
4069
+
4070
+ try (Response response = client.newCall(request).execute()) {
4071
+ final int statusCode = response.code();
4072
+ final ResponseBody responseBody = response.body();
4073
+ final String body = this.readResponseBody(responseBody != null ? responseBody.byteStream() : null);
3875
4074
  final JSONObject payload = new JSONObject(body);
3876
4075
  if (statusCode < 200 || statusCode >= 300) {
3877
4076
  throw new IOException(
@@ -3879,8 +4078,6 @@ public class CapacitorUpdaterPlugin extends Plugin {
3879
4078
  );
3880
4079
  }
3881
4080
  return payload;
3882
- } finally {
3883
- connection.disconnect();
3884
4081
  }
3885
4082
  }
3886
4083
 
@@ -4253,8 +4450,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
4253
4450
  logger.error("Error no url or wrong format");
4254
4451
  return "unavailable";
4255
4452
  }
4453
+ // The TS contract only knows queued / already_running / unavailable.
4256
4454
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
4257
- return "preview_session";
4455
+ return "unavailable";
4456
+ }
4457
+ if (!this._isAutoUpdateEnabled()) {
4458
+ logger.info("Auto update is disabled, update check not triggered");
4459
+ return "unavailable";
4258
4460
  }
4259
4461
  synchronized (this) {
4260
4462
  final Thread previousTask = this.backgroundDownloadTask;
@@ -4387,6 +4589,8 @@ public class CapacitorUpdaterPlugin extends Plugin {
4387
4589
  @PluginMethod
4388
4590
  public void getNextBundle(final PluginCall call) {
4389
4591
  try {
4592
+ // Heals a next bundle left stored after it was activated (set() did not clear it before).
4593
+ this.implementation.clearNextBundleIfCurrent();
4390
4594
  final BundleInfo bundle = this.implementation.getNextBundle();
4391
4595
  if (bundle == null) {
4392
4596
  call.resolve(null);
@@ -4429,59 +4633,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4429
4633
  new TimerTask() {
4430
4634
  @Override
4431
4635
  public void run() {
4432
- try {
4433
- if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
4434
- return;
4435
- }
4436
- CapacitorUpdaterPlugin.this.implementation.getLatest(CapacitorUpdaterPlugin.this.updateUrl, null, (res) -> {
4437
- if (CapacitorUpdaterPlugin.this.shouldBlockAutoUpdateForPreviewSession()) {
4438
- return;
4439
- }
4440
- JSObject jsRes = InternalUtils.mapToJSObject(res);
4441
- if (jsRes.has("error") || jsRes.has("kind")) {
4442
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
4443
- String error = jsRes.has("error") ? jsRes.getString("error") : "";
4444
- String errorMessage = jsRes.has("message")
4445
- ? jsRes.getString("message")
4446
- : "server did not provide a message";
4447
- int statusCode = jsRes.has("statusCode") ? jsRes.optInt("statusCode", 0) : 0;
4448
- String kind = CapacitorUpdaterPlugin.this.getUpdateResponseKind(
4449
- jsRes.has("kind") ? jsRes.getString("kind") : null
4450
- );
4451
- String latestVersion = jsRes.has("version") ? jsRes.getString("version") : current.getVersionName();
4452
- CapacitorUpdaterPlugin.this.notifyUpdateCheckResult(
4453
- kind,
4454
- error,
4455
- errorMessage,
4456
- statusCode,
4457
- latestVersion,
4458
- current
4459
- );
4460
-
4461
- if ("failed".equals(kind)) {
4462
- logger.error("getLatest failed with error: " + error + ", message: " + errorMessage);
4463
- } else if ("blocked".equals(kind)) {
4464
- logger.info("Update check blocked with error: " + error);
4465
- } else {
4466
- logger.info("No new version available");
4467
- }
4468
- } else if (jsRes.has("version")) {
4469
- String newVersion = jsRes.getString("version");
4470
- String currentVersion = String.valueOf(CapacitorUpdaterPlugin.this.implementation.getCurrentBundle());
4471
- if (!Objects.equals(newVersion, currentVersion)) {
4472
- logger.info("New version found: " + newVersion);
4473
- // Check if download is already in progress (with timeout protection)
4474
- if (!CapacitorUpdaterPlugin.this.isDownloadStuckOrTimedOut()) {
4475
- CapacitorUpdaterPlugin.this.backgroundDownload();
4476
- } else {
4477
- logger.info("Download already in progress, skipping duplicate download request");
4478
- }
4479
- }
4480
- }
4481
- });
4482
- } catch (final Exception e) {
4483
- logger.error("Failed to check for update " + e.getMessage());
4484
- }
4636
+ CapacitorUpdaterPlugin.this.runPeriodicUpdateCheck();
4485
4637
  }
4486
4638
  },
4487
4639
  this.periodCheckDelay,
@@ -4489,10 +4641,165 @@ public class CapacitorUpdaterPlugin extends Plugin {
4489
4641
  );
4490
4642
  }
4491
4643
 
4644
+ void runPeriodicUpdateCheck() {
4645
+ try {
4646
+ if (this.shouldBlockAutoUpdateForPreviewSession()) {
4647
+ return;
4648
+ }
4649
+ this.implementation.getLatest(this.updateUrl, null, (res) -> {
4650
+ if (this.shouldBlockAutoUpdateForPreviewSession()) {
4651
+ return;
4652
+ }
4653
+ JSObject jsRes = InternalUtils.mapToJSObject(res);
4654
+ if (jsRes.has("error") || jsRes.has("kind")) {
4655
+ final BundleInfo current = this.implementation.getCurrentBundle();
4656
+ String error = jsRes.has("error") ? jsRes.getString("error") : "";
4657
+ String errorMessage = jsRes.has("message") ? jsRes.getString("message") : "server did not provide a message";
4658
+ int statusCode = jsRes.has("statusCode") ? jsRes.optInt("statusCode", 0) : 0;
4659
+ String kind = this.getUpdateResponseKind(jsRes.has("kind") ? jsRes.getString("kind") : null);
4660
+ String latestVersion = jsRes.has("version") ? jsRes.getString("version") : current.getVersionName();
4661
+ this.notifyUpdateCheckResult(kind, error, errorMessage, statusCode, latestVersion, current);
4662
+
4663
+ if ("failed".equals(kind)) {
4664
+ logger.error("getLatest failed with error: " + error + ", message: " + errorMessage);
4665
+ } else if ("blocked".equals(kind)) {
4666
+ logger.info("Update check blocked with error: " + error);
4667
+ } else {
4668
+ logger.info("No new version available");
4669
+ }
4670
+ } else if (jsRes.has("version")) {
4671
+ String newVersion = jsRes.getString("version");
4672
+ String currentVersion = this.implementation.getCurrentBundle().getVersionName();
4673
+ if (!Objects.equals(newVersion, currentVersion)) {
4674
+ logger.info("New version found: " + newVersion);
4675
+ // Check if download is already in progress (with timeout protection)
4676
+ if (!this.isDownloadStuckOrTimedOut()) {
4677
+ this.backgroundDownload();
4678
+ } else {
4679
+ logger.info("Download already in progress, skipping duplicate download request");
4680
+ }
4681
+ }
4682
+ }
4683
+ });
4684
+ } catch (final Exception e) {
4685
+ logger.error("Failed to check for update " + e.getMessage());
4686
+ }
4687
+ }
4688
+
4689
+ static boolean shouldAcceptReadyCall(
4690
+ final boolean guardArmed,
4691
+ final int expectedGeneration,
4692
+ final boolean hasGeneration,
4693
+ final int reportedGeneration
4694
+ ) {
4695
+ if (!guardArmed) {
4696
+ return true;
4697
+ }
4698
+ return hasGeneration && reportedGeneration == expectedGeneration;
4699
+ }
4700
+
4701
+ static String readyGenerationScript(final int generation) {
4702
+ // Wrap Capacitor.nativePromise, not the plugin proxy. registerPlugin's get trap
4703
+ // ignores assignments to notifyAppReady. Each document keeps its own generation.
4704
+ return (
4705
+ "(function(){window.__CAPGO_READY_GEN=" +
4706
+ generation +
4707
+ ";if(window.__capgoReadyBridge)return;" +
4708
+ "function arm(){var cap=window.Capacitor;if(!cap||typeof cap.nativePromise!=='function'||cap.__capgoNativePromise)return false;" +
4709
+ "var orig=cap.nativePromise.bind(cap);" +
4710
+ "cap.nativePromise=function(pluginName,methodName,options){if(pluginName==='CapacitorUpdater'&&methodName==='notifyAppReady'){" +
4711
+ "var next={};if(options&&typeof options==='object'){for(var k in options){if(Object.prototype.hasOwnProperty.call(options,k))next[k]=options[k];}}" +
4712
+ "next.loadGeneration=window.__CAPGO_READY_GEN;options=next;}return orig(pluginName,methodName,options);};" +
4713
+ "cap.__capgoNativePromise=true;window.__capgoReadyBridge=true;return true;}" +
4714
+ "if(!arm()){var n=0;var t=setInterval(function(){if(arm()||++n>100)clearInterval(t);},20);}" +
4715
+ "})();"
4716
+ );
4717
+ }
4718
+
4719
+ private int armReadyGuard() {
4720
+ synchronized (this.readyGuardLock) {
4721
+ this.readyGeneration = this.readyGeneration + 1;
4722
+ this.readyGuardArmed = true;
4723
+ return this.readyGeneration;
4724
+ }
4725
+ }
4726
+
4727
+ private void disarmReadyGuard(final int generation) {
4728
+ synchronized (this.readyGuardLock) {
4729
+ if (this.readyGeneration == generation) {
4730
+ this.readyGuardArmed = false;
4731
+ logger.warn("Could not stamp notifyAppReady for the next page. Readiness guard disabled for this reload.");
4732
+ }
4733
+ }
4734
+ }
4735
+
4736
+ private void stampReadyGenerationBeforeReload() {
4737
+ final int generation = this.armReadyGuard();
4738
+ final android.webkit.WebView webView = this.bridge != null ? this.bridge.getWebView() : null;
4739
+ if (webView == null) {
4740
+ this.disarmReadyGuard(generation);
4741
+ return;
4742
+ }
4743
+ webView.post(() -> {
4744
+ if (!this.installReadyGenerationScript(webView, generation)) {
4745
+ this.disarmReadyGuard(generation);
4746
+ }
4747
+ });
4748
+ }
4749
+
4750
+ private boolean installReadyGenerationScript(final android.webkit.WebView webView, final int generation) {
4751
+ try {
4752
+ final Class<?> webViewFeature = Class.forName("androidx.webkit.WebViewFeature");
4753
+ final String feature = (String) webViewFeature.getField("DOCUMENT_START_SCRIPT").get(null);
4754
+ final Boolean supported = (Boolean) webViewFeature.getMethod("isFeatureSupported", String.class).invoke(null, feature);
4755
+ if (!Boolean.TRUE.equals(supported)) {
4756
+ return false;
4757
+ }
4758
+ if (this.bridge == null || this.bridge.getAppUrl() == null) {
4759
+ return false;
4760
+ }
4761
+ final String allowedOrigin = Uri.parse(this.bridge.getAppUrl())
4762
+ .buildUpon()
4763
+ .path(null)
4764
+ .fragment(null)
4765
+ .clearQuery()
4766
+ .build()
4767
+ .toString();
4768
+ final Class<?> webViewCompat = Class.forName("androidx.webkit.WebViewCompat");
4769
+ webViewCompat
4770
+ .getMethod("addDocumentStartJavaScript", android.webkit.WebView.class, String.class, Set.class)
4771
+ .invoke(null, webView, readyGenerationScript(generation), java.util.Collections.singleton(allowedOrigin));
4772
+ return true;
4773
+ } catch (final Exception e) {
4774
+ logger.warn("Unable to stamp notifyAppReady generation: " + e.getMessage());
4775
+ return false;
4776
+ }
4777
+ }
4778
+
4779
+ private boolean acceptsReadyCall(final PluginCall call) {
4780
+ if (!this.readyGuardArmed) {
4781
+ return true;
4782
+ }
4783
+ final JSObject data = call.getData();
4784
+ final boolean hasGeneration = data != null && data.has("loadGeneration");
4785
+ final int reported = hasGeneration ? data.optInt("loadGeneration", -1) : -1;
4786
+ return shouldAcceptReadyCall(this.readyGuardArmed, this.readyGeneration, hasGeneration, reported);
4787
+ }
4788
+
4492
4789
  @PluginMethod
4493
4790
  public void notifyAppReady(final PluginCall call) {
4494
4791
  ensureBridgeSet();
4495
4792
  try {
4793
+ if (!this.acceptsReadyCall(call)) {
4794
+ logger.info("Ignoring notifyAppReady from a page that is no longer current");
4795
+ final BundleInfo current = this.implementation.getCurrentBundle();
4796
+ final JSObject ignored = new JSObject();
4797
+ if (current != null) {
4798
+ ignored.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
4799
+ }
4800
+ call.resolve(ignored);
4801
+ return;
4802
+ }
4496
4803
  final BundleInfo bundle = this.implementation.getCurrentBundle();
4497
4804
  this.implementation.setSuccess(bundle, this.autoDeletePrevious);
4498
4805
  this.reportAppLaunchReady(bundle);
@@ -4528,11 +4835,27 @@ public class CapacitorUpdaterPlugin extends Plugin {
4528
4835
  }
4529
4836
  }
4530
4837
 
4531
- if (this.delayUpdateUtils.setMultiDelay(delayConditions.toString())) {
4532
- call.resolve();
4533
- } else {
4838
+ final String conditionMode = call.getData().optString("conditionMode", DelayUpdateUtils.DELAY_CONDITION_MODE_AND);
4839
+ final String previousConditions = prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]");
4840
+ final String previousMode = this.delayUpdateUtils.getConditionMode();
4841
+ if (!this.delayUpdateUtils.setMultiDelay(delayConditions.toString())) {
4842
+ if (!this.delayUpdateUtils.setMultiDelay(previousConditions)) {
4843
+ logger.error("Failed to restore previous delay conditions after setMultiDelay failure");
4844
+ }
4534
4845
  call.reject("Failed to delay update");
4846
+ return;
4535
4847
  }
4848
+ if (!this.delayUpdateUtils.setConditionMode(conditionMode)) {
4849
+ if (!this.delayUpdateUtils.setMultiDelay(previousConditions)) {
4850
+ logger.error("Failed to restore previous delay conditions after setConditionMode failure");
4851
+ }
4852
+ if (!this.delayUpdateUtils.setConditionMode(previousMode)) {
4853
+ logger.error("Failed to restore previous delay condition mode after setConditionMode failure");
4854
+ }
4855
+ call.reject("Failed to delay update");
4856
+ return;
4857
+ }
4858
+ call.resolve();
4536
4859
  } catch (final Exception e) {
4537
4860
  logger.error("Failed to delay update, [Error calling 'setMultiDelay()'] " + e.getMessage());
4538
4861
  call.reject("Failed to delay update", e);
@@ -4653,11 +4976,11 @@ public class CapacitorUpdaterPlugin extends Plugin {
4653
4976
  ret.put("statusCode", statusCode);
4654
4977
  ret.put("version", version);
4655
4978
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
4656
- this.notifyListeners("updateCheckResult", ret);
4979
+ this.notifyListeners("updateCheckResult", ret, false);
4657
4980
  }
4658
4981
 
4659
4982
  private void ensureBridgeSet() {
4660
- if (this.bridge != null && this.bridge.getWebView() != null) {
4983
+ if (this.bridge != null && this.bridge.getWebView() != null && !this.getConfig().getBoolean("disableJSLogging", false)) {
4661
4984
  logger.setBridge(this.bridge);
4662
4985
  }
4663
4986
  }
@@ -4737,12 +5060,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
4737
5060
  }
4738
5061
  final JSObject ret = new JSObject();
4739
5062
  ret.put("version", latestVersionName);
4740
- this.notifyListeners(failureEvent, ret);
5063
+ this.notifyListeners(failureEvent, ret, false);
4741
5064
  }
4742
5065
  if (shouldNotifyNoNeedUpdate) {
4743
5066
  final JSObject ret = new JSObject();
4744
5067
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
4745
- this.notifyListeners("noNeedUpdate", ret);
5068
+ this.notifyListeners("noNeedUpdate", ret, false);
4746
5069
  }
4747
5070
  this.sendReadyToJs(current, msg, plannedDirectUpdate);
4748
5071
  this.backgroundDownloadTask = null;
@@ -4780,6 +5103,26 @@ public class CapacitorUpdaterPlugin extends Plugin {
4780
5103
  return true;
4781
5104
  }
4782
5105
 
5106
+ /**
5107
+ * Security gates of an auto-update download, checked before it starts. Returns the cycle status
5108
+ * when the download must not start (after sending its stat), or null.
5109
+ */
5110
+ private String autoUpdateDownloadBlockedReason(final JSObject latest, final String latestVersionName) {
5111
+ final String sessionKey = latest.getString("sessionKey", "");
5112
+ if (!this.implementation.publicKey.isEmpty() && !CryptoCipher.isValidSessionKey(sessionKey)) {
5113
+ logger.error("Public key present but no valid session key provided");
5114
+ this.implementation.sendStats("session_key_required", latestVersionName);
5115
+ return "Session key required when public key is present";
5116
+ }
5117
+ final String checksum = latest.getString("checksum", "");
5118
+ if (!latest.has("manifest") && (checksum == null || checksum.isEmpty())) {
5119
+ logger.error("No checksum provided");
5120
+ this.implementation.sendStats("checksum_required", latestVersionName);
5121
+ return "Checksum required";
5122
+ }
5123
+ return null;
5124
+ }
5125
+
4783
5126
  private synchronized Thread backgroundDownload() {
4784
5127
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
4785
5128
  return null;
@@ -4841,6 +5184,16 @@ public class CapacitorUpdaterPlugin extends Plugin {
4841
5184
  }
4842
5185
 
4843
5186
  boolean isFailure = "failed".equals(kind);
5187
+ if (isFailure) {
5188
+ // The check itself failed (offline, timeout, unreadable response, 429 block):
5189
+ // nothing was downloaded, so report it apart from download_fail.
5190
+ CapacitorUpdaterPlugin.this.implementation.sendStats(
5191
+ UPDATE_CHECK_ERROR_ACTION,
5192
+ currentBeforeCleanup.getVersionName(),
5193
+ "",
5194
+ updateCheckErrorMetadata(error, statusCode)
5195
+ );
5196
+ }
4844
5197
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
4845
5198
  errorMessage,
4846
5199
  latestVersion,
@@ -4849,7 +5202,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4849
5202
  plannedDirectUpdate,
4850
5203
  "download_fail",
4851
5204
  "downloadFailed",
4852
- isFailure
5205
+ false
4853
5206
  );
4854
5207
  return;
4855
5208
  }
@@ -4898,7 +5251,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4898
5251
  BundleInfo.ID_BUILTIN
4899
5252
  );
4900
5253
  ret.put("bundle", InternalUtils.mapToJSObject(builtinBundle.toJSONMap()));
4901
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret);
5254
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
4902
5255
  }
4903
5256
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
4904
5257
  "Latest version is builtin, autoUpdate onlyDownload",
@@ -4999,7 +5352,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
4999
5352
  "Direct update skipped because splashscreen timeout occurred. Update will install on next background."
5000
5353
  );
5001
5354
  }
5002
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret);
5355
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
5003
5356
  CapacitorUpdaterPlugin.this.implementation.setNextBundle(latest.getId());
5004
5357
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5005
5358
  "update downloaded, will install next background",
@@ -5010,7 +5363,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5010
5363
  );
5011
5364
  } else {
5012
5365
  logger.info("autoUpdate is set to onlyDownload, downloaded update will not be set as next bundle");
5013
- CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret);
5366
+ CapacitorUpdaterPlugin.this.notifyListeners("updateAvailable", ret, false);
5014
5367
  CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5015
5368
  "update downloaded, autoUpdate onlyDownload",
5016
5369
  latestVersionName,
@@ -5037,6 +5390,22 @@ public class CapacitorUpdaterPlugin extends Plugin {
5037
5390
  }
5038
5391
  }
5039
5392
  }
5393
+ // The store refuses these downloads without a callback, so end the cycle here
5394
+ // (appReady, splash hide) like iOS does.
5395
+ final String downloadBlockedReason = CapacitorUpdaterPlugin.this.autoUpdateDownloadBlockedReason(
5396
+ jsRes,
5397
+ latestVersionName
5398
+ );
5399
+ if (downloadBlockedReason != null) {
5400
+ CapacitorUpdaterPlugin.this.endBackGroundTaskWithNotif(
5401
+ downloadBlockedReason,
5402
+ latestVersionName,
5403
+ current,
5404
+ true,
5405
+ plannedDirectUpdate
5406
+ );
5407
+ return;
5408
+ }
5040
5409
  final boolean retryingInFlightDownload =
5041
5410
  latest != null &&
5042
5411
  BundleStatus.DOWNLOADING == latest.getStatus() &&
@@ -5135,6 +5504,19 @@ public class CapacitorUpdaterPlugin extends Plugin {
5135
5504
  return newTask;
5136
5505
  }
5137
5506
 
5507
+ /**
5508
+ * A download that finished while the app is in the background (for example after an
5509
+ * update-check push) would otherwise wait for the next foreground/background cycle, so the
5510
+ * user would open the old version once more. Install it now, like a background transition.
5511
+ */
5512
+ void installNextIfInBackground() {
5513
+ if (!this.appInBackground) {
5514
+ return;
5515
+ }
5516
+ logger.info("Next bundle downloaded while in background, installing it now");
5517
+ this.installNext();
5518
+ }
5519
+
5138
5520
  private void installNext() {
5139
5521
  try {
5140
5522
  if (this.shouldBlockAutoUpdateForPreviewSession()) {
@@ -5187,33 +5569,51 @@ public class CapacitorUpdaterPlugin extends Plugin {
5187
5569
  final JSObject ret = new JSObject();
5188
5570
  ret.put("bundle", InternalUtils.mapToJSObject(current.toJSONMap()));
5189
5571
  this.persistLastFailedBundle(current);
5190
- this.notifyListeners("updateFailed", ret);
5572
+ this.notifyListeners("updateFailed", ret, false);
5191
5573
  this.reportAppLaunchTimeout(current);
5192
5574
  this.implementation.sendStats("update_fail", current.getVersionName());
5193
5575
  this.implementation.setError(current);
5194
5576
  this.performReset(true, false, true);
5195
5577
  if (CapacitorUpdaterPlugin.this.autoDeleteFailed && !current.isBuiltin()) {
5196
5578
  final String failedId = current.getId();
5197
- final String failedVersion = current.getVersionName();
5198
- logger.info("Deleting failing bundle: " + failedVersion);
5199
- // Mark before async work so kill/OOM still resumes via drainPendingDeletes.
5200
- CapacitorUpdaterPlugin.this.implementation.saveBundleInfo(failedId, current.setStatus(BundleStatus.DELETING));
5201
- startNewThread(() -> {
5202
- try {
5203
- final Boolean res = CapacitorUpdaterPlugin.this.implementation.delete(failedId, false, false);
5204
- if (Boolean.TRUE.equals(res)) {
5205
- logger.info("Failed bundle deleted: " + failedVersion);
5579
+ final BundleInfo latest = this.implementation.getBundleInfo(failedId);
5580
+ final boolean stillCurrent = failedId.equals(this.implementation.getCurrentBundle().getId());
5581
+ // performReset waits for notifyAppReady. Resetting onto this same bundle writes
5582
+ // SUCCESS before we get here, so the pre-reset snapshot must not become DELETING.
5583
+ if (latest == null || BundleStatus.ERROR != latest.getStatus() || stillCurrent) {
5584
+ logger.info("Skip deleting bundle " + failedId + " after reset");
5585
+ } else {
5586
+ final String failedVersion = latest.getVersionName();
5587
+ logger.info("Deleting failing bundle: " + failedVersion);
5588
+ // Mark before async work so kill/OOM still resumes via drainPendingDeletes.
5589
+ CapacitorUpdaterPlugin.this.implementation.saveBundleInfo(failedId, latest.setStatus(BundleStatus.DELETING));
5590
+ startNewThread(() -> {
5591
+ try {
5592
+ final Boolean res = CapacitorUpdaterPlugin.this.implementation.delete(failedId, false, false);
5593
+ if (Boolean.TRUE.equals(res)) {
5594
+ logger.info("Failed bundle deleted: " + failedVersion);
5595
+ }
5596
+ } catch (final IOException e) {
5597
+ logger.error("Failed to delete failed bundle: " + failedVersion + " " + e.getMessage());
5206
5598
  }
5207
- } catch (final IOException e) {
5208
- logger.error("Failed to delete failed bundle: " + failedVersion + " " + e.getMessage());
5209
- }
5210
- });
5599
+ });
5600
+ }
5211
5601
  }
5212
5602
  } else {
5213
5603
  logger.info("notifyAppReady was called. This is fine: " + current.getId());
5214
5604
  }
5215
5605
  }
5216
5606
 
5607
+ void runDeferredAppReadyCheck() {
5608
+ // A frozen app wakes up with its sleep already expired, before appMovedToForeground re-arms
5609
+ // the check: its page could not run yet, so wait for the fresh check of the next foreground.
5610
+ if (this.appInBackground) {
5611
+ logger.info("App is in background, notifyAppReady check deferred to the next foreground");
5612
+ return;
5613
+ }
5614
+ this.checkRevert();
5615
+ }
5616
+
5217
5617
  private class DeferredNotifyAppReadyCheck implements Runnable {
5218
5618
 
5219
5619
  private final long waitTimeMs;
@@ -5228,7 +5628,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5228
5628
  try {
5229
5629
  logger.info("Wait for " + this.waitTimeMs + "ms, then check for notifyAppReady");
5230
5630
  Thread.sleep(this.waitTimeMs);
5231
- CapacitorUpdaterPlugin.this.checkRevert();
5631
+ CapacitorUpdaterPlugin.this.runDeferredAppReadyCheck();
5232
5632
  CapacitorUpdaterPlugin.this.clearAppReadyCheckIfCurrent(currentThread);
5233
5633
  } catch (final InterruptedException e) {
5234
5634
  CapacitorUpdaterPlugin.this.clearAppReadyCheckIfCurrent(currentThread);
@@ -5238,6 +5638,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5238
5638
  }
5239
5639
 
5240
5640
  public void appMovedToForeground() {
5641
+ this.appInBackground = false;
5241
5642
  // Ensure activity reference is up-to-date before proceeding
5242
5643
  // This is critical for callbacks that may be invoked during background operations
5243
5644
  try {
@@ -5256,8 +5657,13 @@ public class CapacitorUpdaterPlugin extends Plugin {
5256
5657
  this.delayUpdateUtils.checkCancelDelay(DelayUpdateUtils.CancelDelaySource.FOREGROUND);
5257
5658
  this.delayUpdateUtils.unsetBackgroundTimestamp();
5258
5659
 
5259
- if (CapacitorUpdaterPlugin.this._isAutoUpdateEnabled() && !this.isDownloadStuckOrTimedOut()) {
5260
- this.backgroundDownload();
5660
+ if (CapacitorUpdaterPlugin.this._isAutoUpdateEnabled()) {
5661
+ if (!this.isDownloadStuckOrTimedOut()) {
5662
+ this.backgroundDownload();
5663
+ } else {
5664
+ // The running cycle sends appReady when it ends.
5665
+ logger.info("Download already in progress, skipping duplicate download request");
5666
+ }
5261
5667
  } else {
5262
5668
  final CapConfig config = CapConfig.loadDefault(this.getActivity());
5263
5669
  String serverUrl = config.getServerUrl();
@@ -5271,6 +5677,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5271
5677
  }
5272
5678
 
5273
5679
  public void appMovedToBackground() {
5680
+ this.appInBackground = true;
5274
5681
  // Reset timeout flag at start of each background cycle
5275
5682
  this.autoSplashscreenTimedOut = false;
5276
5683
 
@@ -5625,6 +6032,12 @@ public class CapacitorUpdaterPlugin extends Plugin {
5625
6032
  result.put("installStatus", appUpdateInfo.installStatus());
5626
6033
 
5627
6034
  call.resolve(result);
6035
+ if (
6036
+ appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE &&
6037
+ CapacitorUpdaterPlugin.this.nativeUpdatePrompt != null
6038
+ ) {
6039
+ CapacitorUpdaterPlugin.this.nativeUpdatePrompt.maybeShowForStoreUpdateAvailable();
6040
+ }
5628
6041
  })
5629
6042
  .addOnFailureListener((e) -> {
5630
6043
  logger.error("Failed to get app update info: " + e.getMessage());
@@ -5769,7 +6182,7 @@ public class CapacitorUpdaterPlugin extends Plugin {
5769
6182
  eventData.put("totalBytesToDownload", state.totalBytesToDownload());
5770
6183
  }
5771
6184
 
5772
- notifyListeners("onFlexibleUpdateStateChange", eventData);
6185
+ notifyListeners("onFlexibleUpdateStateChange", eventData, false);
5773
6186
  };
5774
6187
 
5775
6188
  manager.registerListener(installStateUpdatedListener);
@@ -5856,6 +6269,10 @@ public class CapacitorUpdaterPlugin extends Plugin {
5856
6269
  }
5857
6270
 
5858
6271
  private void handleOnDestroyInternal() {
6272
+ instanceLoaded = false;
6273
+ if (this.implementation != null) {
6274
+ this.implementation.releaseStatsOwnership();
6275
+ }
5859
6276
  // Original handleOnDestroy code
5860
6277
  try {
5861
6278
  logger.info("onActivityDestroyed " + getActivity().getClass().getName());