@capgo/capacitor-updater 7.51.23 → 7.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
@@ -15,7 +15,6 @@ import java.io.*;
15
15
  import java.io.FileInputStream;
16
16
  import java.net.HttpURLConnection;
17
17
  import java.net.MalformedURLException;
18
- import java.net.URL;
19
18
  import java.nio.channels.FileChannel;
20
19
  import java.security.MessageDigest;
21
20
  import java.util.ArrayList;
@@ -35,7 +34,9 @@ import java.util.function.BooleanSupplier;
35
34
  import java.util.function.LongConsumer;
36
35
  import okhttp3.Call;
37
36
  import okhttp3.Callback;
37
+ import okhttp3.CookieJar;
38
38
  import okhttp3.Dispatcher;
39
+ import okhttp3.HttpUrl;
39
40
  import okhttp3.Interceptor;
40
41
  import okhttp3.MediaType;
41
42
  import okhttp3.OkHttpClient;
@@ -50,6 +51,14 @@ import org.json.JSONObject;
50
51
 
51
52
  public class DownloadService extends Worker {
52
53
 
54
+ /** A refused HTTPS to HTTP redirect. Permanent for the given URL, so downloads must not retry it. */
55
+ static final class BlockedRedirectException extends IOException {
56
+
57
+ BlockedRedirectException() {
58
+ super("Blocked HTTPS to HTTP redirect; set allowHttpsToHttpRedirect to true to allow it");
59
+ }
60
+ }
61
+
53
62
  static final class DownloadRetryException extends RuntimeException {
54
63
 
55
64
  DownloadRetryException(String message) {
@@ -126,6 +135,8 @@ public class DownloadService extends Worker {
126
135
  // Match CapgoUpdater.timeout / responseTimeout default (20s). OkHttp's 10s
127
136
  // defaults were unused by the plugin config and aborted slow manifest GETs.
128
137
  private static volatile int httpTimeoutMs = 20_000;
138
+ // Off by default: a redirect must never downgrade updater traffic from HTTPS to plain HTTP.
139
+ private static volatile boolean allowHttpsToHttpRedirect = false;
129
140
  private static String currentAppId = "unknown";
130
141
  private static String currentPluginVersion = "unknown";
131
142
  private static String currentVersionOs = "unknown";
@@ -138,6 +149,9 @@ public class DownloadService extends Worker {
138
149
  sharedClient = new OkHttpClient.Builder()
139
150
  .dispatcher(dispatcher)
140
151
  .protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1))
152
+ // Never share cookies with Capgo endpoints: the app's java.net.CookieHandler default is
153
+ // Capacitor's WebView cookie manager, and it must not see (or be fed by) plugin traffic.
154
+ .cookieJar(CookieJar.NO_COOKIES)
141
155
  .connectTimeout(httpTimeoutMs, TimeUnit.MILLISECONDS)
142
156
  .readTimeout(httpTimeoutMs, TimeUnit.MILLISECONDS)
143
157
  .writeTimeout(httpTimeoutMs, TimeUnit.MILLISECONDS)
@@ -147,9 +161,33 @@ public class DownloadService extends Worker {
147
161
  Request requestWithUserAgent = originalRequest.newBuilder().header("User-Agent", userAgent).build();
148
162
  return chain.proceed(requestWithUserAgent);
149
163
  })
164
+ .addNetworkInterceptor((chain) -> {
165
+ Response response = chain.proceed(chain.request());
166
+ if (!allowHttpsToHttpRedirect && isHttpsToHttpRedirect(response)) {
167
+ response.close();
168
+ throw new BlockedRedirectException();
169
+ }
170
+ return response;
171
+ })
150
172
  .build();
151
173
  }
152
174
 
175
+ static void setAllowHttpsToHttpRedirect(boolean allow) {
176
+ allowHttpsToHttpRedirect = allow;
177
+ }
178
+
179
+ static boolean isHttpsToHttpRedirect(Response response) {
180
+ if (!response.isRedirect() || !response.request().isHttps()) {
181
+ return false;
182
+ }
183
+ String location = response.header("Location");
184
+ if (location == null) {
185
+ return false;
186
+ }
187
+ HttpUrl target = response.request().url().resolve(location);
188
+ return target != null && !target.isHttps();
189
+ }
190
+
153
191
  static int httpTimeoutMs() {
154
192
  return httpTimeoutMs;
155
193
  }
@@ -239,8 +277,21 @@ public class DownloadService extends Worker {
239
277
  }
240
278
 
241
279
  private Result createFailureResult(String error) {
242
- Data output = new Data.Builder().putString(ERROR, error).build();
243
- return Result.failure(output);
280
+ return createFailureResult(error, null, null, false);
281
+ }
282
+
283
+ private Result createFailureResult(String error, String version, String dest, boolean isManifest) {
284
+ Data.Builder builder = new Data.Builder().putString(ERROR, error);
285
+ if (version != null) {
286
+ builder.putString(VERSION, version);
287
+ }
288
+ if (dest != null) {
289
+ builder.putString(FILEDEST, dest);
290
+ }
291
+ if (isManifest) {
292
+ builder.putBoolean(IS_MANIFEST, true);
293
+ }
294
+ return Result.failure(builder.build());
244
295
  }
245
296
 
246
297
  private Result createSuccessResult(String dest, String version, String sessionKey, String checksum, boolean isManifest) {
@@ -431,16 +482,16 @@ public class DownloadService extends Worker {
431
482
  @NonNull
432
483
  @Override
433
484
  public Result doWork() {
485
+ final String documentsDir = getInputData().getString(DOCDIR);
486
+ final String dest = getInputData().getString(FILEDEST);
487
+ final String version = getInputData().getString(VERSION);
488
+ final boolean isManifest = getInputData().getBoolean(IS_MANIFEST, false);
434
489
  try {
435
490
  String url = getInputData().getString(URL);
436
491
  String id = getInputData().getString(ID);
437
- String documentsDir = getInputData().getString(DOCDIR);
438
- String dest = getInputData().getString(FILEDEST);
439
- String version = getInputData().getString(VERSION);
440
492
  String sessionKey = getInputData().getString(SESSIONKEY);
441
493
  String checksum = getInputData().getString(CHECKSUM);
442
494
  String publicKey = getInputData().getString(PUBLIC_KEY);
443
- boolean isManifest = getInputData().getBoolean(IS_MANIFEST, false);
444
495
 
445
496
  logger.debug("doWork isManifest: " + isManifest);
446
497
 
@@ -450,10 +501,12 @@ public class DownloadService extends Worker {
450
501
  handleManifestDownload(id, documentsDir, dest, version, sessionKey, publicKey, manifest);
451
502
  return createSuccessResult(dest, version, sessionKey, checksum, true);
452
503
  } else if (isStopped()) {
453
- return createFailureResult("download_cancelled");
504
+ CapgoUpdater.deleteManifestStagingFolderAt(documentsDir != null ? new File(documentsDir) : null, dest, logger);
505
+ return createFailureResult("download_cancelled", version, dest, true);
454
506
  } else {
455
507
  logger.error("Manifest is null");
456
- return createFailureResult("Manifest is null");
508
+ CapgoUpdater.deleteManifestStagingFolderAt(documentsDir != null ? new File(documentsDir) : null, dest, logger);
509
+ return createFailureResult("Manifest is null", version, dest, true);
457
510
  }
458
511
  } else {
459
512
  handleSingleFileDownload(url, id, documentsDir, dest, version, sessionKey, checksum, publicKey);
@@ -465,7 +518,10 @@ public class DownloadService extends Worker {
465
518
  }
466
519
  return Result.retry();
467
520
  } catch (Exception e) {
468
- return createFailureResult(e.getMessage());
521
+ if (isManifest) {
522
+ CapgoUpdater.deleteManifestStagingFolderAt(documentsDir != null ? new File(documentsDir) : null, dest, logger);
523
+ }
524
+ return createFailureResult(e.getMessage(), version, dest, isManifest);
469
525
  }
470
526
  }
471
527
 
@@ -768,20 +824,16 @@ public class DownloadService extends Worker {
768
824
  throw new RuntimeException("insufficient_disk_space");
769
825
  }
770
826
 
771
- HttpURLConnection httpConn = null;
827
+ Response response = null;
772
828
  InputStream inputStream = null;
773
829
  BufferedReader reader = null;
774
830
  BufferedWriter writer = null;
775
831
 
776
832
  try {
777
- URL u = new URL(url);
778
- httpConn = (HttpURLConnection) u.openConnection();
779
-
780
- // Zip can stall longer than a JSON API call; keep a floor so
781
- // responseTimeout cannot shrink large-bundle downloads.
782
- int zipTimeoutMs = Math.max(httpTimeoutMs, 60_000);
783
- httpConn.setConnectTimeout(zipTimeoutMs);
784
- httpConn.setReadTimeout(zipTimeoutMs);
833
+ HttpUrl zipUrl = url != null ? HttpUrl.parse(url) : null;
834
+ if (zipUrl == null) {
835
+ throw new MalformedURLException("Expected an http or https URL");
836
+ }
785
837
 
786
838
  // Reading progress file (if exist)
787
839
  long downloadedBytes = 0;
@@ -810,15 +862,16 @@ public class DownloadService extends Worker {
810
862
  throw new DownloadRetryException("download_stopped");
811
863
  }
812
864
 
813
- if (downloadedBytes > 0) {
814
- httpConn.setRequestProperty("Range", "bytes=" + downloadedBytes + "-");
815
- }
816
-
817
- int responseCode = httpConn.getResponseCode();
865
+ response = executeZipRequest(zipUrl, downloadedBytes);
866
+ int responseCode = response.code();
818
867
 
819
868
  if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL) {
820
- ZipWritePlan writePlan = planZipResumeWrite(responseCode, downloadedBytes, httpConn.getHeaderField("Content-Range"));
821
- long responseBodyLength = httpConn.getContentLength();
869
+ ResponseBody responseBody = response.body();
870
+ if (responseBody == null) {
871
+ throw new IOException("Response body is null");
872
+ }
873
+ ZipWritePlan writePlan = planZipResumeWrite(responseCode, downloadedBytes, response.header("Content-Range"));
874
+ long responseBodyLength = responseBody.contentLength();
822
875
  long contentLength = shouldAppendHttpBody(writePlan.statusCode, writePlan.writeOffset)
823
876
  ? responseBodyLength >= 0
824
877
  ? responseBodyLength + writePlan.writeOffset
@@ -831,7 +884,7 @@ public class DownloadService extends Worker {
831
884
  }
832
885
 
833
886
  try {
834
- inputStream = httpConn.getInputStream();
887
+ inputStream = responseBody.byteStream();
835
888
 
836
889
  if (writePlan.writeOffset == 0 && downloadedBytes == 0) {
837
890
  writer = new BufferedWriter(new FileWriter(infoFile));
@@ -842,7 +895,7 @@ public class DownloadService extends Worker {
842
895
 
843
896
  final int[] lastNotifiedPercent = { 0 };
844
897
  final long totalContentLength = contentLength;
845
- String contentRangeHeader = httpConn.getHeaderField("Content-Range");
898
+ String contentRangeHeader = response.header("Content-Range");
846
899
  writeHttpBody(tempFile, inputStream, writePlan.statusCode, writePlan.writeOffset, this::isStopped, (written) -> {
847
900
  int percent = calcTotalPercent(written, totalContentLength);
848
901
  if (percent >= lastNotifiedPercent[0] + 10) {
@@ -910,6 +963,9 @@ public class DownloadService extends Worker {
910
963
  } catch (MalformedURLException e) {
911
964
  logger.error("Invalid download URL: " + e.getMessage());
912
965
  throw new RuntimeException("invalid_url: " + e.getMessage());
966
+ } catch (BlockedRedirectException e) {
967
+ logger.error("Download error: " + e.getMessage());
968
+ throw new RuntimeException("blocked_redirect: " + e.getMessage());
913
969
  } catch (IOException e) {
914
970
  logger.error("Download error: " + e.getMessage());
915
971
  throw new DownloadRetryException(e.getMessage(), e);
@@ -918,14 +974,35 @@ public class DownloadService extends Worker {
918
974
  throw new RuntimeException(e.getMessage());
919
975
  } finally {
920
976
  // Ensure connection is closed
921
- if (httpConn != null) {
977
+ if (response != null) {
922
978
  try {
923
- httpConn.disconnect();
979
+ response.close();
924
980
  } catch (Exception ignored) {}
925
981
  }
926
982
  }
927
983
  }
928
984
 
985
+ /**
986
+ * Zip bundle request on the shared client (no cookies, same User-Agent), resuming from
987
+ * {@code downloadedBytes} with a Range header. The caller closes the response.
988
+ */
989
+ static Response executeZipRequest(HttpUrl url, long downloadedBytes) throws IOException {
990
+ // Zip can stall longer than a JSON API call; keep a floor so
991
+ // responseTimeout cannot shrink large-bundle downloads.
992
+ int zipTimeoutMs = Math.max(httpTimeoutMs, 60_000);
993
+ OkHttpClient zipClient = sharedClient
994
+ .newBuilder()
995
+ .connectTimeout(zipTimeoutMs, TimeUnit.MILLISECONDS)
996
+ .readTimeout(zipTimeoutMs, TimeUnit.MILLISECONDS)
997
+ .writeTimeout(zipTimeoutMs, TimeUnit.MILLISECONDS)
998
+ .build();
999
+ Request.Builder builder = new Request.Builder().url(url);
1000
+ if (downloadedBytes > 0) {
1001
+ builder.header("Range", "bytes=" + downloadedBytes + "-");
1002
+ }
1003
+ return zipClient.newCall(builder.build()).execute();
1004
+ }
1005
+
929
1006
  static boolean isRetryableHttpStatus(int responseCode) {
930
1007
  return responseCode >= 500 || responseCode == 408 || responseCode == 429;
931
1008
  }
@@ -0,0 +1,325 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ package ee.forgr.capacitor_updater;
8
+
9
+ import android.app.Activity;
10
+ import android.content.Context;
11
+ import android.content.SharedPreferences;
12
+ import android.content.pm.PackageInfo;
13
+ import android.content.pm.PackageManager;
14
+ import android.os.Build;
15
+ import androidx.annotation.NonNull;
16
+ import androidx.core.content.pm.PackageInfoCompat;
17
+ import androidx.work.Constraints;
18
+ import androidx.work.ExistingWorkPolicy;
19
+ import androidx.work.NetworkType;
20
+ import androidx.work.OneTimeWorkRequest;
21
+ import androidx.work.OutOfQuotaPolicy;
22
+ import androidx.work.WorkManager;
23
+ import androidx.work.Worker;
24
+ import androidx.work.WorkerParameters;
25
+ import com.getcapacitor.CapConfig;
26
+ import com.getcapacitor.PluginConfig;
27
+ import com.getcapacitor.plugin.WebView;
28
+ import java.util.Map;
29
+ import java.util.concurrent.CountDownLatch;
30
+ import java.util.concurrent.TimeUnit;
31
+ import java.util.concurrent.atomic.AtomicReference;
32
+ import org.json.JSONArray;
33
+ import org.json.JSONException;
34
+
35
+ /**
36
+ * Runs a live update check with no Activity and no Capacitor bridge, for example when an
37
+ * update-check push wakes a killed app. The bundle is downloaded and, when the app has no UI,
38
+ * applied as the current bundle so the next launch opens the new version (it still has to call
39
+ * notifyAppReady). Enqueued as unique expedited work so the process stays alive until the bundle
40
+ * is unzipped and stored.
41
+ *
42
+ * When a plugin instance is running in the process, use its native trigger instead
43
+ * (CapacitorUpdaterPlugin#triggerBackgroundUpdateCheck); this worker then only stores the bundle as
44
+ * next and lets that instance install it.
45
+ */
46
+ public class HeadlessUpdateWorker extends Worker {
47
+
48
+ static final String UNIQUE_WORK_NAME = "capacitor_updater_headless_update_check";
49
+ private static final long FINISH_TIMEOUT_MINUTES = 9;
50
+
51
+ public HeadlessUpdateWorker(@NonNull final Context context, @NonNull final WorkerParameters params) {
52
+ super(context, params);
53
+ }
54
+
55
+ /** Queue a headless update check. Safe to call from any thread, including an FCM service. */
56
+ public static void enqueue(@NonNull final Context context) {
57
+ final OneTimeWorkRequest.Builder builder = new OneTimeWorkRequest.Builder(HeadlessUpdateWorker.class)
58
+ .setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
59
+ .addTag(UNIQUE_WORK_NAME);
60
+ // Same as downloads: expedited work starts right away on Android 12+ without a foreground service.
61
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
62
+ builder.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST);
63
+ }
64
+ WorkManager.getInstance(context.getApplicationContext()).enqueueUniqueWork(
65
+ UNIQUE_WORK_NAME,
66
+ ExistingWorkPolicy.KEEP,
67
+ builder.build()
68
+ );
69
+ }
70
+
71
+ @NonNull
72
+ @Override
73
+ public Result doWork() {
74
+ final Logger logger = new Logger("CapgoUpdater");
75
+ try {
76
+ final String status = run(getApplicationContext(), logger);
77
+ logger.info("Headless update check finished: " + status);
78
+ } catch (final Exception e) {
79
+ logger.error("Headless update check failed: " + e.getMessage());
80
+ }
81
+ // Never retry: the next launch or push runs a fresh check.
82
+ return Result.success();
83
+ }
84
+
85
+ static String run(final Context context, final Logger logger) throws PackageManager.NameNotFoundException {
86
+ if (CapacitorUpdaterPlugin.instanceLoaded) {
87
+ // The running plugin instance owns downloads and installs in this process.
88
+ return "handed_over";
89
+ }
90
+ final CapConfig capConfig = CapConfig.loadDefault(context);
91
+ final PluginConfig config = capConfig.getPluginConfiguration("CapacitorUpdater");
92
+ final String serverUrl = capConfig.getServerUrl();
93
+ if (serverUrl != null && !serverUrl.isEmpty()) {
94
+ return "unavailable";
95
+ }
96
+ final String autoUpdateMode = CapacitorUpdaterPlugin.autoUpdateModeFromConfig(config, logger);
97
+ if (!CapacitorUpdaterPlugin.isAutoUpdateModeEnabled(autoUpdateMode)) {
98
+ return "unavailable";
99
+ }
100
+
101
+ final SharedPreferences prefs = context.getSharedPreferences(WebView.WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE);
102
+ final boolean allowPreview = config.getBoolean("allowPreview", false);
103
+ if (allowPreview && prefs.getBoolean(CapacitorUpdaterPlugin.PREVIEW_SESSION_PREF_KEY, false)) {
104
+ return "preview_session";
105
+ }
106
+
107
+ final PackageInfo packageInfo = getPackageInfo(context);
108
+ final String versionCode = Long.toString(PackageInfoCompat.getLongVersionCode(packageInfo));
109
+ // After a native update the launch resets bundles first (resetWhenUpdate): leave it to the launch.
110
+ if (nativeBuildChanged(prefs, versionCode)) {
111
+ return "native_update_pending";
112
+ }
113
+
114
+ final boolean setNext = CapacitorUpdaterPlugin.shouldAutoUpdateModeSetNextBundle(autoUpdateMode);
115
+ final CountDownLatch finished = new CountDownLatch(1);
116
+ final AtomicReference<String> result = new AtomicReference<>("no_update");
117
+ final CapgoUpdater updater = new CapgoUpdater(logger) {
118
+ @Override
119
+ void nextBundleReady(final BundleInfo bundle) {
120
+ result.set(applyIfNoUi(this, bundle, logger) ? "installed" : "queued");
121
+ finished.countDown();
122
+ }
123
+
124
+ @Override
125
+ void notifyListeners(final String id, final Map<String, Object> res) {
126
+ if ("downloadFailed".equals(id)) {
127
+ result.set("failed");
128
+ finished.countDown();
129
+ } else if ("updateAvailable".equals(id) && !setNext) {
130
+ result.set("downloaded");
131
+ finished.countDown();
132
+ }
133
+ }
134
+ };
135
+ configure(updater, context, capConfig, config, prefs, packageInfo, versionCode);
136
+ try {
137
+ String updateUrl = config.getString("updateUrl", CapacitorUpdaterPlugin.updateUrlDefault);
138
+ if (config.getBoolean("persistModifyUrl", false) && prefs.contains(CapacitorUpdaterPlugin.UPDATE_URL_PREF_KEY)) {
139
+ updateUrl = prefs.getString(CapacitorUpdaterPlugin.UPDATE_URL_PREF_KEY, updateUrl);
140
+ }
141
+ if (updateUrl == null || updateUrl.isEmpty()) {
142
+ return "unavailable";
143
+ }
144
+
145
+ final AtomicReference<Map<String, Object>> latestRef = new AtomicReference<>();
146
+ final CountDownLatch latestDone = new CountDownLatch(1);
147
+ updater.getLatest(updateUrl, null, (res) -> {
148
+ latestRef.set(res);
149
+ latestDone.countDown();
150
+ });
151
+ try {
152
+ if (!latestDone.await(updater.timeout + 5000L, TimeUnit.MILLISECONDS)) {
153
+ return "failed";
154
+ }
155
+ } catch (final InterruptedException e) {
156
+ Thread.currentThread().interrupt();
157
+ return "failed";
158
+ }
159
+ final Map<String, Object> latest = latestRef.get();
160
+ if (latest == null || latest.containsKey("error") || latest.containsKey("kind")) {
161
+ return "no_update";
162
+ }
163
+ final String version = String.valueOf(latest.get("version"));
164
+ final Object url = latest.get("url");
165
+ final BundleInfo current = updater.getCurrentBundle();
166
+ if ("builtin".equals(version) || version.isEmpty() || version.equals(current.getVersionName()) || !(url instanceof String)) {
167
+ return "no_update";
168
+ }
169
+ final String sessionKey = latest.get("sessionKey") instanceof String ? (String) latest.get("sessionKey") : "";
170
+ final String checksum = latest.get("checksum") instanceof String ? (String) latest.get("checksum") : "";
171
+
172
+ final BundleInfo existing = updater.getBundleInfoByName(version);
173
+ if (existing != null && existing.isErrorStatus()) {
174
+ return "failed";
175
+ }
176
+ if (existing != null && existing.isDownloaded() && BundleStatus.DOWNLOADING != existing.getStatus()) {
177
+ if (setNext && updater.setNextBundle(existing.getId())) {
178
+ return applyIfNoUi(updater, existing, logger) ? "installed" : "queued";
179
+ }
180
+ return "downloaded";
181
+ }
182
+
183
+ // downloadBackground returns null when it refuses the download (blocked encryption, gate,
184
+ // version already downloading): only wait for a download it started.
185
+ final String startedId = updater.downloadBackground((String) url, version, sessionKey, checksum, manifestOf(latest), setNext);
186
+ if (startedId == null) {
187
+ return "skipped";
188
+ }
189
+ final long deadline = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(FINISH_TIMEOUT_MINUTES);
190
+ try {
191
+ // Keep the worker (and so the process) alive until the bundle is stored. If the user opens
192
+ // the app meanwhile, its plugin instance takes over the download (it restarts downloads it
193
+ // does not observe), so stop waiting.
194
+ while (!finished.await(1, TimeUnit.SECONDS)) {
195
+ if (CapacitorUpdaterPlugin.instanceLoaded) {
196
+ return "handed_over";
197
+ }
198
+ if (System.currentTimeMillis() > deadline) {
199
+ return "timeout";
200
+ }
201
+ }
202
+ } catch (final InterruptedException e) {
203
+ Thread.currentThread().interrupt();
204
+ return "interrupted";
205
+ }
206
+ return result.get();
207
+ } finally {
208
+ // Once the plugin instance is up it owns the stats file: hand it our unsent events
209
+ // instead of overwriting its newer file.
210
+ if (CapacitorUpdaterPlugin.instanceLoaded) {
211
+ updater.handOverPendingStats();
212
+ updater.shutdown(false);
213
+ } else {
214
+ updater.shutdown(true);
215
+ }
216
+ }
217
+ }
218
+
219
+ /**
220
+ * With no plugin instance (no bridge, no WebView) nothing shows the current bundle, so switching
221
+ * it is the same as installing on a background transition. Delay conditions keep it as next.
222
+ */
223
+ static boolean applyIfNoUi(final CapgoUpdater updater, final BundleInfo bundle, final Logger logger) {
224
+ if (CapacitorUpdaterPlugin.instanceLoaded) {
225
+ return false;
226
+ }
227
+ final String delays = updater.prefs.getString(DelayUpdateUtils.DELAY_CONDITION_PREFERENCES, "[]");
228
+ if (delays != null && !"[]".equals(delays.trim())) {
229
+ logger.info("Update delayed until delay conditions met");
230
+ return false;
231
+ }
232
+ if (updater.set(bundle)) {
233
+ updater.setNextBundle(null);
234
+ logger.info("Installed bundle " + bundle.getVersionName() + " for the next launch");
235
+ return true;
236
+ }
237
+ return false;
238
+ }
239
+
240
+ static JSONArray manifestOf(final Map<String, Object> latest) {
241
+ final Object manifest = latest.get("manifest");
242
+ if (manifest instanceof JSONArray) {
243
+ return (JSONArray) manifest;
244
+ }
245
+ if (manifest instanceof String) {
246
+ try {
247
+ return new JSONArray((String) manifest);
248
+ } catch (final JSONException e) {
249
+ return null;
250
+ }
251
+ }
252
+ return null;
253
+ }
254
+
255
+ static boolean nativeBuildChanged(final SharedPreferences prefs, final String versionCode) {
256
+ String previous = prefs.getString("LatestNativeBuildVersion", "");
257
+ if (previous == null || previous.isEmpty()) {
258
+ previous = prefs.getString("LatestVersionNative", "");
259
+ }
260
+ return previous != null && !previous.isEmpty() && !previous.equals(versionCode);
261
+ }
262
+
263
+ private static PackageInfo getPackageInfo(final Context context) throws PackageManager.NameNotFoundException {
264
+ final PackageManager packageManager = context.getPackageManager();
265
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
266
+ return packageManager.getPackageInfo(context.getPackageName(), PackageManager.PackageInfoFlags.of(0));
267
+ }
268
+ return packageManager.getPackageInfo(context.getPackageName(), 0);
269
+ }
270
+
271
+ /** Mirrors the identity and URL setup of CapacitorUpdaterPlugin#load. */
272
+ private static void configure(
273
+ final CapgoUpdater updater,
274
+ final Context context,
275
+ final CapConfig capConfig,
276
+ final PluginConfig config,
277
+ final SharedPreferences prefs,
278
+ final PackageInfo packageInfo,
279
+ final String versionCode
280
+ ) {
281
+ updater.appContext = context;
282
+ updater.prefs = prefs;
283
+ updater.editor = prefs.edit();
284
+ updater.documentsDir = context.getFilesDir();
285
+ updater.noBackupDir = context.getNoBackupFilesDir();
286
+ // Shares the plugin's pending-stats file: load it first so a flush does not overwrite it.
287
+ updater.restorePendingStats();
288
+ updater.CAP_SERVER_PATH = WebView.CAP_SERVER_PATH;
289
+ updater.pluginVersion = CapacitorUpdaterPlugin.PLUGIN_VERSION;
290
+ updater.versionBuild = config.getString("version", packageInfo.versionName);
291
+ updater.versionCode = versionCode;
292
+ updater.versionOs = Build.VERSION.RELEASE;
293
+
294
+ String appId = InternalUtils.getPackageName(context.getPackageManager(), context.getPackageName());
295
+ appId = capConfig.getString("appId", appId);
296
+ updater.appId = config.getString("appId", appId);
297
+ updater.setPublicKey(config.getString("publicKey", ""));
298
+
299
+ final boolean persistModifyUrl = config.getBoolean("persistModifyUrl", false);
300
+ updater.statsUrl = config.getString("statsUrl", CapacitorUpdaterPlugin.statsUrlDefault);
301
+ updater.channelUrl = config.getString("channelUrl", CapacitorUpdaterPlugin.channelUrlDefault);
302
+ if (persistModifyUrl) {
303
+ updater.statsUrl = prefs.getString(CapacitorUpdaterPlugin.STATS_URL_PREF_KEY, updater.statsUrl);
304
+ updater.channelUrl = prefs.getString(CapacitorUpdaterPlugin.CHANNEL_URL_PREF_KEY, updater.channelUrl);
305
+ }
306
+
307
+ final String storedDefaultChannel = prefs.getString(CapacitorUpdaterPlugin.DEFAULT_CHANNEL_PREF_KEY, "");
308
+ updater.defaultChannel =
309
+ storedDefaultChannel != null && !storedDefaultChannel.isEmpty() ? storedDefaultChannel : config.getString("defaultChannel", "");
310
+
311
+ if (config.getBoolean("persistCustomId", false)) {
312
+ final String storedCustomId = prefs.getString(CapacitorUpdaterPlugin.CUSTOM_ID_PREF_KEY, "");
313
+ if (storedCustomId != null && !storedCustomId.isEmpty()) {
314
+ updater.customId = storedCustomId;
315
+ }
316
+ }
317
+ updater.deviceID = DeviceIdHelper.getOrCreateDeviceId(context, prefs);
318
+
319
+ final int responseTimeoutSeconds = config.getInt("responseTimeout", 20);
320
+ final long responseTimeoutMillis = responseTimeoutSeconds > 0 ? (long) responseTimeoutSeconds * 1000L : 20_000L;
321
+ updater.timeout = (int) Math.min(Integer.MAX_VALUE, responseTimeoutMillis);
322
+ DownloadService.applyHttpTimeouts(updater.timeout);
323
+ DownloadService.updateUserAgent(updater.appId, updater.pluginVersion, updater.versionOs);
324
+ }
325
+ }