@capgo/capacitor-updater 9.0.0 → 9.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CapgoCapacitorUpdater.podspec +3 -6
  2. package/Package.swift +30 -0
  3. package/README.md +2406 -291
  4. package/android/build.gradle +37 -17
  5. package/android/consumer-rules.pro +48 -0
  6. package/android/proguard-rules.pro +23 -0
  7. package/android/src/main/AndroidManifest.xml +0 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +92 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +115 -0
  10. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +227 -195
  11. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +24 -23
  12. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +7927 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5785 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +564 -121
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +43 -49
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
  19. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +230 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +2041 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +301 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +569 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +436 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +604 -0
  26. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +79 -0
  27. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +419 -0
  28. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  29. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
  30. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +963 -0
  31. package/android/src/main/java/ee/forgr/capacitor_updater/StatsBatchFailureDiagnostics.java +40 -0
  32. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +323 -0
  33. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  34. package/dist/docs.json +4431 -840
  35. package/dist/esm/definitions.d.ts +2641 -225
  36. package/dist/esm/definitions.js +103 -1
  37. package/dist/esm/definitions.js.map +1 -1
  38. package/dist/esm/history.d.ts +1 -0
  39. package/dist/esm/history.js +283 -0
  40. package/dist/esm/history.js.map +1 -0
  41. package/dist/esm/index.d.ts +3 -2
  42. package/dist/esm/index.js +5 -4
  43. package/dist/esm/index.js.map +1 -1
  44. package/dist/esm/web.d.ts +53 -42
  45. package/dist/esm/web.js +180 -37
  46. package/dist/esm/web.js.map +1 -1
  47. package/dist/plugin.cjs.js +570 -37
  48. package/dist/plugin.cjs.js.map +1 -1
  49. package/dist/plugin.js +570 -37
  50. package/dist/plugin.js.map +1 -1
  51. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  52. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  53. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  54. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  55. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +6813 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +200 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +5099 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +387 -0
  60. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  61. package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
  62. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +452 -0
  63. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +380 -0
  64. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  65. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  66. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +97 -0
  67. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +876 -0
  68. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
  69. package/ios/Sources/CapacitorUpdaterPlugin/WKWebView+CapgoObjcBridge.swift +20 -0
  70. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +304 -0
  71. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  72. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  73. package/ios/Tests/CapacitorUpdaterPluginTests/BuiltinHashesTests.swift +210 -0
  74. package/ios/Tests/CapacitorUpdaterPluginTests/BundleHardeningTests.swift +292 -0
  75. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +6533 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +156 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +314 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +653 -0
  80. package/ios/Tests/CapacitorUpdaterPluginTests/InstallPerfTests.swift +174 -0
  81. package/ios/Tests/CapacitorUpdaterPluginTests/ListChannelsTests.swift +74 -0
  82. package/ios/Tests/CapacitorUpdaterPluginTests/LoggerSecurityTests.swift +149 -0
  83. package/ios/Tests/CapacitorUpdaterPluginTests/NativeContractTests.swift +160 -0
  84. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +1109 -0
  85. package/ios/Tests/CapacitorUpdaterPluginTests/PopulateDeltaCacheTests.swift +573 -0
  86. package/ios/Tests/CapacitorUpdaterPluginTests/RedirectPolicyTests.swift +63 -0
  87. package/ios/Tests/CapacitorUpdaterPluginTests/RsaContractTests.swift +281 -0
  88. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +196 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +470 -0
  91. package/ios/Tests/CapacitorUpdaterPluginTests/WebKitOverlayGuardTests.swift +32 -0
  92. package/ios/Tests/CapacitorUpdaterPluginTests/ZipArchiveReaderTests.swift +302 -0
  93. package/ios/Tests/CapacitorUpdaterPluginTests/ZipBundleExtractionTests.swift +122 -0
  94. package/package.json +80 -43
  95. package/scripts/builtin-hashes-lib.mjs +148 -0
  96. package/scripts/capacitor-builtin-hashes-hook.mjs +65 -0
  97. package/scripts/resolve-real-path.mjs +25 -0
  98. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1130
  99. package/ios/Plugin/BundleInfo.swift +0 -113
  100. package/ios/Plugin/BundleStatus.swift +0 -48
  101. package/ios/Plugin/CapacitorUpdater.swift +0 -858
  102. package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
  103. package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
  104. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -677
  105. package/ios/Plugin/CryptoCipher.swift +0 -240
  106. /package/{LICENCE → LICENSE} +0 -0
  107. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  108. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  109. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -0,0 +1,963 @@
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.app.AlertDialog;
11
+ import android.content.DialogInterface;
12
+ import android.hardware.SensorManager;
13
+ import android.text.Editable;
14
+ import android.text.TextWatcher;
15
+ import android.widget.ArrayAdapter;
16
+ import android.widget.Button;
17
+ import android.widget.EditText;
18
+ import android.widget.LinearLayout;
19
+ import android.widget.ListView;
20
+ import android.widget.ProgressBar;
21
+ import com.getcapacitor.Bridge;
22
+ import com.getcapacitor.BridgeActivity;
23
+ import com.getcapacitor.JSArray;
24
+ import com.getcapacitor.JSObject;
25
+ import java.util.ArrayList;
26
+ import java.util.List;
27
+ import java.util.Map;
28
+ import org.json.JSONArray;
29
+ import org.json.JSONObject;
30
+
31
+ public class ShakeMenu implements ShakeDetector.Listener, ThreeFingerPinchDetector.Listener {
32
+
33
+ private interface PreviewMenuAction {
34
+ boolean run();
35
+ }
36
+
37
+ private CapacitorUpdaterPlugin plugin;
38
+ private BridgeActivity activity;
39
+ private ShakeDetector shakeDetector;
40
+ private ThreeFingerPinchDetector pinchDetector;
41
+ private boolean isShowing = false;
42
+ private Logger logger;
43
+ private String gesture;
44
+
45
+ public ShakeMenu(CapacitorUpdaterPlugin plugin, BridgeActivity activity, Logger logger, String gesture) {
46
+ this.plugin = plugin;
47
+ this.activity = activity;
48
+ this.logger = logger;
49
+ this.gesture = gesture;
50
+
51
+ if (CapacitorUpdaterPlugin.SHAKE_MENU_GESTURE_THREE_FINGER_PINCH.equals(gesture)) {
52
+ this.pinchDetector = new ThreeFingerPinchDetector(this, logger);
53
+ this.pinchDetector.start(activity);
54
+ } else {
55
+ SensorManager sensorManager = (SensorManager) activity.getSystemService(Activity.SENSOR_SERVICE);
56
+ this.shakeDetector = new ShakeDetector(this);
57
+ this.shakeDetector.start(sensorManager);
58
+ }
59
+ }
60
+
61
+ public boolean usesGesture(String gesture) {
62
+ return this.gesture != null && this.gesture.equals(gesture);
63
+ }
64
+
65
+ public void stop() {
66
+ if (shakeDetector != null) {
67
+ shakeDetector.stop();
68
+ }
69
+ if (pinchDetector != null) {
70
+ pinchDetector.stop();
71
+ }
72
+ }
73
+
74
+ @Override
75
+ public void onShakeDetected() {
76
+ onMenuGestureDetected("Shake");
77
+ }
78
+
79
+ @Override
80
+ public void onThreeFingerPinchDetected() {
81
+ onMenuGestureDetected("Three finger pinch");
82
+ }
83
+
84
+ private void onMenuGestureDetected(String gestureName) {
85
+ logger.info(gestureName + " detected");
86
+
87
+ boolean canShowPreviewMenu = Boolean.TRUE.equals(plugin.shakeMenuEnabled) && plugin.hasActivePreviewSession();
88
+ boolean canShowChannelSelector = Boolean.TRUE.equals(plugin.shakeChannelSelectorEnabled);
89
+ if (!canShowPreviewMenu && !canShowChannelSelector) {
90
+ if (Boolean.TRUE.equals(plugin.shakeMenuEnabled)) {
91
+ logger.info("Shake preview menu ignored because no preview session is active");
92
+ } else {
93
+ logger.info("Shake menu is disabled");
94
+ }
95
+ return;
96
+ }
97
+
98
+ // Prevent multiple dialogs
99
+ if (isShowing) {
100
+ logger.info("Dialog already showing");
101
+ return;
102
+ }
103
+
104
+ isShowing = true;
105
+
106
+ if (canShowPreviewMenu) {
107
+ showDefaultMenu();
108
+ } else {
109
+ showChannelSelector();
110
+ }
111
+ }
112
+
113
+ private void showDefaultMenu() {
114
+ activity.runOnUiThread(() -> {
115
+ try {
116
+ if (!plugin.hasActivePreviewSession()) {
117
+ logger.info("Shake preview menu ignored because no preview session is active");
118
+ isShowing = false;
119
+ return;
120
+ }
121
+
122
+ showPreviewActionsMenu(Boolean.TRUE.equals(plugin.shakeChannelSelectorEnabled));
123
+ } catch (Exception e) {
124
+ logger.error("Error showing shake menu: " + e.getMessage());
125
+ isShowing = false;
126
+ }
127
+ });
128
+ }
129
+
130
+ private void showPreviewActionsMenu(boolean includeChannelSelector) {
131
+ String appName = activity.getPackageManager().getApplicationLabel(activity.getApplicationInfo()).toString();
132
+ String title = "Preview " + appName + " Menu";
133
+ String message = "Reload, switch, or leave the current preview.";
134
+ final boolean[] openingNestedSelector = { false };
135
+ final boolean[] previewActionRunning = { false };
136
+ final AlertDialog[] dialogRef = { null };
137
+ List<Button> buttons = new ArrayList<>();
138
+
139
+ LinearLayout layout = new LinearLayout(activity);
140
+ layout.setOrientation(LinearLayout.VERTICAL);
141
+ int horizontalPadding = dpToPx(16);
142
+ int verticalPadding = dpToPx(8);
143
+ layout.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding);
144
+
145
+ addPreviewMenuButton(layout, buttons, "Reload preview", () -> {
146
+ AlertDialog dialog = dialogRef[0];
147
+ previewActionRunning[0] = true;
148
+ setPreviewMenuButtonsEnabled(buttons, false);
149
+ logger.info("Reloading webview");
150
+ runPreviewMenuAction(dialog, "Could not reload the test app.", "Error reloading test app: ", () ->
151
+ plugin.reloadPreviewSessionFromShakeMenu()
152
+ );
153
+ });
154
+
155
+ if (plugin.previewMenuPreviews().length() > 0) {
156
+ addPreviewMenuButton(layout, buttons, "Switch preview", () -> {
157
+ AlertDialog dialog = dialogRef[0];
158
+ openingNestedSelector[0] = true;
159
+ dialog.dismiss();
160
+ showPreviewSelector();
161
+ });
162
+ }
163
+
164
+ if (includeChannelSelector) {
165
+ addPreviewMenuButton(layout, buttons, "Switch channel", () -> {
166
+ AlertDialog dialog = dialogRef[0];
167
+ openingNestedSelector[0] = true;
168
+ dialog.dismiss();
169
+ showChannelSelector();
170
+ });
171
+ }
172
+
173
+ addPreviewMenuButton(layout, buttons, "Leave test app", () -> {
174
+ AlertDialog dialog = dialogRef[0];
175
+ previewActionRunning[0] = true;
176
+ setPreviewMenuButtonsEnabled(buttons, false);
177
+ runPreviewMenuAction(dialog, "Could not leave the test app.", "Error leaving test app: ", () ->
178
+ plugin.leavePreviewSessionFromShakeMenu()
179
+ );
180
+ });
181
+
182
+ addPreviewMenuButton(layout, buttons, "Close menu", () -> {
183
+ AlertDialog dialog = dialogRef[0];
184
+ if (dialog != null) {
185
+ logger.info("Shake menu cancelled");
186
+ dialog.dismiss();
187
+ isShowing = false;
188
+ }
189
+ });
190
+
191
+ AlertDialog.Builder builder = new AlertDialog.Builder(activity);
192
+ builder.setTitle(title);
193
+ builder.setMessage(message);
194
+ builder.setView(layout);
195
+
196
+ AlertDialog dialog = builder.create();
197
+ dialogRef[0] = dialog;
198
+ dialog.setOnDismissListener((dialogInterface) -> {
199
+ if (!openingNestedSelector[0] && !previewActionRunning[0]) {
200
+ isShowing = false;
201
+ }
202
+ });
203
+ dialog.show();
204
+ }
205
+
206
+ private void addPreviewMenuButton(LinearLayout layout, List<Button> buttons, String title, Runnable action) {
207
+ Button button = new Button(activity);
208
+ button.setAllCaps(false);
209
+ button.setText(title);
210
+ LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
211
+ LinearLayout.LayoutParams.MATCH_PARENT,
212
+ LinearLayout.LayoutParams.WRAP_CONTENT
213
+ );
214
+ params.setMargins(0, 0, 0, dpToPx(8));
215
+ button.setLayoutParams(params);
216
+ button.setOnClickListener((view) -> action.run());
217
+ buttons.add(button);
218
+ layout.addView(button);
219
+ }
220
+
221
+ private void runPreviewMenuAction(AlertDialog dialog, String failureMessage, String errorPrefix, PreviewMenuAction action) {
222
+ new Thread(() -> {
223
+ try {
224
+ if (!action.run()) {
225
+ activity.runOnUiThread(() -> showError(failureMessage));
226
+ }
227
+ } catch (Exception e) {
228
+ logger.error(errorPrefix + e.getMessage());
229
+ activity.runOnUiThread(() -> showError(errorPrefix + e.getMessage()));
230
+ } finally {
231
+ activity.runOnUiThread(() -> {
232
+ dialog.dismiss();
233
+ isShowing = false;
234
+ });
235
+ }
236
+ }).start();
237
+ }
238
+
239
+ private void setPreviewMenuButtonsEnabled(List<Button> buttons, boolean enabled) {
240
+ for (Button button : buttons) {
241
+ if (!enabled && "Close menu".equals(button.getText().toString())) {
242
+ continue;
243
+ }
244
+ button.setEnabled(enabled);
245
+ }
246
+ }
247
+
248
+ private void showPreviewSelector() {
249
+ activity.runOnUiThread(() -> {
250
+ try {
251
+ JSArray previewsRaw = plugin.previewMenuPreviews();
252
+ List<JSObject> previews = new ArrayList<>();
253
+ for (int i = 0; i < previewsRaw.length(); i++) {
254
+ Object raw = previewsRaw.opt(i);
255
+ if (raw instanceof JSObject preview) {
256
+ previews.add(preview);
257
+ } else if (raw instanceof JSONObject json) {
258
+ previews.add(JSObject.fromJSONObject(json));
259
+ }
260
+ }
261
+
262
+ if (previews.isEmpty()) {
263
+ showError("No saved previews available on this device.");
264
+ return;
265
+ }
266
+
267
+ presentPreviewPicker(previews);
268
+ } catch (Exception e) {
269
+ logger.error("Error showing preview selector: " + e.getMessage());
270
+ isShowing = false;
271
+ }
272
+ });
273
+ }
274
+
275
+ private String previewLabel(JSObject preview) {
276
+ String name = preview.optString("name", "");
277
+ JSObject bundle = preview.getJSObject("bundle");
278
+ String version = bundle == null ? "" : bundle.optString("version", "");
279
+ String label = !name.isEmpty() ? name : !version.isEmpty() ? version : preview.optString("id", "Preview");
280
+ if (preview.optBoolean("isActive", false)) {
281
+ label += " (current)";
282
+ }
283
+ return label;
284
+ }
285
+
286
+ private void presentPreviewPicker(List<JSObject> previews) {
287
+ try {
288
+ AlertDialog.Builder builder = new AlertDialog.Builder(activity);
289
+ builder.setTitle("Select Preview");
290
+
291
+ LinearLayout layout = new LinearLayout(activity);
292
+ layout.setOrientation(LinearLayout.VERTICAL);
293
+ int padding = dpToPx(16);
294
+ layout.setPadding(padding, padding, padding, padding);
295
+
296
+ EditText searchField = new EditText(activity);
297
+ searchField.setHint("Search previews...");
298
+ searchField.setSingleLine(true);
299
+ layout.addView(searchField);
300
+
301
+ final List<JSObject> displayedPreviews = new ArrayList<>();
302
+ displayedPreviews.addAll(previews.subList(0, Math.min(5, previews.size())));
303
+ final ArrayAdapter<String> adapter = new ArrayAdapter<>(
304
+ activity,
305
+ android.R.layout.simple_list_item_1,
306
+ previewLabels(displayedPreviews)
307
+ );
308
+
309
+ ListView listView = new ListView(activity);
310
+ listView.setAdapter(adapter);
311
+ LinearLayout.LayoutParams listParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dpToPx(250));
312
+ listView.setLayoutParams(listParams);
313
+ layout.addView(listView);
314
+
315
+ builder.setView(layout);
316
+ builder.setNegativeButton("Cancel", (dialog, which) -> {
317
+ dialog.dismiss();
318
+ isShowing = false;
319
+ });
320
+
321
+ AlertDialog dialog = builder.create();
322
+ dialog.setOnDismissListener((d) -> isShowing = false);
323
+
324
+ searchField.addTextChangedListener(
325
+ new TextWatcher() {
326
+ @Override
327
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
328
+
329
+ @Override
330
+ public void onTextChanged(CharSequence s, int start, int before, int count) {}
331
+
332
+ @Override
333
+ public void afterTextChanged(Editable s) {
334
+ String query = s.toString().toLowerCase();
335
+ displayedPreviews.clear();
336
+
337
+ for (JSObject preview : previews) {
338
+ if (previewLabel(preview).toLowerCase().contains(query)) {
339
+ displayedPreviews.add(preview);
340
+ if (displayedPreviews.size() >= 5) break;
341
+ }
342
+ }
343
+
344
+ adapter.clear();
345
+ adapter.addAll(previewLabels(displayedPreviews));
346
+ adapter.notifyDataSetChanged();
347
+ }
348
+ }
349
+ );
350
+
351
+ listView.setOnItemClickListener((parent, view, position, id) -> {
352
+ JSObject selectedPreview = displayedPreviews.get(position);
353
+ String previewId = selectedPreview.optString("id", "");
354
+ dialog.dismiss();
355
+ selectPreview(previewId);
356
+ });
357
+
358
+ dialog.show();
359
+ } catch (Exception e) {
360
+ logger.error("Error presenting preview picker: " + e.getMessage());
361
+ isShowing = false;
362
+ }
363
+ }
364
+
365
+ private List<String> previewLabels(List<JSObject> previews) {
366
+ List<String> labels = new ArrayList<>();
367
+ for (JSObject preview : previews) {
368
+ labels.add(previewLabel(preview));
369
+ }
370
+ return labels;
371
+ }
372
+
373
+ private void selectPreview(String previewId) {
374
+ new Thread(() -> {
375
+ try {
376
+ if (!plugin.setPreviewFromShakeMenu(previewId)) {
377
+ activity.runOnUiThread(() -> showError("Could not switch preview."));
378
+ }
379
+ } catch (Exception e) {
380
+ logger.error("Error switching preview: " + e.getMessage());
381
+ activity.runOnUiThread(() -> showError("Error switching preview: " + e.getMessage()));
382
+ } finally {
383
+ isShowing = false;
384
+ }
385
+ }).start();
386
+ }
387
+
388
+ private void showConfiguredDefaultMenu() {
389
+ activity.runOnUiThread(() -> {
390
+ try {
391
+ String appName = activity.getPackageManager().getApplicationLabel(activity.getApplicationInfo()).toString();
392
+ String title = "Preview " + appName + " Menu";
393
+ String message = "What would you like to do?";
394
+ String okButtonTitle = "Go Home";
395
+ String reloadButtonTitle = "Reload app";
396
+ String cancelButtonTitle = "Close menu";
397
+
398
+ CapgoUpdater updater = plugin.implementation;
399
+ Bridge bridge = activity.getBridge();
400
+
401
+ AlertDialog.Builder builder = new AlertDialog.Builder(activity);
402
+ builder.setTitle(title);
403
+ builder.setMessage(message);
404
+
405
+ // Go Home button
406
+ builder.setPositiveButton(
407
+ okButtonTitle,
408
+ new DialogInterface.OnClickListener() {
409
+ public void onClick(DialogInterface dialog, int id) {
410
+ try {
411
+ BundleInfo current = updater.getCurrentBundle();
412
+ logger.info("Current bundle: " + current.toString());
413
+
414
+ BundleInfo next = updater.getNextBundle();
415
+ logger.info("Next bundle: " + (next != null ? next.toString() : "null"));
416
+
417
+ if (next != null && !next.isBuiltin()) {
418
+ logger.info("Setting bundle to: " + next.toString());
419
+ // A pending bundle below the native version floor is rejected: fall back to builtin.
420
+ if (!Boolean.TRUE.equals(updater.set(next))) {
421
+ logger.warn("Cannot activate " + next.toString() + ", resetting to builtin");
422
+ updater.reset();
423
+ }
424
+ String path = updater.getCurrentBundlePath();
425
+ logger.info("Setting server path: " + path);
426
+ if (updater.isUsingBuiltin()) {
427
+ bridge.setServerAssetPath(path);
428
+ } else {
429
+ bridge.setServerBasePath(path);
430
+ }
431
+ } else {
432
+ logger.info("Resetting to builtin");
433
+ updater.reset();
434
+ String path = updater.getCurrentBundlePath();
435
+ bridge.setServerAssetPath(path);
436
+ }
437
+
438
+ try {
439
+ updater.delete(current.getId());
440
+ } catch (Exception err) {
441
+ logger.warn("Cannot delete version " + current.getId() + ": " + err.getMessage());
442
+ }
443
+
444
+ logger.info("Reload app done");
445
+ } catch (Exception e) {
446
+ logger.error("Error in Go Home action: " + e.getMessage());
447
+ } finally {
448
+ dialog.dismiss();
449
+ isShowing = false;
450
+ }
451
+ }
452
+ }
453
+ );
454
+
455
+ // Reload button
456
+ builder.setNeutralButton(
457
+ reloadButtonTitle,
458
+ new DialogInterface.OnClickListener() {
459
+ public void onClick(DialogInterface dialog, int id) {
460
+ try {
461
+ logger.info("Reloading webview");
462
+ String pathHot = updater.getCurrentBundlePath();
463
+ bridge.setServerBasePath(pathHot);
464
+ activity.runOnUiThread(() -> {
465
+ if (bridge.getWebView() != null) {
466
+ bridge.getWebView().reload();
467
+ }
468
+ });
469
+ } catch (Exception e) {
470
+ logger.error("Error in Reload action: " + e.getMessage());
471
+ } finally {
472
+ dialog.dismiss();
473
+ isShowing = false;
474
+ }
475
+ }
476
+ }
477
+ );
478
+
479
+ // Cancel button
480
+ builder.setNegativeButton(
481
+ cancelButtonTitle,
482
+ new DialogInterface.OnClickListener() {
483
+ public void onClick(DialogInterface dialog, int id) {
484
+ logger.info("Shake menu cancelled");
485
+ dialog.dismiss();
486
+ isShowing = false;
487
+ }
488
+ }
489
+ );
490
+
491
+ AlertDialog dialog = builder.create();
492
+ dialog.setOnDismissListener((dialogInterface) -> isShowing = false);
493
+ dialog.show();
494
+ } catch (Exception e) {
495
+ logger.error("Error showing shake menu: " + e.getMessage());
496
+ isShowing = false;
497
+ }
498
+ });
499
+ }
500
+
501
+ private void showChannelSelector() {
502
+ activity.runOnUiThread(() -> {
503
+ try {
504
+ // Show loading dialog
505
+ AlertDialog.Builder loadingBuilder = new AlertDialog.Builder(activity);
506
+ loadingBuilder.setTitle("Loading Channels...");
507
+ loadingBuilder.setCancelable(true);
508
+
509
+ ProgressBar progressBar = new ProgressBar(activity);
510
+ progressBar.setIndeterminate(true);
511
+ int padding = dpToPx(20);
512
+ progressBar.setPadding(padding, padding, padding, padding);
513
+ loadingBuilder.setView(progressBar);
514
+
515
+ final boolean[] didCancel = { false };
516
+
517
+ loadingBuilder.setNegativeButton("Cancel", (dialog, which) -> {
518
+ didCancel[0] = true;
519
+ dialog.dismiss();
520
+ isShowing = false;
521
+ });
522
+
523
+ AlertDialog loadingDialog = loadingBuilder.create();
524
+ loadingDialog.setOnCancelListener((d) -> {
525
+ didCancel[0] = true;
526
+ isShowing = false;
527
+ });
528
+ loadingDialog.setOnDismissListener((d) -> {
529
+ if (didCancel[0]) {
530
+ isShowing = false;
531
+ }
532
+ });
533
+ loadingDialog.show();
534
+
535
+ // Fetch channels in background
536
+ new Thread(() -> {
537
+ final CapgoUpdater updater = plugin.implementation;
538
+ updater.listChannels((res) -> {
539
+ activity.runOnUiThread(() -> {
540
+ loadingDialog.dismiss();
541
+
542
+ if (didCancel[0]) {
543
+ return;
544
+ }
545
+
546
+ if (res == null) {
547
+ showError("Failed to load channels: unknown error");
548
+ return;
549
+ }
550
+
551
+ Object errorObj = res.get("error");
552
+ if (errorObj != null) {
553
+ Object messageObj = res.get("message");
554
+ String message = messageObj != null ? messageObj.toString() : errorObj.toString();
555
+ showError("Failed to load channels: " + message);
556
+ return;
557
+ }
558
+
559
+ Object channelsObj = res.get("channels");
560
+ if (!(channelsObj instanceof List)) {
561
+ showError("No channels available for self-assignment");
562
+ return;
563
+ }
564
+
565
+ List<?> channelsRaw = (List<?>) channelsObj;
566
+ List<Map<String, Object>> channels = toChannelList(channelsRaw);
567
+
568
+ if (channels.isEmpty()) {
569
+ showError("No channels available for self-assignment");
570
+ return;
571
+ }
572
+
573
+ presentChannelPicker(channels);
574
+ });
575
+ });
576
+ }).start();
577
+ } catch (Exception e) {
578
+ logger.error("Error showing channel selector: " + e.getMessage());
579
+ isShowing = false;
580
+ }
581
+ });
582
+ }
583
+
584
+ private List<Map<String, Object>> toChannelList(List<?> channelsRaw) {
585
+ List<Map<String, Object>> channels = new ArrayList<>();
586
+ for (Object item : channelsRaw) {
587
+ if (!(item instanceof Map<?, ?> rawMap)) {
588
+ continue;
589
+ }
590
+
591
+ Map<String, Object> channel = new java.util.HashMap<>();
592
+ for (Map.Entry<?, ?> entry : rawMap.entrySet()) {
593
+ if (entry.getKey() instanceof String key) {
594
+ channel.put(key, entry.getValue());
595
+ }
596
+ }
597
+
598
+ if (!channel.isEmpty()) {
599
+ channels.add(channel);
600
+ }
601
+ }
602
+ return channels;
603
+ }
604
+
605
+ private void presentChannelPicker(List<Map<String, Object>> channels) {
606
+ try {
607
+ AlertDialog.Builder builder = new AlertDialog.Builder(activity);
608
+ builder.setTitle("Select Channel");
609
+
610
+ // Create custom layout with search and channel list
611
+ LinearLayout layout = new LinearLayout(activity);
612
+ layout.setOrientation(LinearLayout.VERTICAL);
613
+ int padding = dpToPx(16);
614
+ layout.setPadding(padding, padding, padding, padding);
615
+
616
+ // Search field
617
+ EditText searchField = new EditText(activity);
618
+ searchField.setHint("Search channels...");
619
+ searchField.setSingleLine(true);
620
+ layout.addView(searchField);
621
+
622
+ // Create list of channel names
623
+ List<String> allChannelNames = new ArrayList<>();
624
+ for (Map<String, Object> channel : channels) {
625
+ Object nameObj = channel.get("name");
626
+ if (nameObj instanceof String) {
627
+ allChannelNames.add((String) nameObj);
628
+ }
629
+ }
630
+
631
+ // Displayed channels (first 5 by default)
632
+ final List<String> displayedChannels = new ArrayList<>();
633
+ displayedChannels.addAll(allChannelNames.subList(0, Math.min(5, allChannelNames.size())));
634
+
635
+ final ArrayAdapter<String> adapter = new ArrayAdapter<>(activity, android.R.layout.simple_list_item_1, displayedChannels);
636
+
637
+ ListView listView = new ListView(activity);
638
+ listView.setAdapter(adapter);
639
+
640
+ // Set fixed height for list (about 5 items)
641
+ LinearLayout.LayoutParams listParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dpToPx(250));
642
+ listView.setLayoutParams(listParams);
643
+ layout.addView(listView);
644
+
645
+ builder.setView(layout);
646
+ builder.setNegativeButton("Cancel", (dialog, which) -> {
647
+ dialog.dismiss();
648
+ isShowing = false;
649
+ });
650
+
651
+ AlertDialog dialog = builder.create();
652
+ dialog.setOnDismissListener((d) -> isShowing = false);
653
+
654
+ // Search filter
655
+ searchField.addTextChangedListener(
656
+ new TextWatcher() {
657
+ @Override
658
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
659
+
660
+ @Override
661
+ public void onTextChanged(CharSequence s, int start, int before, int count) {}
662
+
663
+ @Override
664
+ public void afterTextChanged(Editable s) {
665
+ String query = s.toString().toLowerCase();
666
+ displayedChannels.clear();
667
+
668
+ int count = 0;
669
+ for (String name : allChannelNames) {
670
+ if (name.toLowerCase().contains(query)) {
671
+ displayedChannels.add(name);
672
+ count++;
673
+ if (count >= 5) break;
674
+ }
675
+ }
676
+
677
+ adapter.notifyDataSetChanged();
678
+ }
679
+ }
680
+ );
681
+
682
+ // Channel selection
683
+ listView.setOnItemClickListener((parent, view, position, id) -> {
684
+ String selectedChannel = displayedChannels.get(position);
685
+ dialog.dismiss();
686
+ selectChannel(selectedChannel);
687
+ });
688
+
689
+ dialog.show();
690
+ } catch (Exception e) {
691
+ logger.error("Error presenting channel picker: " + e.getMessage());
692
+ isShowing = false;
693
+ }
694
+ }
695
+
696
+ private void selectChannel(String channelName) {
697
+ activity.runOnUiThread(() -> {
698
+ try {
699
+ // Show progress dialog
700
+ AlertDialog.Builder progressBuilder = new AlertDialog.Builder(activity);
701
+ progressBuilder.setTitle("Switching to " + channelName);
702
+ progressBuilder.setMessage("Setting channel...");
703
+ progressBuilder.setCancelable(false);
704
+
705
+ ProgressBar progressBar = new ProgressBar(activity);
706
+ progressBar.setIndeterminate(true);
707
+ int padding = dpToPx(20);
708
+ progressBar.setPadding(padding, padding, padding, padding);
709
+ progressBuilder.setView(progressBar);
710
+
711
+ AlertDialog progressDialog = progressBuilder.create();
712
+ progressDialog.show();
713
+
714
+ new Thread(() -> {
715
+ final CapgoUpdater updater = plugin.implementation;
716
+ final Bridge bridge = activity.getBridge();
717
+ final String configDefaultChannel = plugin.getConfig().getString("defaultChannel", "");
718
+
719
+ // Set the channel - respect plugin's allowSetDefaultChannel config
720
+ updater.setChannel(
721
+ channelName,
722
+ updater.editor,
723
+ "CapacitorUpdater.defaultChannel",
724
+ plugin.allowSetDefaultChannel,
725
+ configDefaultChannel,
726
+ (setRes) -> {
727
+ if (setRes == null) {
728
+ activity.runOnUiThread(() -> {
729
+ progressDialog.dismiss();
730
+ showError("Failed to set channel: unknown error");
731
+ });
732
+ return;
733
+ }
734
+
735
+ Object errorObj = setRes.get("error");
736
+ if (errorObj != null) {
737
+ Object messageObj = setRes.get("message");
738
+ String message = messageObj != null ? messageObj.toString() : errorObj.toString();
739
+ activity.runOnUiThread(() -> {
740
+ progressDialog.dismiss();
741
+ showError("Failed to set channel: " + message);
742
+ });
743
+ return;
744
+ }
745
+
746
+ // Update progress message
747
+ activity.runOnUiThread(() -> progressDialog.setMessage("Checking for updates..."));
748
+
749
+ // Check for updates
750
+ String updateUrlStr = plugin.getUpdateUrl();
751
+ if (updateUrlStr == null || updateUrlStr.isEmpty()) {
752
+ updateUrlStr = "https://plugin.capgo.app/updates";
753
+ }
754
+
755
+ final String finalUpdateUrlStr = updateUrlStr;
756
+ updater.getLatest(finalUpdateUrlStr, channelName, (latestRes) -> {
757
+ if (latestRes == null) {
758
+ activity.runOnUiThread(() -> {
759
+ progressDialog.dismiss();
760
+ showSuccess("Channel set to " + channelName + ". Could not check for updates.");
761
+ });
762
+ return;
763
+ }
764
+
765
+ String latestError = getString(latestRes, "error");
766
+ String latestKind = getString(latestRes, "kind");
767
+ String latestMessage = getString(latestRes, "message");
768
+
769
+ String detail =
770
+ latestMessage != null && !latestMessage.isEmpty()
771
+ ? latestMessage
772
+ : latestError != null && !latestError.isEmpty()
773
+ ? latestError
774
+ : latestKind != null && !latestKind.isEmpty()
775
+ ? latestKind
776
+ : "server did not provide a message";
777
+
778
+ // Handle update errors first (before "no new version" check)
779
+ if (
780
+ "failed".equals(latestKind) ||
781
+ (latestError != null &&
782
+ !latestError.isEmpty() &&
783
+ !"up_to_date".equals(latestKind) &&
784
+ !"blocked".equals(latestKind))
785
+ ) {
786
+ activity.runOnUiThread(() -> {
787
+ progressDialog.dismiss();
788
+ showError("Channel set to " + channelName + ". Update check failed: " + detail);
789
+ });
790
+ return;
791
+ }
792
+
793
+ if ("blocked".equals(latestKind)) {
794
+ activity.runOnUiThread(() -> {
795
+ progressDialog.dismiss();
796
+ showError("Channel set to " + channelName + ". Update check blocked: " + detail);
797
+ });
798
+ return;
799
+ }
800
+
801
+ String latestUrl = getString(latestRes, "url");
802
+
803
+ Object manifestObj = latestRes.get("manifest");
804
+ JSONArray manifestArray = null;
805
+ if (manifestObj instanceof JSONArray) {
806
+ manifestArray = (JSONArray) manifestObj;
807
+ } else if (manifestObj instanceof List) {
808
+ manifestArray = new JSONArray((List<?>) manifestObj);
809
+ }
810
+ final boolean hasManifest = manifestArray != null && manifestArray.length() > 0;
811
+
812
+ // Check if there's an actual update available. A manifest-only
813
+ // response legitimately has no URL (the files come from the
814
+ // manifest, not a zip), so only report "already on latest" when
815
+ // the URL is empty AND there is no manifest to download from.
816
+ if ("up_to_date".equals(latestKind) || ((latestUrl == null || latestUrl.isEmpty()) && !hasManifest)) {
817
+ activity.runOnUiThread(() -> {
818
+ progressDialog.dismiss();
819
+ showSuccess("Channel set to " + channelName + ". Already on latest version.");
820
+ });
821
+ return;
822
+ }
823
+
824
+ String version = getString(latestRes, "version");
825
+ if (version == null || version.isEmpty()) {
826
+ activity.runOnUiThread(() -> {
827
+ progressDialog.dismiss();
828
+ showError("Channel set to " + channelName + ". Update check failed: missing version.");
829
+ });
830
+ return;
831
+ }
832
+
833
+ // Update message
834
+ final String versionForUi = version;
835
+ activity.runOnUiThread(() -> progressDialog.setMessage("Downloading update " + versionForUi + "..."));
836
+
837
+ String sessionKey = getString(latestRes, "sessionKey");
838
+ String checksum = getString(latestRes, "checksum");
839
+
840
+ // A manifest-only response has no zip URL; downloadManifest
841
+ // tolerates the placeholder URL the plugin already uses.
842
+ final String downloadUrl =
843
+ latestUrl == null || latestUrl.isEmpty() ? "https://404.capgo.app/no.zip" : latestUrl;
844
+
845
+ // Download the update
846
+ try {
847
+ BundleInfo bundle;
848
+ if (hasManifest) {
849
+ bundle = updater.downloadManifest(
850
+ downloadUrl,
851
+ versionForUi,
852
+ sessionKey != null ? sessionKey : "",
853
+ checksum != null ? checksum : "",
854
+ manifestArray
855
+ );
856
+ } else {
857
+ bundle = updater.download(
858
+ downloadUrl,
859
+ versionForUi,
860
+ sessionKey != null ? sessionKey : "",
861
+ checksum != null ? checksum : ""
862
+ );
863
+ }
864
+
865
+ // Set as next bundle
866
+ updater.setNextBundle(bundle.getId());
867
+
868
+ activity.runOnUiThread(() -> {
869
+ progressDialog.dismiss();
870
+ showSuccessWithReload("Update downloaded! Reload to apply version " + versionForUi + "?", () -> {
871
+ try {
872
+ if (bridge == null) {
873
+ logger.warn("Bridge is null, cannot reload app");
874
+ return;
875
+ }
876
+ updater.set(bundle);
877
+ String path = updater.getCurrentBundlePath();
878
+ if (updater.isUsingBuiltin()) {
879
+ bridge.setServerAssetPath(path);
880
+ } else {
881
+ bridge.setServerBasePath(path);
882
+ }
883
+ if (bridge.getWebView() != null) {
884
+ bridge.getWebView().reload();
885
+ }
886
+ } catch (Exception e) {
887
+ logger.error("Error applying bundle before reload: " + e.getMessage());
888
+ }
889
+ });
890
+ });
891
+ } catch (Exception e) {
892
+ activity.runOnUiThread(() -> {
893
+ progressDialog.dismiss();
894
+ showError("Failed to download update: " + e.getMessage());
895
+ });
896
+ }
897
+ });
898
+ }
899
+ );
900
+ }).start();
901
+ } catch (Exception e) {
902
+ logger.error("Error selecting channel: " + e.getMessage());
903
+ isShowing = false;
904
+ }
905
+ });
906
+ }
907
+
908
+ private void showError(String message) {
909
+ logger.error(message);
910
+ new AlertDialog.Builder(activity)
911
+ .setTitle("Error")
912
+ .setMessage(message)
913
+ .setPositiveButton("OK", (d, w) -> {
914
+ d.dismiss();
915
+ isShowing = false;
916
+ })
917
+ .setOnDismissListener((d) -> isShowing = false)
918
+ .show();
919
+ }
920
+
921
+ private void showSuccess(String message) {
922
+ logger.info(message);
923
+ new AlertDialog.Builder(activity)
924
+ .setTitle("Success")
925
+ .setMessage(message)
926
+ .setPositiveButton("OK", (d, w) -> {
927
+ d.dismiss();
928
+ isShowing = false;
929
+ })
930
+ .setOnDismissListener((d) -> isShowing = false)
931
+ .show();
932
+ }
933
+
934
+ private void showSuccessWithReload(String message, Runnable onReload) {
935
+ logger.info(message);
936
+ new AlertDialog.Builder(activity)
937
+ .setTitle("Update Ready")
938
+ .setMessage(message)
939
+ .setPositiveButton("Reload Now", (d, w) -> {
940
+ d.dismiss();
941
+ isShowing = false;
942
+ if (onReload != null) {
943
+ onReload.run();
944
+ }
945
+ })
946
+ .setNegativeButton("Later", (d, w) -> {
947
+ d.dismiss();
948
+ isShowing = false;
949
+ })
950
+ .setOnDismissListener((d) -> isShowing = false)
951
+ .show();
952
+ }
953
+
954
+ private String getString(Map<String, Object> map, String key) {
955
+ Object value = map.get(key);
956
+ return value != null ? value.toString() : null;
957
+ }
958
+
959
+ private int dpToPx(int dp) {
960
+ float density = activity.getResources().getDisplayMetrics().density;
961
+ return Math.round(dp * density);
962
+ }
963
+ }