@capgo/capacitor-updater 7.51.21 → 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 +202 -67
  4. package/android/build.gradle +2 -3
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +610 -177
  6. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +909 -196
  7. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +53 -19
  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 +210 -58
  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 +562 -187
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  20. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +564 -109
  21. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +11 -2
  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 +9 -3
  27. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  28. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  29. package/package.json +7 -3
@@ -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
+ }
@@ -5,15 +5,24 @@ import android.util.Log;
5
5
  import androidx.annotation.NonNull;
6
6
  import androidx.annotation.Nullable;
7
7
  import com.getcapacitor.*;
8
+ import java.nio.ByteBuffer;
9
+ import java.nio.CharBuffer;
10
+ import java.nio.charset.CharsetEncoder;
11
+ import java.nio.charset.CoderResult;
12
+ import java.nio.charset.CodingErrorAction;
13
+ import java.nio.charset.StandardCharsets;
8
14
  import java.util.ArrayList;
9
15
  import java.util.Arrays;
10
16
  import java.util.Date;
11
17
  import java.util.Locale;
12
18
  import java.util.Map;
13
19
  import org.jetbrains.annotations.Contract;
20
+ import org.json.JSONObject;
14
21
 
15
22
  public class Logger {
16
23
 
24
+ static final int MAX_WEBVIEW_LOG_PAYLOAD_CHARS = 4096;
25
+
17
26
  private Bridge bridge;
18
27
 
19
28
  public enum LogLevel {
@@ -261,13 +270,63 @@ public class Logger {
261
270
 
262
271
  // Send to JavaScript if webView is available
263
272
  if (bridge != null && bridge.getWebView() != null) {
264
- bridge.eval(
265
- "console." + level.name() + "(\"[" + tag.replace("\"", "\\\"") + "] " + formattedMessage.replace("\"", "\\\"") + "\")",
266
- null
267
- );
273
+ String script = buildWebViewConsoleScript(level, tag, formattedMessage);
274
+ if (script != null) {
275
+ bridge.eval(script, null);
276
+ }
277
+ }
278
+ }
279
+
280
+ @Nullable
281
+ static String consoleMethodForLevel(@NonNull LogLevel level) {
282
+ switch (level) {
283
+ case error:
284
+ return "error";
285
+ case warn:
286
+ return "warn";
287
+ case info:
288
+ return "info";
289
+ case debug:
290
+ return "debug";
291
+ default:
292
+ return null;
268
293
  }
269
294
  }
270
295
 
296
+ @NonNull
297
+ static String toJsStringLiteral(@NonNull String value) {
298
+ return JSONObject.quote(value);
299
+ }
300
+
301
+ @NonNull
302
+ static String capWebViewLogPayload(@NonNull String payload) {
303
+ CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder()
304
+ .onMalformedInput(CodingErrorAction.REPLACE)
305
+ .onUnmappableCharacter(CodingErrorAction.REPLACE);
306
+ ByteBuffer bytes = ByteBuffer.allocate(MAX_WEBVIEW_LOG_PAYLOAD_CHARS);
307
+ CharBuffer chars = CharBuffer.wrap(payload);
308
+ CoderResult result = encoder.encode(chars, bytes, true);
309
+ if (result.isUnderflow()) {
310
+ result = encoder.flush(bytes);
311
+ }
312
+ if (result.isUnderflow()) {
313
+ return payload;
314
+ }
315
+
316
+ return new String(bytes.array(), 0, bytes.position(), StandardCharsets.UTF_8) + "...";
317
+ }
318
+
319
+ @Nullable
320
+ static String buildWebViewConsoleScript(@NonNull LogLevel level, @NonNull String tag, @NonNull String formattedMessage) {
321
+ String consoleMethod = consoleMethodForLevel(level);
322
+ if (consoleMethod == null) {
323
+ return null;
324
+ }
325
+
326
+ String payload = capWebViewLogPayload("[" + tag + "] " + formattedMessage);
327
+ return "console." + consoleMethod + "(" + toJsStringLiteral(payload) + ")";
328
+ }
329
+
271
330
  public void dir(Object value) {
272
331
  String message;
273
332