@capgo/capacitor-updater 8.52.1-beta.pr937.1951.1 → 8.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 (65) hide show
  1. package/CapgoCapacitorUpdater.podspec +0 -2
  2. package/Package.swift +0 -5
  3. package/README.md +199 -67
  4. package/android/build.gradle +9 -88
  5. package/android/src/main/java/ee/forgr/capacitor_updater/AndroidAppExitReporter.java +60 -32
  6. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +246 -0
  7. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +45 -0
  8. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  9. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +5539 -1066
  10. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +3754 -494
  11. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +496 -0
  12. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +44 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +56 -0
  14. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +14 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +427 -0
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +6 -23
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +1541 -0
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +258 -0
  19. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +318 -0
  20. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +45 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +1 -6
  22. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +417 -217
  24. package/android/src/main/java/ee/forgr/capacitor_updater/ThreeFingerPinchDetector.java +1 -3
  25. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  26. package/dist/docs.json +379 -28
  27. package/dist/esm/definitions.d.ts +209 -10
  28. package/dist/esm/definitions.js.map +1 -1
  29. package/dist/plugin.cjs.js.map +1 -1
  30. package/dist/plugin.js.map +1 -1
  31. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +262 -0
  32. package/ios/Sources/CapacitorUpdaterPlugin/AppHealthTracker.swift +82 -0
  33. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +185 -0
  34. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +127 -0
  35. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +5247 -199
  36. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  37. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +3878 -365
  38. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +328 -0
  39. package/ios/Sources/CapacitorUpdaterPlugin/DelayCondition.swift +74 -0
  40. package/ios/Sources/CapacitorUpdaterPlugin/DelayUntilNext.swift +30 -0
  41. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +343 -0
  42. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +471 -0
  43. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  44. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +96 -0
  45. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +53 -0
  46. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +221 -63
  47. package/ios/Sources/CapacitorUpdaterPlugin/UserDefaultsExtension.swift +46 -0
  48. package/ios/Sources/CapacitorUpdaterPlugin/WebViewStatsReporter.swift +147 -5
  49. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  50. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  51. package/package.json +15 -19
  52. package/android/consumer-rules.pro +0 -15
  53. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoCore.java +0 -67
  54. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoCoreNative.java +0 -97
  55. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoDownloadWorker.java +0 -188
  56. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoEngine.java +0 -114
  57. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoEngineHolder.java +0 -59
  58. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoEngineHost.java +0 -118
  59. package/android/src/main/java/ee/forgr/capacitor_updater/EngineMethodLanes.java +0 -168
  60. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+AppStore.swift +0 -171
  61. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+Methods.swift +0 -168
  62. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+Overlays.swift +0 -285
  63. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin+WebView.swift +0 -134
  64. package/ios/Sources/CapacitorUpdaterPlugin/CapgoCore.swift +0 -61
  65. package/ios/Sources/CapacitorUpdaterPlugin/CapgoEngine.swift +0 -319
@@ -6,11 +6,16 @@
6
6
 
7
7
  package ee.forgr.capacitor_updater;
8
8
 
9
+ import android.app.Activity;
9
10
  import android.content.Context;
10
11
  import android.content.SharedPreferences;
11
- import android.content.pm.ApplicationInfo;
12
12
  import android.content.pm.PackageManager;
13
13
  import android.os.Build;
14
+ import android.os.Handler;
15
+ import android.os.Looper;
16
+ import androidx.annotation.NonNull;
17
+ import androidx.lifecycle.LiveData;
18
+ import androidx.lifecycle.Observer;
14
19
  import androidx.work.Constraints;
15
20
  import androidx.work.Data;
16
21
  import androidx.work.ExistingPeriodicWorkPolicy;
@@ -19,393 +24,193 @@ import androidx.work.ListenableWorker;
19
24
  import androidx.work.NetworkType;
20
25
  import androidx.work.OneTimeWorkRequest;
21
26
  import androidx.work.PeriodicWorkRequest;
27
+ import androidx.work.WorkInfo;
22
28
  import androidx.work.WorkManager;
23
- import com.getcapacitor.plugin.WebView;
29
+ import java.io.BufferedInputStream;
24
30
  import java.io.BufferedReader;
25
- import java.io.ByteArrayOutputStream;
26
31
  import java.io.File;
27
32
  import java.io.FileInputStream;
33
+ import java.io.FileNotFoundException;
28
34
  import java.io.FileOutputStream;
35
+ import java.io.FilenameFilter;
29
36
  import java.io.IOException;
30
37
  import java.io.InputStreamReader;
31
- import java.net.InetSocketAddress;
32
- import java.net.Proxy;
33
- import java.net.ProxySelector;
34
- import java.net.URI;
35
38
  import java.nio.charset.StandardCharsets;
36
- import java.util.Arrays;
39
+ import java.nio.file.Files;
40
+ import java.security.SecureRandom;
41
+ import java.util.ArrayList;
42
+ import java.util.Date;
43
+ import java.util.HashMap;
37
44
  import java.util.HashSet;
45
+ import java.util.Iterator;
46
+ import java.util.LinkedHashSet;
38
47
  import java.util.List;
39
48
  import java.util.Map;
49
+ import java.util.Objects;
40
50
  import java.util.Set;
51
+ import java.util.concurrent.CompletableFuture;
52
+ import java.util.concurrent.ConcurrentHashMap;
53
+ import java.util.concurrent.CopyOnWriteArrayList;
54
+ import java.util.concurrent.ExecutorService;
55
+ import java.util.concurrent.Executors;
56
+ import java.util.concurrent.LinkedBlockingQueue;
57
+ import java.util.concurrent.ScheduledExecutorService;
58
+ import java.util.concurrent.ScheduledFuture;
59
+ import java.util.concurrent.ThreadPoolExecutor;
41
60
  import java.util.concurrent.TimeUnit;
61
+ import java.util.concurrent.atomic.AtomicBoolean;
62
+ import java.util.zip.ZipEntry;
63
+ import java.util.zip.ZipInputStream;
64
+ import okhttp3.*;
65
+ import okhttp3.HttpUrl;
42
66
  import org.json.JSONArray;
43
67
  import org.json.JSONException;
44
68
  import org.json.JSONObject;
45
69
 
46
- /**
47
- * Creates the Rust updater engine ({@code core/src/engine}) and answers its host callbacks: persistence
48
- * (SharedPreferences), logs, events, plugin hooks and the Android-only Background Runner rescheduling.
49
- */
50
70
  public class CapgoUpdater {
51
71
 
52
- /** Receives engine events and hooks. Both can arrive on any thread. */
53
- interface Listener {
54
- void onEvent(String event, String payloadJson);
72
+ private final Logger logger;
73
+
74
+ private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
75
+ private static final SecureRandom rnd = new SecureRandom();
55
76
 
56
- /** Returns the JSON reply of a hook, or {@code null} when it is not handled. */
57
- String onHook(String name, String payloadJson);
58
- }
77
+ private static final String INFO_SUFFIX = "_info";
59
78
 
60
- static final String BUNDLE_DIRECTORY = "versions";
61
- /** Engine configuration persisted at plugin load for downloads WorkManager runs without the plugin. */
62
- static final String ENGINE_CONFIG_FILE = "CapacitorUpdater.engineConfig.json";
79
+ private static final String FALLBACK_VERSION = "pastVersion";
80
+ private static final String NEXT_VERSION = "nextVersion";
81
+ private static final String PREVIEW_FALLBACK_VERSION = "previewFallbackVersion";
82
+ private static final String PENDING_DELETE_IDS = "pendingDeleteIds";
83
+ private static final String bundleDirectory = "versions";
84
+ private static final String TEMP_UNZIP_PREFIX = "capgo_unzip_";
85
+ static final String MANIFEST_STAGING_PREFIX = "capgo_manifest_";
86
+ static final String MANIFEST_DEST_SUFFIX = "_manifest_dest";
87
+ private static final String LEGACY_MANIFEST_STAGING_FOLDER_PATTERN = "^[0-9A-Za-z]{10}$";
88
+ private static final long DELETE_PACE_MS = 75L;
89
+ private final Object deleteLock = new Object();
63
90
  private static final String CAPACITOR_CONFIG_ASSET = "capacitor.config.json";
64
91
  private static final String BACKGROUND_RUNNER_CONFIG_KEY = "BackgroundRunner";
65
92
  private static final String BACKGROUND_RUNNER_WORKER_CLASS = "io.ionic.backgroundrunner.plugin.RunnerWorker";
66
93
 
67
- private final Context context;
68
- private final SharedPreferences prefs;
69
- private final Logger logger;
70
- private final Listener listener;
71
-
72
- CapgoUpdater(final Context context, final SharedPreferences prefs, final Logger logger, final Listener listener) {
73
- this.context = context;
74
- this.prefs = prefs;
75
- this.logger = logger;
76
- this.listener = listener;
77
- }
78
-
79
- /**
80
- * Creates the engine. {@code identity} carries appId, pluginVersion, versionBuild, versionCode, versionOs and
81
- * deviceId; storage paths and device facts are added here.
82
- */
83
- CapgoEngine createEngine(final JSONObject identity, final String serverPathKey) {
84
- this.cancelLegacyDownloadWork();
85
- final JSONObject config;
86
- try {
87
- config = new JSONObject(identity.toString());
88
- final File filesDir = this.context.getFilesDir();
89
- config.put("platform", "android");
90
- config.put("isEmulator", isEmulator());
91
- config.put("isProd", this.isProd());
92
- config.put("installSource", this.getInstallSource());
93
- config.put("bundleRoot", new File(filesDir, BUNDLE_DIRECTORY).getAbsolutePath());
94
- config.put("storageRoot", filesDir.getAbsolutePath());
95
- config.put("statsDir", this.context.getNoBackupFilesDir().getAbsolutePath());
96
- config.put("cacheDir", new File(this.context.getCacheDir(), "capgo_downloads").getAbsolutePath());
97
- config.put("builtinServerPath", "public");
98
- config.put("builtinDir", new File(filesDir, "public").getAbsolutePath());
99
- final ApplicationInfo applicationInfo = this.context.getApplicationInfo();
100
- config.put("builtinApk", applicationInfo == null || applicationInfo.sourceDir == null ? "" : applicationInfo.sourceDir);
101
- config.put(
102
- "keys",
103
- new JSONObject().put("serverPath", serverPathKey == null || serverPathKey.isEmpty() ? "serverBasePath" : serverPathKey)
104
- );
105
- } catch (JSONException e) {
106
- throw new IllegalStateException("Invalid engine config", e);
107
- }
108
- this.persistEngineConfig(config);
109
- return new CapgoEngine(config, this.host);
110
- }
111
-
112
- /** Saved for {@link #createWorkerEngine}: identity and storage paths only (no secret). */
113
- private void persistEngineConfig(final JSONObject config) {
114
- try {
115
- final JSONObject saved = new JSONObject().put("engine", config).put("osLogging", this.logger.usesSystemLog());
116
- final File file = new File(this.context.getNoBackupFilesDir(), ENGINE_CONFIG_FILE);
117
- final File temp = new File(file.getParentFile(), ENGINE_CONFIG_FILE + ".tmp");
118
- try (FileOutputStream output = new FileOutputStream(temp)) {
119
- output.write(saved.toString().getBytes(StandardCharsets.UTF_8));
120
- output.getFD().sync();
121
- }
122
- if (!temp.renameTo(file)) {
123
- temp.delete();
124
- throw new IOException("rename failed");
125
- }
126
- } catch (IOException | JSONException e) {
127
- logger.warn("Cannot persist the engine configuration for background downloads: " + e.getMessage());
128
- }
129
- }
130
-
131
- /**
132
- * Engine for a download WorkManager runs in a process without the plugin (the app was killed mid-download). It uses
133
- * the configuration and preferences the plugin last loaded with; events have no listener. {@code null} when the
134
- * plugin never ran.
135
- */
136
- static CapgoEngine createWorkerEngine(final Context context) {
137
- final File file = new File(context.getNoBackupFilesDir(), ENGINE_CONFIG_FILE);
138
- final JSONObject saved;
139
- try (FileInputStream input = new FileInputStream(file)) {
140
- final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
141
- final byte[] buffer = new byte[8192];
142
- int read;
143
- while ((read = input.read(buffer)) != -1) {
144
- bytes.write(buffer, 0, read);
145
- }
146
- saved = new JSONObject(new String(bytes.toByteArray(), StandardCharsets.UTF_8));
147
- } catch (IOException | JSONException e) {
148
- return null;
149
- }
150
- final JSONObject config = saved.optJSONObject("engine");
151
- if (config == null) {
152
- return null;
153
- }
154
- final Logger logger = new Logger("CapgoUpdater", new Logger.Options(saved.optBoolean("osLogging", true)));
155
- final SharedPreferences prefs = context.getSharedPreferences(WebView.WEBVIEW_PREFS_NAME, Context.MODE_PRIVATE);
156
- final CapgoUpdater updater = new CapgoUpdater(
157
- context,
158
- prefs,
159
- logger,
160
- new Listener() {
161
- @Override
162
- public void onEvent(final String event, final String payloadJson) {}
94
+ public static final String TAG = "Capacitor-updater";
95
+ public SharedPreferences.Editor editor;
163
96
 
164
- @Override
165
- public String onHook(final String name, final String payloadJson) {
166
- return null;
167
- }
168
- }
169
- );
170
- try {
171
- return new CapgoEngine(config, updater.host);
172
- } catch (IllegalStateException | LinkageError e) {
173
- // Native core missing or broken: the job fails instead of crashing the WorkManager process.
174
- logger.error("Cannot create the engine for a background download: " + e.getMessage());
175
- return null;
176
- }
177
- }
97
+ /** Optional gate run before any download touches disk (e.g. wait for launch cleanup). */
98
+ public Runnable downloadGate = null;
99
+ public SharedPreferences prefs;
178
100
 
179
- /** {@code scheduleDownload}: the engine's download becomes a WorkManager job. {@code null} keeps it in-process. */
180
- private String scheduleDownload(final String payloadJson) {
181
- try {
182
- final JSONObject payload = new JSONObject(payloadJson);
183
- final String id = payload.optString("id", "");
184
- if (id.isEmpty()) {
185
- return null;
186
- }
187
- CapgoDownloadWorker.enqueue(this.context, id, payload.optString("version", ""), isEmulator());
188
- return new JSONObject().put("scheduled", true).toString();
189
- } catch (JSONException | RuntimeException e) {
190
- // WorkManager unavailable (not initialized, disabled): download in-process.
191
- logger.warn("Cannot schedule the download, running it in-process: " + e.getMessage());
192
- return null;
193
- }
194
- }
101
+ public File documentsDir;
102
+ public File noBackupDir;
103
+ public Boolean directUpdate = false;
104
+ public Activity activity;
105
+ // Application context: lets downloads run and finish without an Activity (app in the
106
+ // background, or a process woken by a push with no UI at all).
107
+ public Context appContext;
108
+ public String pluginVersion = "";
109
+ public String versionBuild = "";
110
+ public String versionCode = "";
111
+ public String versionOs = "";
112
+ public String CAP_SERVER_PATH = "";
195
113
 
196
- final CapgoEngineHost host = new CapgoEngineHost() {
197
- @Override
198
- void log(final int level, final String message) {
199
- switch (level) {
200
- case 0:
201
- logger.debug(message);
202
- break;
203
- case 1:
204
- logger.info(message);
205
- break;
206
- case 2:
207
- logger.warn(message);
208
- break;
209
- default:
210
- logger.error(message);
211
- break;
212
- }
213
- }
114
+ public String customId = "";
115
+ public String statsUrl = "";
116
+ public String channelUrl = "";
117
+ public String defaultChannel = "";
118
+ public String appId = "";
119
+ public volatile boolean previewSession = false;
120
+ public String publicKey = "";
121
+ public String deviceID = "";
122
+ public int timeout = 20000;
214
123
 
215
- @Override
216
- String kvGet(final String key, final String defaultValue) {
217
- return readPreference(prefs, key, defaultValue);
218
- }
124
+ // Cached key ID calculated once from publicKey
125
+ private String cachedKeyId = "";
219
126
 
220
- @Override
221
- boolean kvContains(final String key) {
222
- return prefs.contains(key);
223
- }
127
+ // Temporary 429 block until this epoch ms (Retry-After / rateLimitResetAt). No sticky latch.
128
+ // Guarded by rateLimitStateLock so concurrent 429s cannot shorten the window or mix metadata.
129
+ private static final Object rateLimitStateLock = new Object();
130
+ private static long rateLimitBlockedUntilMs = 0L;
131
+ private static String rateLimitBlockedError = "too_many_requests";
132
+ private static String rateLimitBlockedMessage = "Too many requests";
224
133
 
225
- @Override
226
- void kvSet(final String key, final String value) {
227
- final SharedPreferences.Editor editor = prefs.edit();
228
- if (value == null) {
229
- editor.remove(key);
230
- } else {
231
- putPreference(editor, key, value);
232
- }
233
- editor.commit();
234
- }
134
+ // Flag to track if we've already sent the rate limit statistic - prevents infinite loop.
135
+ // Released again when the send fails, so a later 429 can retry it.
136
+ private static boolean rateLimitStatisticSent = false;
235
137
 
236
- @Override
237
- String kvKeysJson() {
238
- final Map<String, ?> all = prefs.getAll();
239
- return all == null ? "[]" : new JSONArray(all.keySet()).toString();
240
- }
138
+ // Upper bound for a client-side 429 block, so a bogus Retry-After cannot block the app for days.
139
+ private static final long MAX_RATE_LIMIT_WINDOW_MS = 24 * 60 * 60 * 1000L;
241
140
 
242
- @Override
243
- void emit(final String event, final String payloadJson) {
244
- listener.onEvent(event, payloadJson);
245
- }
141
+ // Stats batching - queue events and send max once per second
142
+ private final List<QueuedStatsEvent> statsQueue = new CopyOnWriteArrayList<>();
143
+ private final List<QueuedStatsEvent> statsInFlight = new ArrayList<>();
144
+ private final Object pendingStatsPersistLock = new Object();
145
+ private final ScheduledExecutorService statsScheduler = Executors.newSingleThreadScheduledExecutor();
146
+ private ScheduledFuture<?> statsFlushTask = null;
147
+ private final AtomicBoolean statsFlushInFlight = new AtomicBoolean(false);
148
+ private final AtomicBoolean statsStopped = new AtomicBoolean(false);
149
+ private static final long STATS_FLUSH_INTERVAL_MS = 1000;
150
+ private static final String PENDING_STATS_FILE = "capgo_pending_stats.json";
151
+ private static final int MAX_PENDING_STATS = 200;
246
152
 
247
- @Override
248
- String hook(final String name, final String payloadJson) {
249
- try {
250
- if ("cleartextPermitted".equals(name)) {
251
- return cleartextPermittedReply(payloadJson);
252
- }
253
- if ("scheduleDownload".equals(name)) {
254
- return scheduleDownload(payloadJson);
255
- }
256
- if ("proxyForUrl".equals(name)) {
257
- return proxyForUrlReply(payloadJson, ProxySelector.getDefault());
258
- }
259
- if ("releaseMethodLane".equals(name)) {
260
- EngineMethodLanes.releaseCurrentThread();
261
- return null;
262
- }
263
- return listener.onHook(name, payloadJson);
264
- } catch (RuntimeException e) {
265
- logger.error("Hook " + name + " failed: " + e.getMessage());
266
- return null;
267
- }
268
- }
153
+ private static final class QueuedStatsEvent {
269
154
 
270
- @Override
271
- void willSwitchBundle(final String path) {
272
- resetBackgroundRunnerWorkForBundleSwitch(new File(path));
273
- }
155
+ private final JSONObject event;
156
+ private final Runnable onSent;
274
157
 
275
- @Override
276
- boolean cancelVersionDownload(final String version) {
277
- return CapgoDownloadWorker.cancelVersion(context, version, logger);
158
+ private QueuedStatsEvent(final JSONObject event, final Runnable onSent) {
159
+ this.event = event;
160
+ this.onSent = onSent;
278
161
  }
162
+ }
279
163
 
280
- @Override
281
- void cancelAllDownloads() {
282
- CapgoDownloadWorker.cancelAll(context);
283
- }
284
- };
164
+ private final Map<String, CompletableFuture<BundleInfo>> downloadFutures = new ConcurrentHashMap<>();
285
165
 
286
- /**
287
- * Plugin versions before the Rust engine queued downloads as WorkManager jobs whose worker class no
288
- * longer exists: cancel any left from before the upgrade (the update check downloads again).
289
- */
290
- private void cancelLegacyDownloadWork() {
291
- // Off the main thread: the plugin loads during Activity.onCreate and WorkManager.getInstance can initialize
292
- // WorkManager there. The legacy tag is not the engine's, so nothing depends on the order.
293
- final Runnable cancel = () -> {
294
- try {
295
- WorkManager.getInstance(this.context.getApplicationContext()).cancelAllWorkByTag("capacitor_updater_download");
296
- } catch (final Exception e) {
297
- logger.debug("No legacy download work to cancel: " + e.getMessage());
298
- }
299
- };
300
- try {
301
- final Thread thread = new Thread(cancel, "capgo-legacy-work-cancel");
302
- thread.setDaemon(true);
303
- thread.start();
304
- } catch (final Throwable e) {
305
- logger.debug("Cannot cancel legacy download work: " + e.getMessage());
306
- }
307
- }
166
+ /** A download failure whose downloadFailed event and stats were already sent by the updater. */
167
+ static final class ReportedDownloadFailureException extends IOException {
308
168
 
309
- /** The engine's HTTP client asks before plain HTTP: the app's network security config decides. */
310
- static String cleartextPermittedReply(final String payloadJson) {
311
- try {
312
- final String host = new JSONObject(payloadJson).optString("host", "");
313
- final android.security.NetworkSecurityPolicy policy = android.security.NetworkSecurityPolicy.getInstance();
314
- boolean permitted;
315
- try {
316
- permitted = policy.isCleartextTrafficPermitted(host);
317
- } catch (final LinkageError e) {
318
- // Platforms without the per-host check (JVM unit tests): the app-wide policy decides.
319
- permitted = policy.isCleartextTrafficPermitted();
320
- }
321
- return new JSONObject().put("permitted", permitted).toString();
322
- } catch (JSONException e) {
323
- return null;
169
+ ReportedDownloadFailureException(final String message) {
170
+ super(message);
324
171
  }
325
172
  }
326
173
 
327
- /**
328
- * System proxy for an engine request, like OkHttp used: the first HTTP proxy {@link ProxySelector} returns
329
- * (Wi-Fi / MDM proxy settings), else direct. SOCKS proxies are not supported and connect directly.
330
- */
331
- static String proxyForUrlReply(final String payloadJson, final ProxySelector selector) {
332
- try {
333
- final String url = new JSONObject(payloadJson).optString("url", "");
334
- final List<Proxy> proxies = selector == null ? null : selector.select(new URI(url));
335
- return proxyReply(proxies).toString();
336
- } catch (JSONException | RuntimeException | java.net.URISyntaxException e) {
337
- return "{\"type\":\"direct\"}";
338
- }
339
- }
174
+ // Versions whose WorkManager download is observed by this process. WorkManager persists work across a
175
+ // process kill, but the observer that finishes the download does not survive it.
176
+ private final Set<String> observedDownloadVersions = ConcurrentHashMap.newKeySet();
177
+ private final ExecutorService io = createIoExecutor();
340
178
 
341
- /** {@code {"type":"http","host":...,"port":...}} for the first usable HTTP proxy, else {@code {"type":"direct"}}. */
342
- static JSONObject proxyReply(final List<Proxy> proxies) throws JSONException {
343
- if (proxies != null) {
344
- for (final Proxy proxy : proxies) {
345
- if (proxy == null || proxy.type() == Proxy.Type.DIRECT) {
346
- break;
347
- }
348
- if (proxy.type() == Proxy.Type.HTTP && proxy.address() instanceof InetSocketAddress) {
349
- final InetSocketAddress address = (InetSocketAddress) proxy.address();
350
- return new JSONObject().put("type", "http").put("host", address.getHostString()).put("port", address.getPort());
351
- }
352
- }
353
- }
354
- return new JSONObject().put("type", "direct");
179
+ private static ExecutorService createIoExecutor() {
180
+ final ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
181
+ executor.allowCoreThreadTimeOut(true);
182
+ return executor;
355
183
  }
356
184
 
357
- /** Keys earlier plugin versions read with getBoolean / getLong: keep the type so a downgrade still reads them. */
358
- private static final Set<String> BOOLEAN_PREFERENCES = new HashSet<>(
359
- Arrays.asList(
360
- "CapacitorUpdater.previewSession",
361
- "CapacitorUpdater.previewSessionAlertPending",
362
- "CapacitorUpdater.defaultChannelInstallMarkerCreated",
363
- "CapacitorUpdater.previewPreviousShakeMenu",
364
- "CapacitorUpdater.previewPreviousShakeChannelSelector",
365
- "CapacitorUpdater.previewPreviousDefaultChannelWasSet"
366
- )
367
- );
368
- private static final Set<String> LONG_PREFERENCES = new HashSet<>(
369
- Arrays.asList("BACKGROUND_TIMESTAMP_KEY_CAPGO", "CapacitorUpdater.lastReportedAppExitTimestamp")
370
- );
185
+ private volatile Handler mainHandler;
371
186
 
372
- static void putPreference(final SharedPreferences.Editor editor, final String key, final String value) {
373
- if (BOOLEAN_PREFERENCES.contains(key) && ("true".equals(value) || "false".equals(value))) {
374
- editor.putBoolean(key, Boolean.parseBoolean(value));
375
- return;
376
- }
377
- if (LONG_PREFERENCES.contains(key)) {
378
- try {
379
- editor.putLong(key, Long.parseLong(value));
380
- return;
381
- } catch (NumberFormatException ignored) {
382
- // Not a number: stored as a string.
383
- }
384
- }
385
- editor.putString(key, value);
187
+ public CapgoUpdater(Logger logger) {
188
+ this.logger = logger;
386
189
  }
387
190
 
388
- /**
389
- * Stored value as a string. Earlier plugin versions stored some keys as booleans or longs
390
- * (preview flags, last reported exit timestamp): those are returned in their string form.
391
- */
392
- static String readPreference(final SharedPreferences prefs, final String key, final String defaultValue) {
393
- try {
394
- return prefs.getString(key, defaultValue);
395
- } catch (ClassCastException e) {
396
- final Map<String, ?> all = prefs.getAll();
397
- final Object value = all == null ? null : all.get(key);
398
- return value == null ? defaultValue : String.valueOf(value);
191
+ private final FilenameFilter filter = (f, name) -> {
192
+ // ignore directories generated by mac os x
193
+ return !name.startsWith("__MACOSX") && !name.startsWith(".") && !name.startsWith(".DS_Store");
194
+ };
195
+
196
+ /** The Activity when the app has one, otherwise the application context. */
197
+ Context context() {
198
+ final Activity current = this.activity;
199
+ if (current != null) {
200
+ return current;
399
201
  }
202
+ return this.appContext;
400
203
  }
401
204
 
402
- // ---- device facts --------------------------------------------------------------------------
403
-
404
205
  private boolean isProd() {
405
206
  try {
406
- return (this.context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0;
207
+ final Context context = this.context();
208
+ if (context == null) {
209
+ return true; // Default to production if no context
210
+ }
211
+ return (context.getApplicationInfo().flags & android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) == 0;
407
212
  } catch (Exception e) {
408
- return true;
213
+ return true; // Default to production if we can't determine
409
214
  }
410
215
  }
411
216
 
@@ -413,6 +218,7 @@ public class CapgoUpdater {
413
218
  if (installerPackageName == null || installerPackageName.trim().isEmpty()) {
414
219
  return "";
415
220
  }
221
+
416
222
  switch (installerPackageName) {
417
223
  case "com.android.vending":
418
224
  // Android exposes the Google Play installer package, but not whether the app came from production, alpha, beta, or internal testing.
@@ -430,12 +236,17 @@ public class CapgoUpdater {
430
236
 
431
237
  @SuppressWarnings("deprecation")
432
238
  private String getInstallSource() {
239
+ final Context context = this.context();
240
+ if (context == null) {
241
+ return "";
242
+ }
243
+
433
244
  try {
434
- final PackageManager packageManager = this.context.getPackageManager();
435
- final String packageName = this.context.getPackageName();
245
+ PackageManager packageManager = context.getPackageManager();
246
+ String packageName = context.getPackageName();
436
247
  String installerPackageName;
437
248
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
438
- final android.content.pm.InstallSourceInfo installSourceInfo = packageManager.getInstallSourceInfo(packageName);
249
+ android.content.pm.InstallSourceInfo installSourceInfo = packageManager.getInstallSourceInfo(packageName);
439
250
  installerPackageName = installSourceInfo.getInstallingPackageName();
440
251
  if (installerPackageName == null || installerPackageName.trim().isEmpty()) {
441
252
  installerPackageName = installSourceInfo.getInitiatingPackageName();
@@ -449,7 +260,7 @@ public class CapgoUpdater {
449
260
  }
450
261
  }
451
262
 
452
- private static boolean isEmulator() {
263
+ private boolean isEmulator() {
453
264
  final String brand = String.valueOf(Build.BRAND);
454
265
  final String device = String.valueOf(Build.DEVICE);
455
266
  final String fingerprint = String.valueOf(Build.FINGERPRINT);
@@ -479,209 +290,3658 @@ public class CapgoUpdater {
479
290
  );
480
291
  }
481
292
 
482
- // ---- Background Runner -----------------------------------------------------------------------
483
- // @capacitor/background-runner runs a script from native public storage through WorkManager: before
484
- // the live bundle changes, cancel its work, copy the new bundle's script and reschedule it.
293
+ private int calcTotalPercent(final int percent, final int min, final int max) {
294
+ return (percent * (max - min)) / 100 + min;
295
+ }
485
296
 
486
- static final class BackgroundRunnerWorkConfig {
297
+ void notifyDownload(final String id, final int percent) {}
487
298
 
488
- final String label;
489
- final String src;
490
- final String event;
491
- final boolean autoStart;
492
- final boolean repeat;
493
- final int interval;
299
+ void directUpdateFinish(final BundleInfo latest) {}
494
300
 
495
- BackgroundRunnerWorkConfig(
496
- final String label,
497
- final String src,
498
- final String event,
499
- final boolean autoStart,
500
- final boolean repeat,
501
- final int interval
502
- ) {
503
- this.label = label;
504
- this.src = src;
505
- this.event = event;
506
- this.autoStart = autoStart;
507
- this.repeat = repeat;
508
- this.interval = interval;
301
+ /** Launch downloads have no waiter. The plugin emits appReady from here when WorkManager settles. */
302
+ void backgroundDownloadSettled(final BundleInfo bundle, final String status) {}
303
+
304
+ void notifyListeners(final String id, final Map<String, Object> res) {}
305
+
306
+ /** A downloaded bundle was stored as next bundle and waits for its install moment. */
307
+ void nextBundleReady(final BundleInfo bundle) {}
308
+
309
+ static boolean shouldNotifyLaunchDownloadReady(
310
+ final boolean awaitedByCaller,
311
+ final boolean success,
312
+ final boolean directInstall,
313
+ final boolean previewSession
314
+ ) {
315
+ if (awaitedByCaller) {
316
+ return false;
317
+ }
318
+ if (!success) {
319
+ return true;
509
320
  }
321
+ return !directInstall && !previewSession;
510
322
  }
511
323
 
512
- static BackgroundRunnerWorkConfig getBackgroundRunnerWorkConfigFromConfig(final String configJson) {
513
- if (configJson == null || configJson.trim().isEmpty()) {
514
- return null;
324
+ static boolean shouldRestartOrphanedDownload(final boolean observedByThisProcess) {
325
+ return !observedByThisProcess;
326
+ }
327
+
328
+ static boolean shouldReleaseLaunchWhileRetrying(
329
+ final boolean awaitedByCaller,
330
+ final boolean setNext,
331
+ final boolean directUpdate,
332
+ final boolean previewSession
333
+ ) {
334
+ return !awaitedByCaller && setNext && directUpdate && !previewSession;
335
+ }
336
+
337
+ static String launchDownloadReadyStatus(final boolean success, final boolean setNext) {
338
+ if (!success) {
339
+ return "Error downloading file";
515
340
  }
516
- try {
517
- final JSONObject config = new JSONObject(configJson);
518
- final JSONObject plugins = config.optJSONObject("plugins");
519
- if (plugins == null) {
520
- return null;
521
- }
522
- final JSONObject backgroundRunner = plugins.optJSONObject(BACKGROUND_RUNNER_CONFIG_KEY);
523
- if (backgroundRunner == null) {
524
- return null;
525
- }
526
- final String label = backgroundRunner.optString("label", "").trim();
527
- if (label.isEmpty()) {
528
- return null;
529
- }
530
- return new BackgroundRunnerWorkConfig(
531
- label,
532
- backgroundRunner.optString("src", "").trim(),
533
- backgroundRunner.optString("event", "").trim(),
534
- backgroundRunner.optBoolean("autoStart", false),
535
- backgroundRunner.optBoolean("repeat", false),
536
- backgroundRunner.optInt("interval", 0)
537
- );
538
- } catch (JSONException ignored) {
539
- return null;
341
+ if (setNext) {
342
+ return "update downloaded, will install next background";
540
343
  }
344
+ return "update downloaded, autoUpdate onlyDownload";
541
345
  }
542
346
 
543
- private String readAssetAsString(final String assetPath) throws IOException {
544
- final StringBuilder buffer = new StringBuilder();
545
- try (
546
- final BufferedReader reader = new BufferedReader(
547
- new InputStreamReader(this.context.getAssets().open(assetPath), StandardCharsets.UTF_8)
548
- )
549
- ) {
550
- String line;
551
- while ((line = reader.readLine()) != null) {
552
- buffer.append(line).append('\n');
553
- }
347
+ public String randomString() {
348
+ final StringBuilder sb = new StringBuilder(10);
349
+ for (int i = 0; i < 10; i++) sb.append(AB.charAt(rnd.nextInt(AB.length())));
350
+ return sb.toString();
351
+ }
352
+
353
+ static boolean isManifestStagingFolderName(final String name) {
354
+ if (name == null || !name.startsWith(MANIFEST_STAGING_PREFIX)) {
355
+ return false;
554
356
  }
555
- return buffer.toString();
357
+ final String suffix = name.substring(MANIFEST_STAGING_PREFIX.length());
358
+ return suffix.length() == 10 && suffix.matches("[0-9A-Za-z]{10}");
556
359
  }
557
360
 
558
- /** Resolves {@code relativePath} inside {@code base} with the shared core path guard, then canonically. */
559
- private static File resolveInside(final File base, final String relativePath) throws IOException {
560
- final File canonicalBase = base.getCanonicalFile();
561
- final String resolved;
562
- try {
563
- resolved = CapgoCore.call(
564
- "resolvePathInside",
565
- CapgoCore.input("base", canonicalBase.getPath(), "path", relativePath)
566
- ).getString("path");
567
- } catch (CapgoCore.Failure | JSONException e) {
568
- throw new IOException("Invalid path: " + e.getMessage());
361
+ String manifestStagingDest() {
362
+ return MANIFEST_STAGING_PREFIX + this.randomString();
363
+ }
364
+
365
+ private static boolean isLegacyBareManifestStagingFolderName(final String name) {
366
+ return name != null && name.matches(LEGACY_MANIFEST_STAGING_FOLDER_PATTERN);
367
+ }
368
+
369
+ private static boolean isSymbolicLinkEntry(final File file) {
370
+ return Files.isSymbolicLink(file.toPath());
371
+ }
372
+
373
+ private static boolean isRegularFileEntry(final File file) {
374
+ return file.isFile() && !isSymbolicLinkEntry(file);
375
+ }
376
+
377
+ private static boolean isRegularDirectoryEntry(final File file) {
378
+ return file.isDirectory() && !isSymbolicLinkEntry(file);
379
+ }
380
+
381
+ private static final long LEGACY_MANIFEST_STAGING_MIN_AGE_MS = 24L * 60L * 60L * 1000L;
382
+
383
+ private static boolean looksLikeLeakedManifestStaging(final File dir) {
384
+ if (dir == null || !isRegularDirectoryEntry(dir)) {
385
+ return false;
569
386
  }
570
- final File target = new File(resolved).getCanonicalFile();
571
- final String basePath = canonicalBase.getPath().endsWith(File.separator)
572
- ? canonicalBase.getPath()
573
- : canonicalBase.getPath() + File.separator;
574
- if (!target.getPath().startsWith(basePath)) {
575
- throw new IOException("Path escapes base directory: " + relativePath);
387
+ if (isRegularFileEntry(new File(dir, "index.html"))) {
388
+ return true;
389
+ }
390
+ if (isRegularDirectoryEntry(new File(dir, "assets"))) {
391
+ return true;
576
392
  }
577
- return target;
393
+ return isRegularDirectoryEntry(new File(dir, "www"));
578
394
  }
579
395
 
580
- private void syncBackgroundRunnerScriptFromBundle(final File bundle, final BackgroundRunnerWorkConfig config) {
581
- if (bundle == null || config == null || config.src == null || config.src.isEmpty()) {
396
+ private static boolean isOldEnoughForLegacyManifestCleanup(final File dir) {
397
+ final long ageMs = System.currentTimeMillis() - dir.lastModified();
398
+ return ageMs >= LEGACY_MANIFEST_STAGING_MIN_AGE_MS;
399
+ }
400
+
401
+ void saveManifestStagingDest(final String bundleId, final String dest) {
402
+ if (this.editor == null || bundleId == null || dest == null || dest.isEmpty()) {
582
403
  return;
583
404
  }
584
- if (bundle.getPath().endsWith("/public") || "public".equals(bundle.getName())) {
405
+ this.editor.putString(bundleId + MANIFEST_DEST_SUFFIX, dest);
406
+ this.editor.commit();
407
+ }
408
+
409
+ void clearManifestStagingDest(final String bundleId) {
410
+ if (this.editor == null || bundleId == null) {
585
411
  return;
586
412
  }
587
- try {
588
- final File source = resolveInside(bundle, config.src);
589
- if (!source.isFile()) {
590
- return;
413
+ this.editor.remove(bundleId + MANIFEST_DEST_SUFFIX);
414
+ this.editor.commit();
415
+ }
416
+
417
+ void cleanupManifestStagingAfterDownloadFailed(final String bundleId, final String failedDest, final boolean failedManifest) {
418
+ if (failedManifest) {
419
+ this.deleteManifestStagingFolder(failedDest);
420
+ }
421
+ this.clearManifestStagingDest(bundleId);
422
+ }
423
+
424
+ void cleanupManifestStagingAfterDownloadCancelled(final String bundleId) {
425
+ final String cancelledDest = this.prefs != null ? this.prefs.getString(bundleId + MANIFEST_DEST_SUFFIX, null) : null;
426
+ this.deleteManifestStagingFolder(cancelledDest);
427
+ this.clearManifestStagingDest(bundleId);
428
+ }
429
+
430
+ Set<String> activeManifestStagingDests() {
431
+ final Set<String> activeDests = new HashSet<>();
432
+ if (this.prefs == null) {
433
+ return activeDests;
434
+ }
435
+ for (final BundleInfo info : this.list(true)) {
436
+ if (info == null || info.getId() == null || info.getId().isEmpty()) {
437
+ continue;
591
438
  }
592
- final File dest = resolveInside(new File(this.context.getFilesDir(), "public"), config.src);
593
- final File parent = dest.getParentFile();
594
- if (parent != null && !parent.exists() && !parent.mkdirs()) {
595
- throw new IOException("Failed to create parent directory: " + parent.getAbsolutePath());
439
+ if (info.getStatus() != BundleStatus.DOWNLOADING) {
440
+ continue;
596
441
  }
597
- final File temp = File.createTempFile("capgo-", ".tmp", parent);
598
- // Plain streams and rename (like the previous plugin): java.nio.file needs API 26.
599
- try {
600
- try (FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(temp)) {
601
- final byte[] buffer = new byte[64 * 1024];
602
- int length;
603
- while ((length = input.read(buffer)) != -1) {
604
- output.write(buffer, 0, length);
605
- }
606
- }
607
- if (!temp.renameTo(dest)) {
608
- throw new IOException("Failed to replace file: " + dest.getAbsolutePath());
609
- }
610
- } finally {
611
- if (temp.exists()) {
612
- temp.delete();
613
- }
442
+ final String dest = this.prefs.getString(info.getId() + MANIFEST_DEST_SUFFIX, null);
443
+ if (dest != null && !dest.isEmpty()) {
444
+ activeDests.add(dest);
614
445
  }
615
- logger.info("Synced Background Runner script into native public storage before bundle switch.");
616
- logger.debug("Background Runner script path: " + dest.getAbsolutePath());
617
- } catch (Exception e) {
618
- logger.debug("Background Runner script sync skipped: " + e.getMessage());
619
446
  }
447
+ return activeDests;
620
448
  }
621
449
 
622
- private void resetBackgroundRunnerWorkForBundleSwitch(final File bundle) {
623
- final BackgroundRunnerWorkConfig config;
450
+ public void deleteManifestStagingFolder(final String dest) {
451
+ if (this.documentsDir == null || dest == null || dest.isEmpty() || !isManifestStagingFolderName(dest)) {
452
+ return;
453
+ }
454
+ final File folder = new File(this.documentsDir, dest);
624
455
  try {
625
- config = getBackgroundRunnerWorkConfigFromConfig(this.readAssetAsString(CAPACITOR_CONFIG_ASSET));
626
- } catch (IOException ignored) {
456
+ this.assertPathInsideDocumentsDir(folder);
457
+ deleteManifestStagingTree(folder);
458
+ } catch (IOException e) {
459
+ logger.warn("Failed to delete manifest staging folder: " + e.getMessage());
460
+ }
461
+ }
462
+
463
+ static void deleteManifestStagingFolderAt(final File documentsDir, final String dest, final Logger log) {
464
+ if (documentsDir == null || dest == null || dest.isEmpty() || !isManifestStagingFolderName(dest)) {
627
465
  return;
628
466
  }
629
- if (config == null) {
467
+ final File folder = new File(documentsDir, dest);
468
+ if (!folder.exists()) {
630
469
  return;
631
470
  }
632
471
  try {
633
- final WorkManager workManager = WorkManager.getInstance(this.context.getApplicationContext());
634
- workManager.cancelUniqueWork(config.label);
635
- workManager.cancelAllWorkByTag(config.label);
636
- logger.info("Cancelled Background Runner work before bundle switch.");
637
- logger.debug("Background Runner label: " + config.label);
638
- } catch (Exception e) {
639
- logger.warn("Failed to cancel Background Runner work before bundle switch.");
640
- logger.debug("Background Runner cancellation error: " + e.getMessage());
472
+ final File canonicalBase = documentsDir.getCanonicalFile();
473
+ final File canonicalTarget = folder.getCanonicalFile();
474
+ final String basePath = canonicalBase.getPath();
475
+ final String normalizedBasePath = basePath.endsWith(File.separator) ? basePath : basePath + File.separator;
476
+ final String targetPath = canonicalTarget.getPath();
477
+ if (!targetPath.equals(basePath) && !targetPath.startsWith(normalizedBasePath)) {
478
+ if (log != null) {
479
+ log.warn("Refusing unsafe manifest staging delete: " + folder.getAbsolutePath());
480
+ }
481
+ return;
482
+ }
483
+ if (canonicalTarget.isDirectory()) {
484
+ deleteManifestStagingTree(canonicalTarget);
485
+ } else if (!canonicalTarget.delete()) {
486
+ if (log != null) {
487
+ log.warn("Failed to delete manifest staging file: " + canonicalTarget.getAbsolutePath());
488
+ }
489
+ }
490
+ } catch (IOException e) {
491
+ if (log != null) {
492
+ log.warn("Failed to delete manifest staging folder: " + e.getMessage());
493
+ }
641
494
  }
642
- this.syncBackgroundRunnerScriptFromBundle(bundle, config);
643
- this.rescheduleBackgroundRunnerWork(config);
644
495
  }
645
496
 
646
- private void rescheduleBackgroundRunnerWork(final BackgroundRunnerWorkConfig config) {
647
- if (!config.autoStart || config.interval <= 0 || config.src.isEmpty()) {
497
+ private static void deleteManifestStagingTree(final File file) throws IOException {
498
+ if (isSymbolicLinkEntry(file)) {
499
+ if (!file.delete()) {
500
+ throw new IOException("Failed to delete symlink: " + file);
501
+ }
648
502
  return;
649
503
  }
650
- try {
504
+ if (file.isDirectory()) {
505
+ final File[] entries = file.listFiles();
506
+ if (entries != null) {
507
+ for (final File entry : entries) {
508
+ deleteManifestStagingTree(entry);
509
+ }
510
+ }
511
+ }
512
+ if (!file.delete()) {
513
+ throw new IOException("Failed to delete: " + file);
514
+ }
515
+ }
516
+
517
+ public void cleanupOrphanedManifestStagingFolders(final Thread threadToCheck) {
518
+ if (this.documentsDir == null) {
519
+ logger.warn("Documents directory is null, skipping manifest staging cleanup");
520
+ return;
521
+ }
522
+
523
+ final File[] entries = this.documentsDir.listFiles();
524
+ if (entries == null) {
525
+ return;
526
+ }
527
+
528
+ final Set<String> protectedDests = this.activeManifestStagingDests();
529
+
530
+ for (final File entry : entries) {
531
+ if (threadToCheck != null && threadToCheck.isInterrupted()) {
532
+ logger.warn("cleanupOrphanedManifestStagingFolders was cancelled");
533
+ return;
534
+ }
535
+ if (!entry.isDirectory()) {
536
+ continue;
537
+ }
538
+ final String folderName = entry.getName();
539
+ if (!isManifestStagingFolderName(folderName)) {
540
+ continue;
541
+ }
542
+ if (protectedDests.contains(folderName)) {
543
+ continue;
544
+ }
545
+ try {
546
+ deleteManifestStagingTree(entry);
547
+ logger.info("Deleted orphaned manifest staging folder");
548
+ logger.debug("Folder: " + folderName);
549
+ } catch (IOException e) {
550
+ logger.error("Failed to delete orphaned manifest staging folder");
551
+ logger.debug("Folder: " + folderName + ", Error: " + e.getMessage());
552
+ }
553
+ }
554
+
555
+ this.cleanupLegacyBareManifestStagingFolders(threadToCheck, protectedDests);
556
+ }
557
+
558
+ private void cleanupLegacyBareManifestStagingFolders(final Thread threadToCheck, final Set<String> protectedDests) {
559
+ final File[] entries = this.documentsDir.listFiles();
560
+ if (entries == null) {
561
+ return;
562
+ }
563
+
564
+ for (final File entry : entries) {
565
+ if (threadToCheck != null && threadToCheck.isInterrupted()) {
566
+ logger.warn("cleanupLegacyBareManifestStagingFolders was cancelled");
567
+ return;
568
+ }
569
+ if (!entry.isDirectory()) {
570
+ continue;
571
+ }
572
+ final String folderName = entry.getName();
573
+ if (!isLegacyBareManifestStagingFolderName(folderName)) {
574
+ continue;
575
+ }
576
+ if (protectedDests.contains(folderName)) {
577
+ continue;
578
+ }
579
+ if (!looksLikeLeakedManifestStaging(entry)) {
580
+ continue;
581
+ }
582
+ if (!isOldEnoughForLegacyManifestCleanup(entry)) {
583
+ continue;
584
+ }
585
+ try {
586
+ deleteManifestStagingTree(entry);
587
+ logger.info("Deleted legacy bare manifest staging folder");
588
+ logger.debug("Folder: " + folderName);
589
+ } catch (IOException e) {
590
+ logger.error("Failed to delete legacy bare manifest staging folder");
591
+ logger.debug("Folder: " + folderName + ", Error: " + e.getMessage());
592
+ }
593
+ }
594
+ }
595
+
596
+ public void setPublicKey(String publicKey) {
597
+ // Empty string means no encryption - proceed normally
598
+ if (publicKey == null || publicKey.isEmpty()) {
599
+ this.publicKey = "";
600
+ this.cachedKeyId = "";
601
+ return;
602
+ }
603
+
604
+ // Non-empty: must be a valid RSA key or crash
605
+ try {
606
+ CryptoCipher.stringToPublicKey(publicKey);
607
+ } catch (Exception e) {
608
+ throw new RuntimeException(
609
+ "Invalid public key in capacitor.config.json: failed to parse RSA key. Remove the key or provide a valid PEM-formatted RSA public key.",
610
+ e
611
+ );
612
+ }
613
+
614
+ this.publicKey = publicKey;
615
+ this.cachedKeyId = CryptoCipher.calcKeyId(publicKey);
616
+ }
617
+
618
+ private void requireSessionKeyForEncryptedUpdate(final String sessionKey) throws IOException {
619
+ if (!this.publicKey.isEmpty() && !CryptoCipher.isValidSessionKey(sessionKey)) {
620
+ logger.error("Public key present but no valid session key provided");
621
+ this.sendStats("session_key_required");
622
+ throw new IOException("Session key required when public key is present");
623
+ }
624
+ }
625
+
626
+ private void requireBundleChecksum(final String checksum) throws IOException {
627
+ if (checksum == null || checksum.isEmpty()) {
628
+ logger.error("No checksum provided");
629
+ this.sendStats("checksum_required");
630
+ throw new IOException("Checksum required");
631
+ }
632
+ }
633
+
634
+ static boolean containsPathTraversalSegment(final String relativePath) {
635
+ for (final String segment : relativePath.split("/")) {
636
+ if ("..".equals(segment)) {
637
+ return true;
638
+ }
639
+ }
640
+ return false;
641
+ }
642
+
643
+ static File resolvePathInsideDirectory(final File baseDirectory, final String relativePath) throws IOException {
644
+ if (relativePath == null || relativePath.isEmpty()) {
645
+ throw new IOException("Invalid empty path");
646
+ }
647
+ if (relativePath.contains("\\") || relativePath.indexOf('\0') >= 0) {
648
+ throw new IOException("Invalid path separator");
649
+ }
650
+ if (containsPathTraversalSegment(relativePath)) {
651
+ throw new IOException("Path traversal segments are not allowed");
652
+ }
653
+ if (new File(relativePath).isAbsolute()) {
654
+ throw new IOException("Absolute paths are not allowed");
655
+ }
656
+
657
+ final File canonicalBase = baseDirectory.getCanonicalFile();
658
+ final File canonicalTarget = new File(canonicalBase, relativePath).getCanonicalFile();
659
+ final String basePath = canonicalBase.getPath();
660
+ final String targetPath = canonicalTarget.getPath();
661
+ final String normalizedBasePath = basePath.endsWith(File.separator) ? basePath : basePath + File.separator;
662
+
663
+ // Require a strict child of the base. Equality would accept "." and wipe/write the root.
664
+ if (!targetPath.startsWith(normalizedBasePath)) {
665
+ throw new IOException("Path escapes base directory: " + relativePath);
666
+ }
667
+
668
+ return canonicalTarget;
669
+ }
670
+
671
+ static File resolveBundleDirectory(final File documentsDir, final String bundleId) throws IOException {
672
+ return resolvePathInsideDirectory(new File(documentsDir, bundleDirectory), bundleId);
673
+ }
674
+
675
+ public String getKeyId() {
676
+ return this.cachedKeyId;
677
+ }
678
+
679
+ File unzip(final String id, final File zipFile, final String dest) throws IOException {
680
+ return unzip(id, zipFile, dest, CryptoCipher.ioBufferBytes());
681
+ }
682
+
683
+ File unzip(final String id, final File zipFile, final String dest, final int bufferSize) throws IOException {
684
+ final File targetDirectory = new File(this.documentsDir, dest);
685
+ try (
686
+ final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFile));
687
+ final ZipInputStream zis = new ZipInputStream(bis)
688
+ ) {
689
+ int count;
690
+ final byte[] buffer = new byte[bufferSize];
691
+ final long lengthTotal = zipFile.length();
692
+ long lengthRead = bufferSize;
693
+ int percent = 0;
694
+ this.notifyDownload(id, 75);
695
+
696
+ ZipEntry entry;
697
+ while ((entry = zis.getNextEntry()) != null) {
698
+ final File file;
699
+ try {
700
+ file = resolvePathInsideDirectory(targetDirectory, entry.getName());
701
+ } catch (IOException e) {
702
+ if (entry.getName().contains("\\")) {
703
+ logger.error("Unzip failed: Windows path not supported");
704
+ logger.debug("Invalid path: " + entry.getName());
705
+ this.sendStats("windows_path_fail");
706
+ } else {
707
+ this.sendStats("canonical_path_fail");
708
+ }
709
+ throw e;
710
+ }
711
+ final File dir = entry.isDirectory() ? file : file.getParentFile();
712
+
713
+ assert dir != null;
714
+ if (!dir.isDirectory() && !dir.mkdirs()) {
715
+ this.sendStats("directory_path_fail");
716
+ throw new FileNotFoundException("Failed to ensure directory: " + dir.getAbsolutePath());
717
+ }
718
+
719
+ if (entry.isDirectory()) {
720
+ continue;
721
+ }
722
+
723
+ try (final FileOutputStream outputStream = new FileOutputStream(file)) {
724
+ while ((count = zis.read(buffer)) != -1) outputStream.write(buffer, 0, count);
725
+ }
726
+
727
+ final int newPercent = (int) ((lengthRead / (float) lengthTotal) * 100);
728
+ if (lengthTotal > 1 && newPercent != percent) {
729
+ percent = newPercent;
730
+ this.notifyDownload(id, this.calcTotalPercent(percent, 75, 90));
731
+ }
732
+
733
+ lengthRead += entry.getCompressedSize();
734
+ }
735
+ return targetDirectory;
736
+ } catch (IOException e) {
737
+ this.sendStats("unzip_fail");
738
+ throw new IOException("Failed to unzip: " + zipFile.getPath());
739
+ }
740
+ }
741
+
742
+ private void flattenAssets(final File sourceFile, final File destinationFile) throws IOException {
743
+ if (!sourceFile.exists()) {
744
+ throw new FileNotFoundException("Source file not found: " + sourceFile.getPath());
745
+ }
746
+ assertPathInsideBundleRoot(destinationFile);
747
+ Objects.requireNonNull(destinationFile.getParentFile()).mkdirs();
748
+ final String[] entries = sourceFile.list(this.filter);
749
+ if (entries == null || entries.length == 0) {
750
+ throw new IOException("Source file was not a directory or was empty: " + sourceFile.getPath());
751
+ }
752
+ if (entries.length == 1 && !"index.html".equals(entries[0])) {
753
+ final File child = new File(sourceFile, entries[0]);
754
+ if (!child.renameTo(destinationFile)) {
755
+ throw new IOException("Failed to move bundle contents: " + child.getPath() + " -> " + destinationFile.getPath());
756
+ }
757
+ } else {
758
+ if (!sourceFile.renameTo(destinationFile)) {
759
+ throw new IOException("Failed to move bundle contents: " + sourceFile.getPath() + " -> " + destinationFile.getPath());
760
+ }
761
+ }
762
+ sourceFile.delete();
763
+ }
764
+
765
+ private void cacheBundleFilesAsync(final String id) {
766
+ io.execute(() -> cacheBundleFiles(id));
767
+ }
768
+
769
+ void cacheBundleFiles(final String id) {
770
+ if (this.context() == null) {
771
+ logger.debug("Skip delta cache population: no context");
772
+ return;
773
+ }
774
+
775
+ final File bundleDir;
776
+ try {
777
+ bundleDir = this.getBundleDirectory(id);
778
+ } catch (IOException e) {
779
+ logger.debug("Skip delta cache population: invalid bundle id");
780
+ return;
781
+ }
782
+ if (!bundleDir.exists()) {
783
+ logger.debug("Skip delta cache population: bundle dir missing");
784
+ return;
785
+ }
786
+
787
+ final File cacheDir = new File(this.context().getCacheDir(), "capgo_downloads");
788
+ if (cacheDir.exists() && !cacheDir.isDirectory()) {
789
+ logger.debug("Skip delta cache population: cache dir is not a directory");
790
+ return;
791
+ }
792
+ if (!cacheDir.exists() && !cacheDir.mkdirs()) {
793
+ logger.debug("Skip delta cache population: failed to create cache dir");
794
+ return;
795
+ }
796
+
797
+ final File builtinFolder = new File(this.context().getFilesDir(), "public");
798
+
799
+ final List<File> files = new ArrayList<>();
800
+ collectFiles(bundleDir, files);
801
+ final int bundlePrefixLength = bundleDir.getAbsolutePath().length() + 1;
802
+ for (File file : files) {
803
+ final String checksum = CryptoCipher.calcChecksum(file);
804
+ if (checksum.isEmpty()) {
805
+ continue;
806
+ }
807
+
808
+ // Builtin is already a permanent reuse source (see isManifestEntryAvailableLocally),
809
+ // so there's no need to also duplicate a byte-identical file into the delta cache.
810
+ final String relativePath = file.getAbsolutePath().substring(bundlePrefixLength);
811
+ final File builtinFile = new File(builtinFolder, relativePath);
812
+ if (verifyChecksum(builtinFile, checksum)) {
813
+ continue;
814
+ }
815
+
816
+ final String cacheName = checksum + "_" + file.getName();
817
+ final File cacheFile = new File(cacheDir, cacheName);
818
+ if (cacheFile.exists()) {
819
+ continue;
820
+ }
821
+ try {
822
+ copyFileAtomically(file, cacheFile);
823
+ } catch (IOException e) {
824
+ logger.debug("Delta cache copy failed: " + file.getPath());
825
+ }
826
+ }
827
+ }
828
+
829
+ private void collectFiles(final File dir, final List<File> files) {
830
+ final File[] entries = dir.listFiles();
831
+ if (entries == null) {
832
+ return;
833
+ }
834
+ for (File entry : entries) {
835
+ if (!this.filter.accept(dir, entry.getName())) {
836
+ continue;
837
+ }
838
+ if (entry.isDirectory()) {
839
+ collectFiles(entry, files);
840
+ } else if (entry.isFile()) {
841
+ files.add(entry);
842
+ }
843
+ }
844
+ }
845
+
846
+ private void copyFile(final File source, final File dest) throws IOException {
847
+ try (final FileInputStream input = new FileInputStream(source); final FileOutputStream output = new FileOutputStream(dest)) {
848
+ final byte[] buffer = new byte[CryptoCipher.copyBufferBytes()];
849
+ int length;
850
+ while ((length = input.read(buffer)) != -1) {
851
+ output.write(buffer, 0, length);
852
+ }
853
+ }
854
+ }
855
+
856
+ private boolean verifyChecksum(final File file, final String expectedHash) {
857
+ if (expectedHash == null || expectedHash.isEmpty() || file == null || !file.exists()) {
858
+ return false;
859
+ }
860
+ final String actualHash = CryptoCipher.calcChecksum(file);
861
+ return expectedHash.equalsIgnoreCase(actualHash);
862
+ }
863
+
864
+ private String resolveManifestFileHash(final JSONObject entry, final String sessionKey) {
865
+ String fileHash = entry.optString("file_hash", "");
866
+ if (fileHash.isEmpty()) {
867
+ return "";
868
+ }
869
+ if (this.publicKey != null && !this.publicKey.isEmpty()) {
870
+ if (!CryptoCipher.isValidSessionKey(sessionKey)) {
871
+ return "";
872
+ }
873
+ try {
874
+ fileHash = CryptoCipher.decryptChecksum(fileHash, this.publicKey);
875
+ } catch (Exception e) {
876
+ logger.error("Checksum decryption failed while checking missing manifest files");
877
+ logger.debug("File: " + entry.optString("file_name", "unknown") + ", Error: " + e.getMessage());
878
+ return "";
879
+ }
880
+ }
881
+ return fileHash;
882
+ }
883
+
884
+ private boolean isManifestEntryAvailableLocally(final JSONObject entry, final String sessionKey) {
885
+ final String fileName = entry.optString("file_name", "");
886
+ final String fileHash = resolveManifestFileHash(entry, sessionKey);
887
+ if (fileName.isEmpty() || fileHash.isEmpty() || this.context() == null) {
888
+ return false;
889
+ }
890
+
891
+ if (DownloadService.builtinAssetMatches(this.context().getAssets(), fileName, fileHash)) {
892
+ return true;
893
+ }
894
+
895
+ try {
896
+ final File builtinFile = DownloadService.resolveManifestBuiltinFile(new File(this.context().getFilesDir(), "public"), fileName);
897
+ if (verifyChecksum(builtinFile, fileHash)) {
898
+ return true;
899
+ }
900
+ } catch (IOException ignored) {
901
+ // Invalid path; fall through to cache lookup.
902
+ }
903
+
904
+ final boolean isBrotli = fileName.endsWith(".br");
905
+ final String fileNameWithoutPath = new File(fileName).getName();
906
+ final String cacheBaseName = isBrotli ? fileNameWithoutPath.substring(0, fileNameWithoutPath.length() - 3) : fileNameWithoutPath;
907
+ if (isSafeCacheHash(fileHash)) {
908
+ final File cacheFolder = new File(this.context().getCacheDir(), "capgo_downloads");
909
+ final File cacheFile = new File(cacheFolder, fileHash + "_" + cacheBaseName);
910
+ // Cache files are named `{hash}_{filename}` and were checksum-verified
911
+ // when written. Re-hashing every hit re-reads the whole bundle and
912
+ // OOMs/janks low-RAM devices during getMissing / delta apply.
913
+ if (isReusableCacheFile(cacheFile, fileHash)) {
914
+ return true;
915
+ }
916
+
917
+ if (isBrotli) {
918
+ final File legacyCacheFile = new File(cacheFolder, fileHash + "_" + fileNameWithoutPath);
919
+ return isReusableCacheFile(legacyCacheFile, fileHash);
920
+ }
921
+ }
922
+
923
+ return false;
924
+ }
925
+
926
+ static final String EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
927
+
928
+ static boolean isSafeCacheHash(final String hash) {
929
+ if (hash == null) {
930
+ return false;
931
+ }
932
+ final int len = hash.length();
933
+ if (len != 64 && len != 8) {
934
+ return false;
935
+ }
936
+ for (int i = 0; i < len; i++) {
937
+ final char c = hash.charAt(i);
938
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
939
+ return false;
940
+ }
941
+ }
942
+ return true;
943
+ }
944
+
945
+ // SHA-256 hash-named cache files were verified when written. Existence is
946
+ // enough for non-empty files; empty files are reused only for the empty SHA-256.
947
+ // CRC32 (8 hex) is too collision-prone to trust without a re-read.
948
+ static boolean isReusableCacheFile(final File file, final String expectedHash) {
949
+ if (file == null || !file.isFile() || !isSafeCacheHash(expectedHash) || expectedHash.length() != 64) {
950
+ return false;
951
+ }
952
+ final long length = file.length();
953
+ if (length > 0) {
954
+ return true;
955
+ }
956
+ return length == 0 && EMPTY_SHA256.equalsIgnoreCase(expectedHash);
957
+ }
958
+
959
+ public JSONArray getMissingBundleFiles(final JSONArray manifest, final String sessionKey) throws JSONException {
960
+ final JSONArray missing = new JSONArray();
961
+ for (int i = 0; i < manifest.length(); i++) {
962
+ final JSONObject entry = manifest.getJSONObject(i);
963
+ if (!isManifestEntryAvailableLocally(entry, sessionKey)) {
964
+ missing.put(entry);
965
+ }
966
+ }
967
+ return missing;
968
+ }
969
+
970
+ public JSONObject missingBundleFilesResult(final JSONArray manifest, final String sessionKey) throws JSONException {
971
+ final JSONArray missing = getMissingBundleFiles(manifest, sessionKey);
972
+ final JSONObject ret = new JSONObject();
973
+ ret.put("missing", missing);
974
+ ret.put("total", manifest.length());
975
+ ret.put("missingCount", missing.length());
976
+ ret.put("reusableCount", manifest.length() - missing.length());
977
+ return ret;
978
+ }
979
+
980
+ private String manifestSizeUrl(final String updateUrl) {
981
+ HttpUrl parsed = HttpUrl.parse(updateUrl);
982
+ if (parsed == null) {
983
+ return updateUrl;
984
+ }
985
+ return parsed.newBuilder().addPathSegment("manifest_size").query(null).build().toString();
986
+ }
987
+
988
+ private JSONObject unavailableBundleSizeResult(final JSONArray manifest, final String error) throws JSONException {
989
+ final JSONObject ret = new JSONObject();
990
+ final JSONArray files = new JSONArray();
991
+ for (int i = 0; i < manifest.length(); i++) {
992
+ final JSONObject entry = new JSONObject(manifest.getJSONObject(i).toString());
993
+ entry.put("error", error);
994
+ files.put(entry);
995
+ }
996
+ ret.put("totalSize", 0);
997
+ ret.put("knownFiles", 0);
998
+ ret.put("unknownFiles", manifest.length());
999
+ ret.put("files", files);
1000
+ return ret;
1001
+ }
1002
+
1003
+ public JSONObject getBundleDownloadSize(final String updateUrl, final String version, final JSONArray manifest) throws JSONException {
1004
+ if (manifest.length() == 0) {
1005
+ final JSONObject ret = new JSONObject();
1006
+ ret.put("totalSize", 0);
1007
+ ret.put("knownFiles", 0);
1008
+ ret.put("unknownFiles", 0);
1009
+ ret.put("files", new JSONArray());
1010
+ return ret;
1011
+ }
1012
+
1013
+ final JSONObject json = this.createInfoObject();
1014
+ json.put("version", version != null ? version : "");
1015
+ json.put("manifest", manifest);
1016
+
1017
+ Request request = new Request.Builder()
1018
+ .url(manifestSizeUrl(updateUrl))
1019
+ .post(RequestBody.create(json.toString(), MediaType.get("application/json; charset=utf-8")))
1020
+ .build();
1021
+
1022
+ try (Response response = DownloadService.sharedClient.newCall(request).execute()) {
1023
+ final ResponseBody responseBody = response.body();
1024
+ final String responseData = responseBody != null ? responseBody.string() : "";
1025
+ if (!response.isSuccessful() || responseData.isEmpty()) {
1026
+ return unavailableBundleSizeResult(manifest, "response_error");
1027
+ }
1028
+ return new JSONObject(responseData);
1029
+ } catch (IOException e) {
1030
+ logger.error("Error getting bundle download size");
1031
+ logger.debug("Error: " + e.getMessage());
1032
+ return unavailableBundleSizeResult(manifest, "response_error");
1033
+ }
1034
+ }
1035
+
1036
+ private void notifyLaunchDownloadReady(
1037
+ final boolean awaitedByCaller,
1038
+ final boolean success,
1039
+ final boolean directInstall,
1040
+ final boolean previewSession,
1041
+ final boolean setNext,
1042
+ final BundleInfo bundle
1043
+ ) {
1044
+ if (!shouldNotifyLaunchDownloadReady(awaitedByCaller, success, directInstall, previewSession)) {
1045
+ return;
1046
+ }
1047
+ final BundleInfo readyBundle = bundle != null ? bundle : this.getCurrentBundle();
1048
+ this.backgroundDownloadSettled(readyBundle, launchDownloadReadyStatus(success, setNext));
1049
+ }
1050
+
1051
+ // Created on first use: plain JVM unit tests construct CapgoUpdater without a main Looper.
1052
+ private Handler mainHandler() {
1053
+ Handler handler = this.mainHandler;
1054
+ if (handler == null) {
1055
+ handler = new Handler(Looper.getMainLooper());
1056
+ this.mainHandler = handler;
1057
+ }
1058
+ return handler;
1059
+ }
1060
+
1061
+ @SuppressWarnings("unchecked")
1062
+ private void observeWorkProgress(Context context, String id, String observedVersion, boolean setNext) {
1063
+ final AtomicBoolean terminalHandled = new AtomicBoolean(false);
1064
+ final AtomicBoolean launchReleasedWhileRetrying = new AtomicBoolean(false);
1065
+ final LiveData<List<WorkInfo>> workInfosLiveData = WorkManager.getInstance(
1066
+ context.getApplicationContext()
1067
+ ).getWorkInfosByTagLiveData(id);
1068
+ // observeForever, not observe(activity): a stopped Activity pauses LiveData, so a download
1069
+ // that completes while the app is in the background would only be finished once the user
1070
+ // opens the app again. The observer removes itself on a terminal state.
1071
+ final Observer<List<WorkInfo>>[] observerRef = new Observer[1];
1072
+ final Runnable removeObserver = () -> mainHandler().post(() -> workInfosLiveData.removeObserver(observerRef[0]));
1073
+ mainHandler().post(() -> {
1074
+ observerRef[0] = (workInfos) -> {
1075
+ if (workInfos == null || workInfos.isEmpty()) return;
1076
+
1077
+ WorkInfo workInfo = workInfos.get(0);
1078
+ Data progress = workInfo.getProgress();
1079
+
1080
+ switch (workInfo.getState()) {
1081
+ case ENQUEUED:
1082
+ // A run attempt already happened, so WorkManager scheduled a retry (network lost midway,
1083
+ // 5xx, ...). Retries back off without limit, so a direct install must not keep the launch
1084
+ // (and its splashscreen) blocked until the network comes back.
1085
+ if (
1086
+ workInfo.getRunAttemptCount() > 0 &&
1087
+ shouldReleaseLaunchWhileRetrying(
1088
+ downloadFutures.containsKey(id),
1089
+ setNext,
1090
+ Boolean.TRUE.equals(CapgoUpdater.this.directUpdate),
1091
+ CapgoUpdater.this.previewSession
1092
+ ) &&
1093
+ launchReleasedWhileRetrying.compareAndSet(false, true)
1094
+ ) {
1095
+ logger.warn("Direct update download is retrying, continuing launch on the current bundle");
1096
+ // Same fallback as the autoSplashscreen timeout: a later success installs on next background.
1097
+ CapgoUpdater.this.directUpdate = false;
1098
+ io.execute(() -> backgroundDownloadSettled(getCurrentBundle(), launchDownloadReadyStatus(false, false)));
1099
+ }
1100
+ break;
1101
+ case RUNNING:
1102
+ int percent = progress.getInt(DownloadService.PERCENT, 0);
1103
+ notifyDownload(id, percent);
1104
+ break;
1105
+ case SUCCEEDED:
1106
+ if (!terminalHandled.compareAndSet(false, true)) break;
1107
+ removeObserver.run();
1108
+ observedDownloadVersions.remove(observedVersion);
1109
+ logger.info("Download succeeded: " + workInfo.getState());
1110
+ Data outputData = workInfo.getOutputData();
1111
+ String dest = outputData.getString(DownloadService.FILEDEST);
1112
+ String version = outputData.getString(DownloadService.VERSION);
1113
+ String sessionKey = outputData.getString(DownloadService.SESSIONKEY);
1114
+ String checksum = outputData.getString(DownloadService.CHECKSUM);
1115
+ boolean isManifest = outputData.getBoolean(DownloadService.IS_MANIFEST, false);
1116
+
1117
+ io.execute(() -> {
1118
+ // finishDownload clears directUpdate, so read the install plan first.
1119
+ final boolean directInstall =
1120
+ setNext && Boolean.TRUE.equals(CapgoUpdater.this.directUpdate) && !CapgoUpdater.this.previewSession;
1121
+ final boolean previewSession = CapgoUpdater.this.previewSession;
1122
+ boolean success = finishDownload(id, dest, version, sessionKey, checksum, setNext, isManifest);
1123
+ BundleInfo resultBundle;
1124
+ if (!success) {
1125
+ logger.error("Finish download failed");
1126
+ logger.debug("Version: " + version);
1127
+ resultBundle = new BundleInfo(id, version, BundleStatus.ERROR, new Date(System.currentTimeMillis()), "");
1128
+ saveBundleInfo(id, resultBundle);
1129
+ // Cleanup download tracking
1130
+ DownloadWorkerManager.cancelBundleDownload(context, id, version);
1131
+ sendStats("finish_download_fail", version);
1132
+ // finishDownload already emitted downloadFailed for this failure.
1133
+ } else {
1134
+ // Successful download - cleanup tracking
1135
+ DownloadWorkerManager.cancelBundleDownload(context, id, version);
1136
+ resultBundle = getBundleInfo(id);
1137
+ }
1138
+
1139
+ CapgoUpdater.this.clearManifestStagingDest(id);
1140
+
1141
+ // Complete the future if it exists. download() waits on it.
1142
+ // downloadBackground does not, so the launch check must emit appReady here.
1143
+ CompletableFuture<BundleInfo> future = downloadFutures.remove(id);
1144
+ if (future != null) {
1145
+ future.complete(resultBundle);
1146
+ }
1147
+ final BundleInfo readyBundle = success && setNext ? resultBundle : null;
1148
+ if (!launchReleasedWhileRetrying.get()) {
1149
+ notifyLaunchDownloadReady(future != null, success, directInstall, previewSession, setNext, readyBundle);
1150
+ }
1151
+ });
1152
+ break;
1153
+ case FAILED:
1154
+ if (!terminalHandled.compareAndSet(false, true)) break;
1155
+ removeObserver.run();
1156
+ observedDownloadVersions.remove(observedVersion);
1157
+ Data failedData = workInfo.getOutputData();
1158
+ String error = failedData.getString(DownloadService.ERROR);
1159
+ logger.error("Download failed");
1160
+ logger.debug("Error: " + error + ", State: " + workInfo.getState());
1161
+ String failedVersion = failedData.getString(DownloadService.VERSION);
1162
+ final String failedDest = failedData.getString(DownloadService.FILEDEST);
1163
+ final boolean failedManifest = failedData.getBoolean(DownloadService.IS_MANIFEST, false);
1164
+
1165
+ io.execute(() -> {
1166
+ CapgoUpdater.this.cleanupManifestStagingAfterDownloadFailed(id, failedDest, failedManifest);
1167
+ BundleInfo failedBundle = new BundleInfo(
1168
+ id,
1169
+ failedVersion,
1170
+ BundleStatus.ERROR,
1171
+ new Date(System.currentTimeMillis()),
1172
+ ""
1173
+ );
1174
+ saveBundleInfo(id, failedBundle);
1175
+ // Cleanup download tracking for failed downloads
1176
+ DownloadWorkerManager.cancelBundleDownload(context, id, failedVersion);
1177
+ Map<String, Object> ret = new HashMap<>();
1178
+ ret.put("version", failedVersion);
1179
+ if ("low_mem_fail".equals(error)) {
1180
+ sendStats("low_mem_fail", failedVersion);
1181
+ }
1182
+ if ("insufficient_disk_space".equals(error)) {
1183
+ sendStats("insufficient_disk_space", failedVersion);
1184
+ }
1185
+ ret.put("error", error != null ? error : "download_fail");
1186
+ sendStats("download_fail", failedVersion);
1187
+ notifyListeners("downloadFailed", ret);
1188
+
1189
+ // Complete the future with error status
1190
+ CompletableFuture<BundleInfo> failedFuture = downloadFutures.remove(id);
1191
+ if (failedFuture != null) {
1192
+ failedFuture.complete(failedBundle);
1193
+ }
1194
+ if (!launchReleasedWhileRetrying.get()) {
1195
+ notifyLaunchDownloadReady(failedFuture != null, false, false, false, false, null);
1196
+ }
1197
+ });
1198
+ break;
1199
+ case CANCELLED:
1200
+ if (!terminalHandled.compareAndSet(false, true)) break;
1201
+ removeObserver.run();
1202
+ observedDownloadVersions.remove(observedVersion);
1203
+ DataManager.getInstance().clearManifest(id);
1204
+ io.execute(() -> CapgoUpdater.this.cleanupManifestStagingAfterDownloadCancelled(id));
1205
+ CompletableFuture<BundleInfo> cancelledFuture = downloadFutures.remove(id);
1206
+ if (cancelledFuture != null) {
1207
+ cancelledFuture.cancel(true);
1208
+ }
1209
+ break;
1210
+ }
1211
+ };
1212
+ workInfosLiveData.observeForever(observerRef[0]);
1213
+ });
1214
+ }
1215
+
1216
+ private void download(
1217
+ final String id,
1218
+ final String url,
1219
+ final String dest,
1220
+ final String version,
1221
+ final String sessionKey,
1222
+ final String checksum,
1223
+ final JSONArray manifest,
1224
+ final boolean setNext
1225
+ ) {
1226
+ final Context context = this.context();
1227
+ if (context == null) {
1228
+ logger.error("No context, cannot observe work progress");
1229
+ return;
1230
+ }
1231
+ observedDownloadVersions.add(version);
1232
+ observeWorkProgress(context, id, version, setNext);
1233
+
1234
+ if (manifest != null) {
1235
+ DataManager.getInstance().setManifest(id, manifest);
1236
+ this.saveManifestStagingDest(id, dest);
1237
+ }
1238
+
1239
+ DownloadWorkerManager.enqueueDownload(
1240
+ context,
1241
+ url,
1242
+ id,
1243
+ this.documentsDir.getAbsolutePath(),
1244
+ dest,
1245
+ version,
1246
+ sessionKey,
1247
+ checksum,
1248
+ this.publicKey,
1249
+ manifest != null,
1250
+ this.isEmulator(),
1251
+ this.appId,
1252
+ this.pluginVersion,
1253
+ this.isProd(),
1254
+ this.getInstallSource(),
1255
+ this.statsUrl,
1256
+ this.deviceID,
1257
+ this.versionBuild,
1258
+ this.versionCode,
1259
+ this.versionOs,
1260
+ this.customId,
1261
+ this.defaultChannel
1262
+ );
1263
+ }
1264
+
1265
+ public Boolean finishDownload(
1266
+ String id,
1267
+ String dest,
1268
+ String version,
1269
+ String sessionKey,
1270
+ String checksumRes,
1271
+ Boolean setNext,
1272
+ Boolean isManifest
1273
+ ) {
1274
+ File downloaded = null;
1275
+ File extractedDir = null;
1276
+ String checksum = "";
1277
+
1278
+ try {
1279
+ this.requireSessionKeyForEncryptedUpdate(sessionKey);
1280
+ this.notifyDownload(id, 71);
1281
+ downloaded = new File(this.documentsDir, dest);
1282
+
1283
+ if (!isManifest) {
1284
+ String expectedChecksum = Objects.requireNonNullElse(checksumRes, "");
1285
+ this.requireBundleChecksum(expectedChecksum);
1286
+
1287
+ if (CryptoCipher.isValidSessionKey(sessionKey)) {
1288
+ CryptoCipher.decryptFile(downloaded, publicKey, sessionKey);
1289
+ expectedChecksum = CryptoCipher.decryptChecksum(checksumRes, publicKey);
1290
+ }
1291
+ checksum = CryptoCipher.calcChecksum(downloaded);
1292
+ CryptoCipher.logChecksumInfo("Calculated checksum", checksum);
1293
+ CryptoCipher.logChecksumInfo("Expected checksum", expectedChecksum);
1294
+ if (!expectedChecksum.equals(checksum)) {
1295
+ logger.error("Checksum mismatch");
1296
+ logger.debug("Expected: " + expectedChecksum + ", Got: " + checksum);
1297
+ this.sendStats("checksum_fail");
1298
+ throw new IOException("Checksum failed: " + id);
1299
+ }
1300
+ }
1301
+ // Remove the decryption for manifest downloads
1302
+ } catch (Exception e) {
1303
+ safeDelete(downloaded);
1304
+ final Boolean res = this.delete(id);
1305
+ if (!res) {
1306
+ logger.info("Failed to cleanup after error");
1307
+ logger.debug("Version: " + version);
1308
+ }
1309
+
1310
+ final Map<String, Object> ret = new HashMap<>();
1311
+ ret.put("version", version);
1312
+
1313
+ CapgoUpdater.this.notifyListeners("downloadFailed", ret);
1314
+ CapgoUpdater.this.sendStats("download_fail");
1315
+ return false;
1316
+ }
1317
+
1318
+ try {
1319
+ if (!isManifest) {
1320
+ extractedDir = this.unzip(id, downloaded, TEMP_UNZIP_PREFIX + this.randomString());
1321
+ this.notifyDownload(id, 91);
1322
+ this.flattenAssets(extractedDir, this.getBundleDirectory(id));
1323
+ this.cacheBundleFilesAsync(id);
1324
+ } else {
1325
+ this.notifyDownload(id, 91);
1326
+ this.flattenAssets(downloaded, this.getBundleDirectory(id));
1327
+ downloaded.delete();
1328
+ }
1329
+ // Remove old bundle info and set new one
1330
+ this.saveBundleInfo(id, null);
1331
+ BundleInfo next = new BundleInfo(id, version, BundleStatus.PENDING, new Date(System.currentTimeMillis()), checksum);
1332
+ this.saveBundleInfo(id, next);
1333
+ this.notifyDownload(id, 100);
1334
+
1335
+ final Map<String, Object> ret = new HashMap<>();
1336
+ ret.put("bundle", InternalUtils.mapToJSObject(next.toJSONMap()));
1337
+ logger.info("updateAvailable: " + ret);
1338
+ CapgoUpdater.this.notifyListeners("updateAvailable", ret);
1339
+ logger.info("setNext: " + setNext);
1340
+ if (setNext) {
1341
+ if (this.previewSession) {
1342
+ logger.info("Preview session is active, skipping automatic install of downloaded bundle");
1343
+ this.directUpdate = false;
1344
+ } else if (this.directUpdate) {
1345
+ logger.info("directUpdate: " + this.directUpdate);
1346
+ CapgoUpdater.this.directUpdateFinish(next);
1347
+ this.directUpdate = false;
1348
+ } else {
1349
+ logger.info("directUpdate: " + this.directUpdate);
1350
+ if (this.setNextBundle(next.getId())) {
1351
+ this.nextBundleReady(next);
1352
+ }
1353
+ }
1354
+ }
1355
+ } catch (IOException e) {
1356
+ safeDelete(extractedDir);
1357
+ safeDelete(downloaded);
1358
+ e.printStackTrace();
1359
+ final Map<String, Object> ret = new HashMap<>();
1360
+ ret.put("version", version);
1361
+ CapgoUpdater.this.notifyListeners("downloadFailed", ret);
1362
+ CapgoUpdater.this.sendStats("download_fail");
1363
+ return false;
1364
+ }
1365
+ if (!isManifest) {
1366
+ safeDelete(downloaded);
1367
+ }
1368
+ return true;
1369
+ }
1370
+
1371
+ private void deleteDirectory(final File file) throws IOException {
1372
+ deleteDirectory(file, null);
1373
+ }
1374
+
1375
+ private void deleteDirectory(final File file, final Thread threadToCheck) throws IOException {
1376
+ // Check if thread was interrupted (cancelled)
1377
+ if (threadToCheck != null && threadToCheck.isInterrupted()) {
1378
+ throw new IOException("Operation cancelled");
1379
+ }
1380
+
1381
+ if (file.isDirectory()) {
1382
+ final File[] entries = file.listFiles();
1383
+ if (entries != null) {
1384
+ for (final File entry : entries) {
1385
+ this.deleteDirectory(entry, threadToCheck);
1386
+ }
1387
+ }
1388
+ }
1389
+ if (!file.delete()) {
1390
+ throw new IOException("Failed to delete: " + file);
1391
+ }
1392
+ }
1393
+
1394
+ public void cleanupDeltaCache() {
1395
+ cleanupDeltaCache(null);
1396
+ }
1397
+
1398
+ public void cleanupDeltaCache(final Thread threadToCheck) {
1399
+ if (this.context() == null) {
1400
+ logger.warn("Activity is null, skipping delta cache cleanup");
1401
+ return;
1402
+ }
1403
+ final File cacheFolder = new File(this.context().getCacheDir(), "capgo_downloads");
1404
+ if (!cacheFolder.exists()) {
1405
+ return;
1406
+ }
1407
+ try {
1408
+ this.deleteDirectory(cacheFolder, threadToCheck);
1409
+ logger.info("Cleaned up delta cache folder");
1410
+ } catch (IOException e) {
1411
+ logger.error("Failed to cleanup delta cache");
1412
+ logger.debug("Error: " + e.getMessage());
1413
+ }
1414
+ }
1415
+
1416
+ public void cleanupDownloadDirectories(final Set<String> allowedIds) {
1417
+ cleanupDownloadDirectories(allowedIds, null);
1418
+ }
1419
+
1420
+ public void cleanupDownloadDirectories(final Set<String> allowedIds, final Thread threadToCheck) {
1421
+ if (this.documentsDir == null) {
1422
+ logger.warn("Documents directory is null, skipping download cleanup");
1423
+ return;
1424
+ }
1425
+
1426
+ final File bundleRoot = new File(this.documentsDir, bundleDirectory);
1427
+ if (!bundleRoot.exists() || !bundleRoot.isDirectory()) {
1428
+ return;
1429
+ }
1430
+
1431
+ final File[] entries = bundleRoot.listFiles();
1432
+ if (entries != null) {
1433
+ for (final File entry : entries) {
1434
+ // Check if thread was interrupted (cancelled)
1435
+ if (threadToCheck != null && threadToCheck.isInterrupted()) {
1436
+ logger.warn("cleanupDownloadDirectories was cancelled");
1437
+ return;
1438
+ }
1439
+
1440
+ if (!entry.isDirectory()) {
1441
+ continue;
1442
+ }
1443
+
1444
+ final String id = entry.getName();
1445
+
1446
+ if (allowedIds != null && allowedIds.contains(id)) {
1447
+ continue;
1448
+ }
1449
+
1450
+ try {
1451
+ this.deleteDirectory(entry, threadToCheck);
1452
+ if (entry.exists()) {
1453
+ logger.error("Orphan bundle directory still present after delete");
1454
+ logger.debug("Bundle ID: " + id);
1455
+ continue;
1456
+ }
1457
+ this.removeBundleInfo(id);
1458
+ logger.info("Deleted orphan bundle directory");
1459
+ logger.debug("Bundle ID: " + id);
1460
+ } catch (IOException e) {
1461
+ logger.error("Failed to delete orphan bundle directory");
1462
+ logger.debug("Bundle ID: " + id + ", Error: " + e.getMessage());
1463
+ }
1464
+ }
1465
+ }
1466
+ }
1467
+
1468
+ public Set<String> allowedBundleIdsForCleanup() {
1469
+ final Set<String> allowedIds = new HashSet<>();
1470
+ for (final BundleInfo info : this.list(true)) {
1471
+ if (info == null || info.getId() == null || info.getId().isEmpty()) {
1472
+ continue;
1473
+ }
1474
+ // DELETED tombstones must not protect leftover folders.
1475
+ // DELETING stays protected so drainPendingDeletes owns the removal.
1476
+ if (info.isDeleted()) {
1477
+ continue;
1478
+ }
1479
+ allowedIds.add(info.getId());
1480
+ }
1481
+ final String currentId = this.getCurrentBundleId();
1482
+ if (currentId != null && !currentId.isEmpty()) {
1483
+ allowedIds.add(currentId);
1484
+ }
1485
+ final BundleInfo fallback = this.getFallbackBundle();
1486
+ if (fallback != null && fallback.getId() != null && !fallback.getId().isEmpty() && !fallback.isDeleting()) {
1487
+ allowedIds.add(fallback.getId());
1488
+ }
1489
+ final BundleInfo next = this.getNextBundle();
1490
+ if (next != null && next.getId() != null && !next.getId().isEmpty() && !next.isDeleting()) {
1491
+ allowedIds.add(next.getId());
1492
+ }
1493
+ final BundleInfo previewFallback = this.getPreviewFallbackBundle();
1494
+ if (
1495
+ previewFallback != null &&
1496
+ previewFallback.getId() != null &&
1497
+ !previewFallback.getId().isEmpty() &&
1498
+ !previewFallback.isDeleting()
1499
+ ) {
1500
+ allowedIds.add(previewFallback.getId());
1501
+ }
1502
+ return allowedIds;
1503
+ }
1504
+
1505
+ public void cleanupOrphanedTempFolders(final Thread threadToCheck) {
1506
+ if (this.documentsDir == null) {
1507
+ logger.warn("Documents directory is null, skipping temp folder cleanup");
1508
+ return;
1509
+ }
1510
+
1511
+ final File[] entries = this.documentsDir.listFiles();
1512
+ if (entries == null) {
1513
+ return;
1514
+ }
1515
+
1516
+ for (final File entry : entries) {
1517
+ // Check if thread was interrupted (cancelled)
1518
+ if (threadToCheck != null && threadToCheck.isInterrupted()) {
1519
+ logger.warn("cleanupOrphanedTempFolders was cancelled");
1520
+ return;
1521
+ }
1522
+
1523
+ if (!entry.isDirectory()) {
1524
+ continue;
1525
+ }
1526
+
1527
+ final String folderName = entry.getName();
1528
+
1529
+ // Only delete folders with the temp unzip prefix
1530
+ if (!folderName.startsWith(TEMP_UNZIP_PREFIX)) {
1531
+ continue;
1532
+ }
1533
+
1534
+ try {
1535
+ this.deleteDirectory(entry, threadToCheck);
1536
+ logger.info("Deleted orphaned temp unzip folder");
1537
+ logger.debug("Folder: " + folderName);
1538
+ } catch (IOException e) {
1539
+ logger.error("Failed to delete orphaned temp folder");
1540
+ logger.debug("Folder: " + folderName + ", Error: " + e.getMessage());
1541
+ }
1542
+ }
1543
+ }
1544
+
1545
+ private void assertPathInsideDocumentsDir(final File target) throws IOException {
1546
+ if (this.documentsDir == null) {
1547
+ throw new IOException("Documents directory unavailable");
1548
+ }
1549
+ final File canonicalBase = this.documentsDir.getCanonicalFile();
1550
+ final File canonicalTarget = target.getCanonicalFile();
1551
+ final String basePath = canonicalBase.getPath();
1552
+ final String normalizedBasePath = basePath.endsWith(File.separator) ? basePath : basePath + File.separator;
1553
+ final String targetPath = canonicalTarget.getPath();
1554
+ if (!targetPath.equals(basePath) && !targetPath.startsWith(normalizedBasePath)) {
1555
+ throw new IOException("Path escapes updater storage: " + target.getPath());
1556
+ }
1557
+ }
1558
+
1559
+ private void assertPathInsideBundleRoot(final File target) throws IOException {
1560
+ final File bundleRoot = new File(this.documentsDir, bundleDirectory).getCanonicalFile();
1561
+ final File canonicalTarget = target.getCanonicalFile();
1562
+ final String basePath = bundleRoot.getPath();
1563
+ final String normalizedBasePath = basePath.endsWith(File.separator) ? basePath : basePath + File.separator;
1564
+ final String targetPath = canonicalTarget.getPath();
1565
+ if (!targetPath.equals(basePath) && !targetPath.startsWith(normalizedBasePath)) {
1566
+ throw new IOException("Path escapes bundle storage: " + target.getPath());
1567
+ }
1568
+ }
1569
+
1570
+ private void safeDelete(final File target) {
1571
+ if (target == null || !target.exists()) {
1572
+ return;
1573
+ }
1574
+ try {
1575
+ this.assertPathInsideDocumentsDir(target);
1576
+ if (target.isDirectory()) {
1577
+ this.deleteDirectory(target);
1578
+ } else if (!target.delete()) {
1579
+ logger.warn("Failed to delete file: " + target.getAbsolutePath());
1580
+ }
1581
+ } catch (IOException cleanupError) {
1582
+ logger.warn("Refusing unsafe delete for " + target.getAbsolutePath() + ": " + cleanupError.getMessage());
1583
+ }
1584
+ }
1585
+
1586
+ private void setCurrentBundle(final File bundle) {
1587
+ this.resetBackgroundRunnerWorkForBundleSwitch(bundle);
1588
+ this.editor.putString(this.CAP_SERVER_PATH, bundle.getPath());
1589
+ logger.info("Current bundle set to: " + bundle);
1590
+ this.editor.commit();
1591
+ }
1592
+
1593
+ static boolean shouldResetForForeignBundle(final String bundlePath, final boolean isBuiltin, final boolean hasStoredBundleInfo) {
1594
+ return bundlePath != null && !bundlePath.trim().isEmpty() && !isBuiltin && !hasStoredBundleInfo;
1595
+ }
1596
+
1597
+ static final class BackgroundRunnerWorkConfig {
1598
+
1599
+ final String label;
1600
+ final String src;
1601
+ final String event;
1602
+ final boolean autoStart;
1603
+ final boolean repeat;
1604
+ final int interval;
1605
+
1606
+ BackgroundRunnerWorkConfig(
1607
+ final String label,
1608
+ final String src,
1609
+ final String event,
1610
+ final boolean autoStart,
1611
+ final boolean repeat,
1612
+ final int interval
1613
+ ) {
1614
+ this.label = label;
1615
+ this.src = src;
1616
+ this.event = event;
1617
+ this.autoStart = autoStart;
1618
+ this.repeat = repeat;
1619
+ this.interval = interval;
1620
+ }
1621
+ }
1622
+
1623
+ static BackgroundRunnerWorkConfig getBackgroundRunnerWorkConfigFromConfig(final String configJson) {
1624
+ if (configJson == null || configJson.trim().isEmpty()) {
1625
+ return null;
1626
+ }
1627
+
1628
+ try {
1629
+ final JSONObject config = new JSONObject(configJson);
1630
+ final JSONObject plugins = config.optJSONObject("plugins");
1631
+ if (plugins == null) {
1632
+ return null;
1633
+ }
1634
+
1635
+ final JSONObject backgroundRunner = plugins.optJSONObject(BACKGROUND_RUNNER_CONFIG_KEY);
1636
+ if (backgroundRunner == null) {
1637
+ return null;
1638
+ }
1639
+
1640
+ final String label = backgroundRunner.optString("label", "").trim();
1641
+ if (label.isEmpty()) {
1642
+ return null;
1643
+ }
1644
+
1645
+ final String src = backgroundRunner.optString("src", "").trim();
1646
+ final String event = backgroundRunner.optString("event", "").trim();
1647
+ return new BackgroundRunnerWorkConfig(
1648
+ label,
1649
+ src,
1650
+ event,
1651
+ backgroundRunner.optBoolean("autoStart", false),
1652
+ backgroundRunner.optBoolean("repeat", false),
1653
+ backgroundRunner.optInt("interval", 0)
1654
+ );
1655
+ } catch (JSONException ignored) {
1656
+ return null;
1657
+ }
1658
+ }
1659
+
1660
+ static String getBackgroundRunnerLabelFromConfig(final String configJson) {
1661
+ final BackgroundRunnerWorkConfig config = getBackgroundRunnerWorkConfigFromConfig(configJson);
1662
+ return config == null ? null : config.label;
1663
+ }
1664
+
1665
+ private String readAssetAsString(final String assetPath) throws IOException {
1666
+ final StringBuilder buffer = new StringBuilder();
1667
+ try (
1668
+ final BufferedReader reader = new BufferedReader(
1669
+ new InputStreamReader(this.context().getAssets().open(assetPath), StandardCharsets.UTF_8)
1670
+ )
1671
+ ) {
1672
+ String line;
1673
+ while ((line = reader.readLine()) != null) {
1674
+ buffer.append(line).append('\n');
1675
+ }
1676
+ }
1677
+ return buffer.toString();
1678
+ }
1679
+
1680
+ private void copyFileAtomically(final File source, final File dest) throws IOException {
1681
+ final File parent = dest.getParentFile();
1682
+ if (parent != null && !parent.exists() && !parent.mkdirs()) {
1683
+ throw new IOException("Failed to create parent directory: " + parent.getAbsolutePath());
1684
+ }
1685
+
1686
+ final File tempFile = File.createTempFile("capgo-", ".tmp", parent);
1687
+ try {
1688
+ try (
1689
+ final FileInputStream input = new FileInputStream(source);
1690
+ final FileOutputStream output = new FileOutputStream(tempFile)
1691
+ ) {
1692
+ final byte[] buffer = new byte[CryptoCipher.copyBufferBytes()];
1693
+ int length;
1694
+ while ((length = input.read(buffer)) != -1) {
1695
+ output.write(buffer, 0, length);
1696
+ }
1697
+ }
1698
+ CryptoCipher.replaceFile(tempFile, dest);
1699
+ } finally {
1700
+ if (tempFile.exists()) {
1701
+ tempFile.delete();
1702
+ }
1703
+ }
1704
+ }
1705
+
1706
+ private void syncBackgroundRunnerScriptFromBundle(final File bundle, final BackgroundRunnerWorkConfig config) {
1707
+ if (this.context() == null || bundle == null || config == null || config.src == null || config.src.isEmpty()) {
1708
+ return;
1709
+ }
1710
+
1711
+ if (bundle.getPath().endsWith("/public") || "public".equals(bundle.getName())) {
1712
+ return;
1713
+ }
1714
+
1715
+ try {
1716
+ final File source = resolvePathInsideDirectory(bundle, config.src);
1717
+ if (!source.isFile()) {
1718
+ return;
1719
+ }
1720
+
1721
+ final File publicDir = new File(this.context().getFilesDir(), "public");
1722
+ final File dest = resolvePathInsideDirectory(publicDir, config.src);
1723
+ this.copyFileAtomically(source, dest);
1724
+ logger.info("Synced Background Runner script into native public storage before bundle switch.");
1725
+ logger.debug("Background Runner script path: " + dest.getAbsolutePath());
1726
+ } catch (Exception e) {
1727
+ logger.debug("Background Runner script sync skipped: " + e.getMessage());
1728
+ }
1729
+ }
1730
+
1731
+ private void resetBackgroundRunnerWorkForBundleSwitch(final File bundle) {
1732
+ if (this.context() == null) {
1733
+ return;
1734
+ }
1735
+
1736
+ final BackgroundRunnerWorkConfig config;
1737
+ try {
1738
+ config = getBackgroundRunnerWorkConfigFromConfig(this.readAssetAsString(CAPACITOR_CONFIG_ASSET));
1739
+ } catch (IOException ignored) {
1740
+ return;
1741
+ }
1742
+
1743
+ if (config == null) {
1744
+ return;
1745
+ }
1746
+
1747
+ try {
1748
+ final WorkManager workManager = WorkManager.getInstance(this.context().getApplicationContext());
1749
+ workManager.cancelUniqueWork(config.label);
1750
+ workManager.cancelAllWorkByTag(config.label);
1751
+ logger.info("Cancelled Background Runner work before bundle switch.");
1752
+ logger.debug("Background Runner label: " + config.label);
1753
+ } catch (Exception e) {
1754
+ logger.warn("Failed to cancel Background Runner work before bundle switch.");
1755
+ logger.debug("Background Runner cancellation error: " + e.getMessage());
1756
+ }
1757
+
1758
+ this.syncBackgroundRunnerScriptFromBundle(bundle, config);
1759
+ this.rescheduleBackgroundRunnerWork(config);
1760
+ }
1761
+
1762
+ private void rescheduleBackgroundRunnerWork(final BackgroundRunnerWorkConfig config) {
1763
+ if (!config.autoStart || config.interval <= 0 || config.src.isEmpty()) {
1764
+ return;
1765
+ }
1766
+
1767
+ try {
651
1768
  @SuppressWarnings("unchecked")
652
1769
  final Class<? extends ListenableWorker> workerClass = (Class<? extends ListenableWorker>) Class.forName(
653
1770
  BACKGROUND_RUNNER_WORKER_CLASS
654
1771
  );
655
- final Data data = new Data.Builder()
656
- .putString("label", config.label)
657
- .putString("src", config.src)
658
- .putString("event", config.event)
1772
+ final Data data = new Data.Builder()
1773
+ .putString("label", config.label)
1774
+ .putString("src", config.src)
1775
+ .putString("event", config.event)
1776
+ .build();
1777
+ final Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
1778
+ final WorkManager workManager = WorkManager.getInstance(this.context().getApplicationContext());
1779
+
1780
+ if (!config.repeat) {
1781
+ final OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(workerClass)
1782
+ .setInitialDelay(config.interval, TimeUnit.MINUTES)
1783
+ .setInputData(data)
1784
+ .addTag(config.label)
1785
+ .setConstraints(constraints)
1786
+ .build();
1787
+ workManager.enqueueUniqueWork(config.label, ExistingWorkPolicy.REPLACE, work);
1788
+ } else {
1789
+ final PeriodicWorkRequest work = new PeriodicWorkRequest.Builder(workerClass, config.interval, TimeUnit.MINUTES)
1790
+ .setInitialDelay(config.interval, TimeUnit.MINUTES)
1791
+ .setInputData(data)
1792
+ .addTag(config.label)
1793
+ .setConstraints(constraints)
1794
+ .build();
1795
+ workManager.enqueueUniquePeriodicWork(config.label, ExistingPeriodicWorkPolicy.UPDATE, work);
1796
+ }
1797
+
1798
+ logger.info("Rescheduled Background Runner work after bundle switch.");
1799
+ } catch (ClassNotFoundException ignored) {
1800
+ logger.debug("Background Runner plugin not installed, skipping reschedule.");
1801
+ } catch (Exception e) {
1802
+ logger.warn("Failed to reschedule Background Runner work after bundle switch.");
1803
+ logger.debug("Background Runner reschedule error: " + e.getMessage());
1804
+ }
1805
+ }
1806
+
1807
+ private boolean hasStoredBundleInfo(final String id) {
1808
+ return (
1809
+ id != null &&
1810
+ !id.isEmpty() &&
1811
+ !BundleInfo.ID_BUILTIN.equals(id) &&
1812
+ !BundleInfo.VERSION_UNKNOWN.equals(id) &&
1813
+ this.prefs.contains(id + INFO_SUFFIX)
1814
+ );
1815
+ }
1816
+
1817
+ private void runDownloadGate() throws IOException {
1818
+ if (this.downloadGate == null) {
1819
+ return;
1820
+ }
1821
+ try {
1822
+ this.downloadGate.run();
1823
+ } catch (final RuntimeException e) {
1824
+ throw new IOException(e.getMessage() == null ? "Download gate failed" : e.getMessage(), e);
1825
+ }
1826
+ }
1827
+
1828
+ private boolean runDownloadGateQuiet() {
1829
+ try {
1830
+ this.runDownloadGate();
1831
+ return true;
1832
+ } catch (final IOException e) {
1833
+ logger.error("Download blocked by cleanup gate: " + e.getMessage());
1834
+ return false;
1835
+ }
1836
+ }
1837
+
1838
+ public void downloadBackground(
1839
+ final String url,
1840
+ final String version,
1841
+ final String sessionKey,
1842
+ final String checksum,
1843
+ final JSONArray manifest
1844
+ ) {
1845
+ downloadBackground(url, version, sessionKey, checksum, manifest, true);
1846
+ }
1847
+
1848
+ public String downloadBackground(
1849
+ final String url,
1850
+ final String version,
1851
+ final String sessionKey,
1852
+ final String checksum,
1853
+ final JSONArray manifest,
1854
+ final boolean setNext
1855
+ ) {
1856
+ try {
1857
+ this.requireSessionKeyForEncryptedUpdate(sessionKey);
1858
+ if (manifest == null) {
1859
+ this.requireBundleChecksum(checksum);
1860
+ }
1861
+ } catch (final IOException e) {
1862
+ logger.error("Download blocked: " + e.getMessage());
1863
+ return null;
1864
+ }
1865
+ if (!this.runDownloadGateQuiet()) {
1866
+ return null;
1867
+ }
1868
+ final String id = this.randomString();
1869
+
1870
+ // Check if version is already downloading, but allow retry if previous download failed
1871
+ if (this.context() != null && DownloadWorkerManager.isVersionDownloading(this.context(), version)) {
1872
+ // Check if there's an existing bundle with error status that we can retry
1873
+ BundleInfo existingBundle = this.getBundleInfoByName(version);
1874
+ if (existingBundle != null && existingBundle.isErrorStatus()) {
1875
+ // Cancel the failed download and allow retry
1876
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), version)) {
1877
+ logger.error("Failed to cancel previous download before retry");
1878
+ return null;
1879
+ }
1880
+ logger.info("Retrying failed download for version: " + version);
1881
+ } else if (shouldRestartOrphanedDownload(observedDownloadVersions.contains(version))) {
1882
+ // Left over from a killed process: nothing would finish it or release the launch, so start over.
1883
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), version)) {
1884
+ logger.error("Failed to cancel orphaned download before restarting it");
1885
+ return null;
1886
+ }
1887
+ BundleInfo orphanedBundle = null;
1888
+ for (final BundleInfo info : this.list(true)) {
1889
+ if (info != null && info.getStatus() == BundleStatus.DOWNLOADING && version.equals(info.getVersionName())) {
1890
+ orphanedBundle = info;
1891
+ break;
1892
+ }
1893
+ }
1894
+ if (orphanedBundle != null) {
1895
+ this.cleanupManifestStagingAfterDownloadCancelled(orphanedBundle.getId());
1896
+ this.saveBundleInfo(orphanedBundle.getId(), orphanedBundle.setStatus(BundleStatus.ERROR));
1897
+ }
1898
+ logger.info("Restarting download orphaned by a previous process for version: " + version);
1899
+ } else {
1900
+ logger.info("Version already downloading: " + version);
1901
+ return null;
1902
+ }
1903
+ }
1904
+
1905
+ saveBundleInfo(id, new BundleInfo(id, version, BundleStatus.DOWNLOADING, new Date(System.currentTimeMillis()), ""));
1906
+ this.notifyDownload(id, 0);
1907
+ this.notifyDownload(id, 5);
1908
+
1909
+ final String dest = manifest != null ? this.manifestStagingDest() : this.randomString();
1910
+ this.download(id, url, dest, version, sessionKey, checksum, manifest, setNext);
1911
+ return id;
1912
+ }
1913
+
1914
+ public BundleInfo download(final String url, final String version, final String sessionKey, final String checksum) throws IOException {
1915
+ this.requireSessionKeyForEncryptedUpdate(sessionKey);
1916
+ this.requireBundleChecksum(checksum);
1917
+ this.runDownloadGate();
1918
+ // Check for existing bundle with same version and clean up if in error state
1919
+ BundleInfo existingBundle = this.getBundleInfoByName(version);
1920
+ if (existingBundle != null && (existingBundle.isErrorStatus() || existingBundle.isDeleted() || existingBundle.isDeleting())) {
1921
+ logger.info("Found existing failed bundle for version " + version + ", deleting before retry");
1922
+ if (!Boolean.TRUE.equals(this.delete(existingBundle.getId(), true))) {
1923
+ throw new IOException("Failed to delete existing bundle before retry");
1924
+ }
1925
+ }
1926
+
1927
+ final String id = this.randomString();
1928
+ saveBundleInfo(id, new BundleInfo(id, version, BundleStatus.DOWNLOADING, new Date(System.currentTimeMillis()), ""));
1929
+ this.notifyDownload(id, 0);
1930
+ this.notifyDownload(id, 5);
1931
+ final String dest = this.randomString();
1932
+
1933
+ // Create a CompletableFuture to track download completion
1934
+ CompletableFuture<BundleInfo> downloadFuture = new CompletableFuture<>();
1935
+ downloadFutures.put(id, downloadFuture);
1936
+
1937
+ // Start the download
1938
+ this.download(id, url, dest, version, sessionKey, checksum, null, false);
1939
+
1940
+ // Wait for completion without timeout
1941
+ try {
1942
+ BundleInfo result = downloadFuture.get();
1943
+ if (result.isErrorStatus()) {
1944
+ // The download observer already emitted downloadFailed and its stats.
1945
+ throw new ReportedDownloadFailureException("Download failed with status: " + result.getStatus());
1946
+ }
1947
+ return result;
1948
+ } catch (Exception e) {
1949
+ // Clean up on failure
1950
+ downloadFutures.remove(id);
1951
+ logger.error("Error waiting for download");
1952
+ logger.debug("Error: " + e.getMessage());
1953
+ BundleInfo errorBundle = new BundleInfo(id, version, BundleStatus.ERROR, new Date(System.currentTimeMillis()), "");
1954
+ saveBundleInfo(id, errorBundle);
1955
+ if (e instanceof IOException) {
1956
+ throw (IOException) e;
1957
+ }
1958
+ throw new IOException("Error waiting for download: " + e.getMessage(), e);
1959
+ }
1960
+ }
1961
+
1962
+ public BundleInfo downloadManifest(
1963
+ final String url,
1964
+ final String version,
1965
+ final String sessionKey,
1966
+ final String checksum,
1967
+ final JSONArray manifest
1968
+ ) throws IOException {
1969
+ this.requireSessionKeyForEncryptedUpdate(sessionKey);
1970
+ this.runDownloadGate();
1971
+ if (manifest == null) {
1972
+ return download(url, version, sessionKey, checksum);
1973
+ }
1974
+
1975
+ // Check for existing bundle with same version and clean up if in error state
1976
+ BundleInfo existingBundle = this.getBundleInfoByName(version);
1977
+ if (existingBundle != null && (existingBundle.isErrorStatus() || existingBundle.isDeleted() || existingBundle.isDeleting())) {
1978
+ logger.info("Found existing failed bundle for version " + version + ", deleting before retry");
1979
+ if (!Boolean.TRUE.equals(this.delete(existingBundle.getId(), true))) {
1980
+ throw new IOException("Failed to delete existing bundle before retry");
1981
+ }
1982
+ }
1983
+
1984
+ final String id = this.randomString();
1985
+ saveBundleInfo(id, new BundleInfo(id, version, BundleStatus.DOWNLOADING, new Date(System.currentTimeMillis()), ""));
1986
+ this.notifyDownload(id, 0);
1987
+ this.notifyDownload(id, 5);
1988
+ final String dest = this.manifestStagingDest();
1989
+
1990
+ // Create a CompletableFuture to track download completion
1991
+ CompletableFuture<BundleInfo> downloadFuture = new CompletableFuture<>();
1992
+ downloadFutures.put(id, downloadFuture);
1993
+
1994
+ // Start the download
1995
+ this.download(id, url, dest, version, sessionKey, checksum, manifest, false);
1996
+
1997
+ // Wait for completion without timeout
1998
+ try {
1999
+ BundleInfo result = downloadFuture.get();
2000
+ if (result.isErrorStatus()) {
2001
+ // The download observer already emitted downloadFailed and its stats.
2002
+ throw new ReportedDownloadFailureException("Download failed with status: " + result.getStatus());
2003
+ }
2004
+ return result;
2005
+ } catch (Exception e) {
2006
+ // Clean up on failure
2007
+ downloadFutures.remove(id);
2008
+ logger.error("Error waiting for download");
2009
+ logger.debug("Error: " + e.getMessage());
2010
+ BundleInfo errorBundle = new BundleInfo(id, version, BundleStatus.ERROR, new Date(System.currentTimeMillis()), "");
2011
+ saveBundleInfo(id, errorBundle);
2012
+ if (e instanceof IOException) {
2013
+ throw (IOException) e;
2014
+ }
2015
+ throw new IOException("Error waiting for download: " + e.getMessage(), e);
2016
+ }
2017
+ }
2018
+
2019
+ public List<BundleInfo> list(boolean rawList) {
2020
+ if (!rawList) {
2021
+ final List<BundleInfo> res = new ArrayList<>();
2022
+ final File destHot = new File(this.documentsDir, bundleDirectory);
2023
+ logger.debug("list File : " + destHot.getPath());
2024
+ if (destHot.exists()) {
2025
+ for (final File i : Objects.requireNonNull(destHot.listFiles())) {
2026
+ final String id = i.getName();
2027
+ res.add(this.getBundleInfo(id));
2028
+ }
2029
+ } else {
2030
+ logger.info("No versions available to list" + destHot);
2031
+ }
2032
+ return res;
2033
+ } else {
2034
+ final List<BundleInfo> res = new ArrayList<>();
2035
+ for (String value : this.prefs.getAll().keySet()) {
2036
+ if (!value.matches("^[0-9A-Za-z]{10}_info$")) {
2037
+ continue;
2038
+ }
2039
+
2040
+ res.add(this.getBundleInfo(value.split("_")[0]));
2041
+ }
2042
+ return res;
2043
+ }
2044
+ }
2045
+
2046
+ public Boolean delete(final String id, final Boolean removeInfo) throws IOException {
2047
+ return this.delete(id, removeInfo, true);
2048
+ }
2049
+
2050
+ public Boolean delete(final String id, final Boolean removeInfo, final boolean cancelActiveDownload) throws IOException {
2051
+ synchronized (this.deleteLock) {
2052
+ final File bundle;
2053
+ try {
2054
+ bundle = this.getBundleDirectory(id);
2055
+ } catch (IOException e) {
2056
+ logger.error("Cannot delete bundle with invalid id");
2057
+ logger.debug("Bundle ID: " + id + ", Error: " + e.getMessage());
2058
+ return false;
2059
+ }
2060
+ final BundleInfo deleted = this.getBundleInfo(id);
2061
+ if (deleted.isBuiltin() || this.getCurrentBundleId().equals(id)) {
2062
+ logger.error("Cannot delete current or builtin bundle");
2063
+ logger.debug("Bundle ID: " + id);
2064
+ return false;
2065
+ }
2066
+ final BundleInfo previewFallback = this.getPreviewFallbackBundle();
2067
+ if (
2068
+ previewFallback != null &&
2069
+ !previewFallback.isDeleted() &&
2070
+ !previewFallback.isErrorStatus() &&
2071
+ !previewFallback.isDeleting() &&
2072
+ previewFallback.getId().equals(id)
2073
+ ) {
2074
+ logger.error("Cannot delete the preview fallback bundle");
2075
+ logger.debug("Bundle ID: " + id);
2076
+ return false;
2077
+ }
2078
+ final BundleInfo next = this.getNextBundle();
2079
+ if (next != null && !next.isDeleted() && !next.isErrorStatus() && !next.isDeleting() && next.getId().equals(id)) {
2080
+ logger.error("Cannot delete the next bundle");
2081
+ logger.debug("Bundle ID: " + id);
2082
+ return false;
2083
+ }
2084
+
2085
+ final boolean hadRegistry = this.hasStoredBundleInfo(id);
2086
+ final boolean hadFolder = bundle.exists();
2087
+ if (!hadRegistry && !hadFolder) {
2088
+ logger.error("Cannot delete unknown bundle");
2089
+ logger.debug("Bundle ID: " + id);
2090
+ return false;
2091
+ }
2092
+
2093
+ // Persist DELETING before touching disk so kill/OOM can resume on next launch.
2094
+ if (!deleted.isDeleting()) {
2095
+ if (!this.saveBundleInfo(id, deleted.setStatus(BundleStatus.DELETING))) {
2096
+ logger.error("Failed to persist DELETING marker, aborting disk delete");
2097
+ logger.debug("Bundle ID: " + id);
2098
+ return false;
2099
+ }
2100
+ }
2101
+
2102
+ // Cancel download for this version if active
2103
+ if (cancelActiveDownload && this.context() != null) {
2104
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), deleted.getVersionName())) {
2105
+ logger.error("Failed to cancel active download before delete");
2106
+ return false;
2107
+ }
2108
+ }
2109
+
2110
+ if (bundle.exists()) {
2111
+ try {
2112
+ this.deleteDirectory(bundle);
2113
+ } catch (final IOException e) {
2114
+ logger.error("Failed to delete bundle folder, will retry later");
2115
+ logger.debug("Bundle ID: " + id + ", Error: " + e.getMessage());
2116
+ return false;
2117
+ }
2118
+ }
2119
+
2120
+ // Only drop registry after the folder is confirmed gone.
2121
+ if (bundle.exists()) {
2122
+ logger.error("Bundle folder still present after delete, will retry later");
2123
+ logger.debug("Bundle ID: " + id);
2124
+ return false;
2125
+ }
2126
+
2127
+ final boolean finalized;
2128
+ if (Boolean.FALSE.equals(removeInfo)) {
2129
+ finalized = this.saveBundleInfo(id, deleted.setStatus(BundleStatus.DELETED));
2130
+ } else {
2131
+ finalized = this.saveBundleInfo(id, null);
2132
+ }
2133
+ if (!finalized) {
2134
+ logger.error("Failed to finalize delete registry update, will retry later");
2135
+ logger.debug("Bundle ID: " + id);
2136
+ return false;
2137
+ }
2138
+ this.sendStats("delete", deleted.getVersionName());
2139
+ this.dequeuePendingDelete(id);
2140
+ logger.info("Bundle deleted and confirmed gone");
2141
+ logger.debug("Bundle ID: " + id);
2142
+ return true;
2143
+ }
2144
+ }
2145
+
2146
+ public Boolean delete(final String id) {
2147
+ try {
2148
+ return this.delete(id, true);
2149
+ } catch (IOException e) {
2150
+ e.printStackTrace();
2151
+ logger.info("Failed to delete bundle (" + id + ")" + "\nError:\n" + e.toString());
2152
+ return false;
2153
+ }
2154
+ }
2155
+
2156
+ /**
2157
+ * Resume incomplete deletes one-by-one. Safe across app kill / OOM because
2158
+ * delete() marks DELETING before disk work and only clears registry after confirm.
2159
+ */
2160
+ public void drainPendingDeletes() {
2161
+ final LinkedHashSet<String> pendingIds = new LinkedHashSet<>();
2162
+ for (final BundleInfo info : this.list(true)) {
2163
+ if (info != null && info.isDeleting() && info.getId() != null && !info.getId().isEmpty()) {
2164
+ pendingIds.add(info.getId());
2165
+ }
2166
+ }
2167
+ pendingIds.addAll(this.getPendingDeleteIds());
2168
+ for (final String id : pendingIds) {
2169
+ try {
2170
+ logger.info("Resuming pending delete for bundle: " + id);
2171
+ if (Boolean.TRUE.equals(this.delete(id, true))) {
2172
+ this.dequeuePendingDelete(id);
2173
+ }
2174
+ } catch (final Exception e) {
2175
+ logger.error("Pending delete failed, will retry next launch");
2176
+ logger.debug("Bundle ID: " + id + ", Error: " + e.getMessage());
2177
+ }
2178
+ try {
2179
+ Thread.sleep(DELETE_PACE_MS);
2180
+ } catch (final InterruptedException ie) {
2181
+ Thread.currentThread().interrupt();
2182
+ return;
2183
+ }
2184
+ }
2185
+ }
2186
+
2187
+ private Set<String> getPendingDeleteIds() {
2188
+ final Set<String> ids = new LinkedHashSet<>();
2189
+ if (this.prefs == null) {
2190
+ return ids;
2191
+ }
2192
+ final String raw = this.prefs.getString(PENDING_DELETE_IDS, "");
2193
+ if (raw == null || raw.isEmpty()) {
2194
+ return ids;
2195
+ }
2196
+ for (final String part : raw.split(",")) {
2197
+ if (part != null && !part.isEmpty()) {
2198
+ ids.add(part);
2199
+ }
2200
+ }
2201
+ return ids;
2202
+ }
2203
+
2204
+ private void enqueuePendingDelete(final String id) {
2205
+ if (id == null || id.isEmpty() || this.editor == null || this.prefs == null) {
2206
+ return;
2207
+ }
2208
+ final Set<String> ids = this.getPendingDeleteIds();
2209
+ if (!ids.add(id)) {
2210
+ return;
2211
+ }
2212
+ this.editor.putString(PENDING_DELETE_IDS, String.join(",", ids));
2213
+ this.editor.commit();
2214
+ }
2215
+
2216
+ private void dequeuePendingDelete(final String id) {
2217
+ if (id == null || id.isEmpty() || this.editor == null || this.prefs == null) {
2218
+ return;
2219
+ }
2220
+ final Set<String> ids = this.getPendingDeleteIds();
2221
+ if (!ids.remove(id)) {
2222
+ return;
2223
+ }
2224
+ if (ids.isEmpty()) {
2225
+ this.editor.remove(PENDING_DELETE_IDS);
2226
+ } else {
2227
+ this.editor.putString(PENDING_DELETE_IDS, String.join(",", ids));
2228
+ }
2229
+ this.editor.commit();
2230
+ }
2231
+
2232
+ private File getBundleDirectory(final String id) throws IOException {
2233
+ return resolveBundleDirectory(this.documentsDir, id);
2234
+ }
2235
+
2236
+ private boolean bundleExists(final String id) {
2237
+ final File bundle;
2238
+ try {
2239
+ bundle = this.getBundleDirectory(id);
2240
+ } catch (IOException e) {
2241
+ return false;
2242
+ }
2243
+ final BundleInfo bundleInfo = this.getBundleInfo(id);
2244
+ return (
2245
+ bundle.isDirectory() &&
2246
+ bundle.exists() &&
2247
+ new File(bundle.getPath(), "/index.html").exists() &&
2248
+ !bundleInfo.isDeleted() &&
2249
+ !bundleInfo.isDeleting()
2250
+ );
2251
+ }
2252
+
2253
+ static final class ResetState {
2254
+
2255
+ final String currentBundlePath;
2256
+ final String fallbackBundleId;
2257
+ final String nextBundleId;
2258
+
2259
+ ResetState(final String currentBundlePath, final String fallbackBundleId, final String nextBundleId) {
2260
+ this.currentBundlePath = currentBundlePath;
2261
+ this.fallbackBundleId = fallbackBundleId;
2262
+ this.nextBundleId = nextBundleId;
2263
+ }
2264
+ }
2265
+
2266
+ ResetState captureResetState() {
2267
+ return new ResetState(
2268
+ this.getCurrentBundlePath(),
2269
+ this.prefs.getString(FALLBACK_VERSION, BundleInfo.ID_BUILTIN),
2270
+ this.prefs.getString(NEXT_VERSION, null)
2271
+ );
2272
+ }
2273
+
2274
+ void restoreResetState(final ResetState state) {
2275
+ final String currentBundlePath =
2276
+ state.currentBundlePath == null || state.currentBundlePath.trim().isEmpty() ? "public" : state.currentBundlePath;
2277
+ final String fallbackBundleId =
2278
+ state.fallbackBundleId == null || state.fallbackBundleId.isEmpty() ? BundleInfo.ID_BUILTIN : state.fallbackBundleId;
2279
+
2280
+ this.editor.putString(this.CAP_SERVER_PATH, currentBundlePath);
2281
+ this.editor.putString(FALLBACK_VERSION, fallbackBundleId);
2282
+ if (state.nextBundleId == null || state.nextBundleId.isEmpty()) {
2283
+ this.editor.remove(NEXT_VERSION);
2284
+ } else {
2285
+ this.editor.putString(NEXT_VERSION, state.nextBundleId);
2286
+ }
2287
+ this.editor.commit();
2288
+ }
2289
+
2290
+ void prepareResetStateForTransition() {
2291
+ this.setCurrentBundle(new File("public"));
2292
+ this.setFallbackBundle(null);
2293
+ this.setNextBundle(null);
2294
+ }
2295
+
2296
+ void finalizeResetTransition(final String previousBundleName, final boolean internal) {
2297
+ if (this.context() != null) {
2298
+ DownloadWorkerManager.cancelAllDownloads(this.context());
2299
+ }
2300
+ if (!internal) {
2301
+ this.sendStats("reset", this.getCurrentBundle().getVersionName(), previousBundleName);
2302
+ }
2303
+ }
2304
+
2305
+ boolean canSet(final BundleInfo bundle) {
2306
+ return bundle != null && (bundle.isBuiltin() || this.bundleExists(bundle.getId()));
2307
+ }
2308
+
2309
+ public Boolean set(final BundleInfo bundle) {
2310
+ return this.set(bundle.getId());
2311
+ }
2312
+
2313
+ public Boolean set(final String id) {
2314
+ final BundleInfo newBundle = this.getBundleInfo(id);
2315
+ if (newBundle.isBuiltin()) {
2316
+ this.reset();
2317
+ return true;
2318
+ }
2319
+ final File bundle;
2320
+ try {
2321
+ bundle = this.getBundleDirectory(id);
2322
+ } catch (IOException e) {
2323
+ logger.error("Invalid bundle id");
2324
+ logger.debug("Bundle ID: " + id + ", Error: " + e.getMessage());
2325
+ this.setBundleStatus(id, BundleStatus.ERROR);
2326
+ this.sendStats("set_fail", newBundle.getVersionName());
2327
+ return false;
2328
+ }
2329
+ logger.info("Setting next active bundle: " + id);
2330
+ if (this.bundleExists(id)) {
2331
+ var currentBundleName = this.getCurrentBundle().getVersionName();
2332
+ this.setCurrentBundle(bundle);
2333
+ this.setBundleStatus(id, BundleStatus.PENDING);
2334
+ this.sendStats("set", newBundle.getVersionName(), currentBundleName);
2335
+ return true;
2336
+ }
2337
+ this.setBundleStatus(id, BundleStatus.ERROR);
2338
+ this.sendStats("set_fail", newBundle.getVersionName());
2339
+ return false;
2340
+ }
2341
+
2342
+ boolean stagePendingReload(final BundleInfo bundle) {
2343
+ if (bundle == null || bundle.isBuiltin() || !this.bundleExists(bundle.getId())) {
2344
+ return false;
2345
+ }
2346
+ try {
2347
+ this.setCurrentBundle(this.getBundleDirectory(bundle.getId()));
2348
+ return true;
2349
+ } catch (IOException e) {
2350
+ return false;
2351
+ }
2352
+ }
2353
+
2354
+ boolean stagePreviewFallbackReload(final BundleInfo bundle) {
2355
+ if (bundle == null || bundle.isErrorStatus()) {
2356
+ return false;
2357
+ }
2358
+ if (bundle.isBuiltin()) {
2359
+ this.setCurrentBundle(new File("public"));
2360
+ return true;
2361
+ }
2362
+ if (!this.bundleExists(bundle.getId())) {
2363
+ return false;
2364
+ }
2365
+ try {
2366
+ this.setCurrentBundle(this.getBundleDirectory(bundle.getId()));
2367
+ return true;
2368
+ } catch (IOException e) {
2369
+ return false;
2370
+ }
2371
+ }
2372
+
2373
+ void finalizePendingReload(final BundleInfo bundle, final String previousBundleName) {
2374
+ if (bundle == null || bundle.isBuiltin()) {
2375
+ return;
2376
+ }
2377
+ this.sendStats("set", bundle.getVersionName(), previousBundleName);
2378
+ }
2379
+
2380
+ @Deprecated
2381
+ public void autoReset() {
2382
+ this.autoReset(this.versionCode == null ? "" : this.versionCode);
2383
+ }
2384
+
2385
+ public void autoReset(final String currentNativeBuildVersion) {
2386
+ this.autoReset(currentNativeBuildVersion, true);
2387
+ }
2388
+
2389
+ public void autoReset(final String currentNativeBuildVersion, final boolean resetWhenNativeVersionChanged) {
2390
+ final BundleInfo currentBundle = this.getCurrentBundle();
2391
+ if (!currentBundle.isBuiltin() && !this.bundleExists(currentBundle.getId())) {
2392
+ logger.info("Folder at bundle path does not exist. Triggering reset.");
2393
+ this.reset();
2394
+ return;
2395
+ }
2396
+ String bundlePath = this.prefs.getString(this.CAP_SERVER_PATH, null);
2397
+ if (shouldResetForForeignBundle(bundlePath, currentBundle.isBuiltin(), this.hasStoredBundleInfo(currentBundle.getId()))) {
2398
+ logger.info("Current bundle id is not one of the bundle ids stored by this plugin. Triggering reset.");
2399
+ this.reset();
2400
+ return;
2401
+ }
2402
+ final String previousNativeBuildVersion = this.getStoredNativeBuildVersion();
2403
+ if (
2404
+ resetWhenNativeVersionChanged &&
2405
+ !previousNativeBuildVersion.isEmpty() &&
2406
+ currentNativeBuildVersion != null &&
2407
+ !currentNativeBuildVersion.isEmpty() &&
2408
+ !Objects.equals(previousNativeBuildVersion, currentNativeBuildVersion)
2409
+ ) {
2410
+ logger.info(
2411
+ "Stored native build version " +
2412
+ previousNativeBuildVersion +
2413
+ " does not match current native build version " +
2414
+ currentNativeBuildVersion +
2415
+ ". Triggering reset."
2416
+ );
2417
+ this.reset();
2418
+ }
2419
+ }
2420
+
2421
+ private String getStoredNativeBuildVersion() {
2422
+ if (this.prefs == null) {
2423
+ return "";
2424
+ }
2425
+ String previousNativeBuildVersion = this.prefs.getString("LatestNativeBuildVersion", "");
2426
+ if (previousNativeBuildVersion == null || previousNativeBuildVersion.isEmpty()) {
2427
+ previousNativeBuildVersion = this.prefs.getString("LatestVersionNative", "");
2428
+ }
2429
+ return previousNativeBuildVersion == null ? "" : previousNativeBuildVersion;
2430
+ }
2431
+
2432
+ public void reset() {
2433
+ this.reset(false);
2434
+ }
2435
+
2436
+ public void setSuccess(final BundleInfo bundle, Boolean autoDeletePrevious) {
2437
+ this.setBundleStatus(bundle.getId(), BundleStatus.SUCCESS);
2438
+ final BundleInfo fallback = this.getFallbackBundle();
2439
+ final BundleInfo previewFallback = this.getPreviewFallbackBundle();
2440
+ final boolean fallbackIsPreviewFallback = previewFallback != null && previewFallback.getId().equals(fallback.getId());
2441
+ logger.debug("Fallback bundle is: " + fallback);
2442
+ logger.info("Version successfully loaded: " + bundle.getVersionName());
2443
+ // Only attempt to delete when the fallback is a different bundle than the
2444
+ // currently loaded one. Otherwise we spam logs with "Cannot delete <id>"
2445
+ // because delete() protects the current bundle from removal.
2446
+ final String previousFallbackId = fallback.getId();
2447
+ final String previousFallbackVersion = fallback.getVersionName();
2448
+ final BundleInfo nextBundle = this.getNextBundle();
2449
+ final boolean previousIsNext =
2450
+ nextBundle != null &&
2451
+ previousFallbackId != null &&
2452
+ previousFallbackId.equals(nextBundle.getId()) &&
2453
+ !nextBundle.isDeleted() &&
2454
+ !nextBundle.isErrorStatus() &&
2455
+ !nextBundle.isDeleting();
2456
+ final boolean shouldDeletePrevious =
2457
+ Boolean.TRUE.equals(autoDeletePrevious) &&
2458
+ !fallback.isBuiltin() &&
2459
+ previousFallbackId != null &&
2460
+ !previousFallbackId.equals(bundle.getId()) &&
2461
+ !fallbackIsPreviewFallback &&
2462
+ !previousIsNext;
2463
+ if (shouldDeletePrevious) {
2464
+ if (!this.saveBundleInfo(previousFallbackId, fallback.setStatus(BundleStatus.DELETING))) {
2465
+ logger.error("Failed to persist DELETING for previous bundle; queueing durable retry");
2466
+ logger.debug("Bundle ID: " + previousFallbackId);
2467
+ this.enqueuePendingDelete(previousFallbackId);
2468
+ }
2469
+ }
2470
+ boolean deletePreviousAsync = shouldDeletePrevious;
2471
+ this.setFallbackBundle(bundle);
2472
+ if (deletePreviousAsync) {
2473
+ final String asyncPreviousFallbackId = previousFallbackId;
2474
+ final String asyncPreviousFallbackVersion = previousFallbackVersion;
2475
+ io.execute(() -> {
2476
+ if (this.context() != null) {
2477
+ if (!DownloadWorkerManager.cancelVersionDownloadAndAwait(this.context(), asyncPreviousFallbackVersion)) {
2478
+ logger.error("Failed to cancel previous version download before delete");
2479
+ return;
2480
+ }
2481
+ }
2482
+ try {
2483
+ final Boolean res = this.delete(asyncPreviousFallbackId, true, false);
2484
+ if (Boolean.TRUE.equals(res)) {
2485
+ logger.info("Deleted previous bundle: " + asyncPreviousFallbackVersion);
2486
+ } else {
2487
+ logger.debug("Previous bundle delete incomplete, will retry: " + asyncPreviousFallbackId);
2488
+ }
2489
+ } catch (final IOException e) {
2490
+ logger.error("Failed to delete previous bundle: " + asyncPreviousFallbackId + " " + e.getMessage());
2491
+ }
2492
+ });
2493
+ }
2494
+ }
2495
+
2496
+ public void setError(final BundleInfo bundle) {
2497
+ this.setBundleStatus(bundle.getId(), BundleStatus.ERROR);
2498
+ }
2499
+
2500
+ public void reset(final boolean internal) {
2501
+ logger.debug("reset: " + internal);
2502
+ final String currentBundleName = this.getCurrentBundle().getVersionName();
2503
+ this.prepareResetStateForTransition();
2504
+ this.finalizeResetTransition(currentBundleName, internal);
2505
+ }
2506
+
2507
+ private JSONObject createInfoObject() throws JSONException {
2508
+ return this.createInfoObject(null);
2509
+ }
2510
+
2511
+ private JSONObject createInfoObject(final String appIdOverride) throws JSONException {
2512
+ JSONObject json = new JSONObject();
2513
+ json.put("platform", "android");
2514
+ json.put("device_id", this.deviceID);
2515
+ json.put("app_id", appIdOverride == null || appIdOverride.trim().isEmpty() ? this.appId : appIdOverride);
2516
+ json.put("custom_id", this.customId);
2517
+ json.put("version_build", this.versionBuild);
2518
+ json.put("version_code", this.versionCode);
2519
+ json.put("version_os", this.versionOs);
2520
+ json.put("version_name", this.getCurrentBundle().getVersionName());
2521
+ json.put("plugin_version", this.pluginVersion);
2522
+ json.put("is_emulator", this.isEmulator());
2523
+ json.put("is_prod", this.isProd());
2524
+ json.put("install_source", this.getInstallSource());
2525
+ json.put("defaultChannel", this.defaultChannel);
2526
+
2527
+ // Add encryption key ID if encryption is enabled (use cached value)
2528
+ if (!this.cachedKeyId.isEmpty()) {
2529
+ json.put("key_id", this.cachedKeyId);
2530
+ }
2531
+
2532
+ return json;
2533
+ }
2534
+
2535
+ private static final class RemoteBlockResult {
2536
+
2537
+ final boolean blocked;
2538
+ final String error;
2539
+ final String message;
2540
+
2541
+ RemoteBlockResult(final boolean blocked, final String error, final String message) {
2542
+ this.blocked = blocked;
2543
+ this.error = error;
2544
+ this.message = message;
2545
+ }
2546
+ }
2547
+
2548
+ /**
2549
+ * Handle HTTP 429 responses by honouring Retry-After / rateLimitResetAt.
2550
+ * All 429s use the same temporary client block — no sticky latch until restart.
2551
+ */
2552
+ private RemoteBlockResult checkAndHandleRateLimitResponse(Response response, String responseData) {
2553
+ if (response == null || response.code() != 429) {
2554
+ return new RemoteBlockResult(false, "", "");
2555
+ }
2556
+
2557
+ final String parsedError = parseRemoteError(responseData);
2558
+ final String parsedMessage = parseRemoteMessage(responseData);
2559
+ final String errorCode = parsedError.isEmpty() ? "too_many_requests" : parsedError;
2560
+ final String message = parsedMessage.isEmpty() ? "Too many requests" : parsedMessage;
2561
+
2562
+ final long retryUntilMs = resolveRateLimitBlockedUntilMs(response, responseData);
2563
+ synchronized (rateLimitStateLock) {
2564
+ if (retryUntilMs > rateLimitBlockedUntilMs) {
2565
+ rateLimitBlockedUntilMs = retryUntilMs;
2566
+ rateLimitBlockedError = errorCode;
2567
+ rateLimitBlockedMessage = message;
2568
+ } else if (rateLimitBlockedUntilMs <= 0L) {
2569
+ rateLimitBlockedError = errorCode;
2570
+ rateLimitBlockedMessage = message;
2571
+ }
2572
+ }
2573
+
2574
+ // Claim last, and only when there is somewhere to send it, so a 429 burst with no
2575
+ // stats URL does not claim and release the latch once per response.
2576
+ if ("too_many_requests".equals(errorCode) && !this.previewSession && this.hasStatsUrl() && claimRateLimitStatistic()) {
2577
+ sendRateLimitStatistic();
2578
+ }
2579
+
2580
+ final long nowMs = System.currentTimeMillis();
2581
+ final long retryAfter = Math.max(0L, (Math.max(retryUntilMs, nowMs) - nowMs + 999L) / 1000L);
2582
+ logger.warn("Received 429 (" + errorCode + "). Honouring Retry-After: " + retryAfter + "s.");
2583
+ return new RemoteBlockResult(true, errorCode, message);
2584
+ }
2585
+
2586
+ private String parseRemoteError(final String responseData) {
2587
+ if (responseData == null || responseData.isEmpty()) {
2588
+ return "";
2589
+ }
2590
+ try {
2591
+ final JSONObject json = new JSONObject(responseData);
2592
+ return json.optString("error", "");
2593
+ } catch (JSONException ignored) {
2594
+ return "";
2595
+ }
2596
+ }
2597
+
2598
+ private String parseRemoteMessage(final String responseData) {
2599
+ if (responseData == null || responseData.isEmpty()) {
2600
+ return "";
2601
+ }
2602
+ try {
2603
+ final JSONObject json = new JSONObject(responseData);
2604
+ return json.optString("message", "");
2605
+ } catch (JSONException ignored) {
2606
+ return "";
2607
+ }
2608
+ }
2609
+
2610
+ private long resolveRateLimitBlockedUntilMs(final Response response, final String responseData) {
2611
+ final long nowMs = System.currentTimeMillis();
2612
+ final double candidate = rawRateLimitDeadlineMs(response, responseData, nowMs);
2613
+ // NaN and past deadlines mean "no client-side block"; anything further out is capped.
2614
+ if (!(candidate > nowMs)) {
2615
+ return 0L;
2616
+ }
2617
+ return (long) Math.min(candidate, (double) nowMs + MAX_RATE_LIMIT_WINDOW_MS);
2618
+ }
2619
+
2620
+ private double rawRateLimitDeadlineMs(final Response response, final String responseData, final long nowMs) {
2621
+ final String header = response.header("Retry-After");
2622
+ if (header != null) {
2623
+ try {
2624
+ final double seconds = Double.parseDouble(header.trim());
2625
+ if (seconds >= 0) {
2626
+ return nowMs + seconds * 1000d;
2627
+ }
2628
+ } catch (NumberFormatException ignored) {
2629
+ // Fall through to body fields
2630
+ }
2631
+ }
2632
+
2633
+ if (responseData != null && !responseData.isEmpty()) {
2634
+ try {
2635
+ final JSONObject json = new JSONObject(responseData);
2636
+ final JSONObject moreInfo = json.optJSONObject("moreInfo");
2637
+ if (moreInfo != null && moreInfo.has("retryAfterSeconds")) {
2638
+ final double retryAfter = moreInfo.getDouble("retryAfterSeconds");
2639
+ if (retryAfter >= 0) {
2640
+ return nowMs + retryAfter * 1000d;
2641
+ }
2642
+ } else if (json.has("retryAfterSeconds")) {
2643
+ final double retryAfter = json.getDouble("retryAfterSeconds");
2644
+ if (retryAfter >= 0) {
2645
+ return nowMs + retryAfter * 1000d;
2646
+ }
2647
+ }
2648
+ if (moreInfo != null && moreInfo.has("rateLimitResetAt")) {
2649
+ return moreInfo.getDouble("rateLimitResetAt");
2650
+ } else if (json.has("rateLimitResetAt")) {
2651
+ return json.getDouble("rateLimitResetAt");
2652
+ }
2653
+ } catch (JSONException ignored) {
2654
+ // No retry hint
2655
+ }
2656
+ }
2657
+
2658
+ // No retry hint — do not hold a client-side block; allow immediate retry to the worker
2659
+ return 0d;
2660
+ }
2661
+
2662
+ private static boolean claimRateLimitStatistic() {
2663
+ synchronized (rateLimitStateLock) {
2664
+ if (rateLimitStatisticSent) {
2665
+ return false;
2666
+ }
2667
+ rateLimitStatisticSent = true;
2668
+ return true;
2669
+ }
2670
+ }
2671
+
2672
+ /**
2673
+ * Give the claim back when the statistic never made it out, so a later 429 can retry it.
2674
+ */
2675
+ private static void releaseRateLimitStatisticClaim() {
2676
+ synchronized (rateLimitStateLock) {
2677
+ rateLimitStatisticSent = false;
2678
+ }
2679
+ }
2680
+
2681
+ private boolean hasStatsUrl() {
2682
+ final String url = this.statsUrl;
2683
+ return url != null && !url.isEmpty();
2684
+ }
2685
+
2686
+ private boolean isRemoteBlocked() {
2687
+ synchronized (rateLimitStateLock) {
2688
+ if (rateLimitBlockedUntilMs <= 0L) {
2689
+ return false;
2690
+ }
2691
+ if (System.currentTimeMillis() >= rateLimitBlockedUntilMs) {
2692
+ rateLimitBlockedUntilMs = 0L;
2693
+ return false;
2694
+ }
2695
+ return true;
2696
+ }
2697
+ }
2698
+
2699
+ private RemoteBlockResult remoteBlockedClientError() {
2700
+ synchronized (rateLimitStateLock) {
2701
+ return new RemoteBlockResult(true, rateLimitBlockedError, rateLimitBlockedMessage);
2702
+ }
2703
+ }
2704
+
2705
+ /**
2706
+ * Send a statistic about rate limiting.
2707
+ * Dispatched through OkHttp so no caller thread waits on the request.
2708
+ */
2709
+ private void sendRateLimitStatistic() {
2710
+ String statsUrl = this.statsUrl;
2711
+ if (statsUrl == null || statsUrl.isEmpty()) {
2712
+ // The URL was cleared after the claim was taken; nothing went out, so hand it back.
2713
+ releaseRateLimitStatisticClaim();
2714
+ return;
2715
+ }
2716
+
2717
+ try {
2718
+ BundleInfo current = this.getCurrentBundle();
2719
+ JSONObject json = this.createInfoObject();
2720
+ json.put("version_name", current.getVersionName());
2721
+ json.put("old_version_name", "");
2722
+ json.put("action", "rate_limit_reached");
2723
+
2724
+ Request request = new Request.Builder()
2725
+ .url(statsUrl)
2726
+ .post(RequestBody.create(json.toString(), MediaType.get("application/json")))
659
2727
  .build();
660
- final Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
661
- final WorkManager workManager = WorkManager.getInstance(this.context.getApplicationContext());
662
- if (!config.repeat) {
663
- final OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(workerClass)
664
- .setInitialDelay(config.interval, TimeUnit.MINUTES)
665
- .setInputData(data)
666
- .addTag(config.label)
667
- .setConstraints(constraints)
668
- .build();
669
- workManager.enqueueUniqueWork(config.label, ExistingWorkPolicy.REPLACE, work);
2728
+
2729
+ // User-Agent header is automatically added by DownloadService.sharedClient interceptor
2730
+ DownloadService.sharedClient.newCall(request).enqueue(
2731
+ new okhttp3.Callback() {
2732
+ @Override
2733
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
2734
+ releaseRateLimitStatisticClaim();
2735
+ logger.error("Failed to send rate limit statistic");
2736
+ logger.debug("Error: " + e.getMessage());
2737
+ }
2738
+
2739
+ @Override
2740
+ public void onResponse(@NonNull Call call, @NonNull Response response) {
2741
+ // The body is unused here; closing the Response closes it.
2742
+ try (response) {
2743
+ if (response.isSuccessful()) {
2744
+ logger.info("Rate limit statistic sent");
2745
+ } else {
2746
+ releaseRateLimitStatisticClaim();
2747
+ logger.error("Error sending rate limit statistic");
2748
+ logger.debug("Response code: " + response.code());
2749
+ }
2750
+ }
2751
+ }
2752
+ }
2753
+ );
2754
+ } catch (final Exception e) {
2755
+ releaseRateLimitStatisticClaim();
2756
+ logger.error("Failed to send rate limit statistic");
2757
+ logger.debug("Error: " + e.getMessage());
2758
+ }
2759
+ }
2760
+
2761
+ private void makeJsonRequest(String url, JSONObject jsonBody, Callback callback) {
2762
+ MediaType JSON = MediaType.get("application/json; charset=utf-8");
2763
+ RequestBody body = RequestBody.create(jsonBody.toString(), JSON);
2764
+
2765
+ Request request = new Request.Builder().url(url).post(body).build();
2766
+
2767
+ DownloadService.sharedClient.newCall(request).enqueue(
2768
+ new okhttp3.Callback() {
2769
+ @Override
2770
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
2771
+ Map<String, Object> retError = new HashMap<>();
2772
+ retError.put("message", "Request failed: " + e.getMessage());
2773
+ retError.put("error", "network_error");
2774
+ retError.put("kind", "failed");
2775
+ callback.callback(retError);
2776
+ }
2777
+
2778
+ @Override
2779
+ public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
2780
+ try (ResponseBody responseBody = response.body()) {
2781
+ final int statusCode = response.code();
2782
+ final String responseData = responseBody != null ? responseBody.string() : "";
2783
+ JSONObject jsonResponse = null;
2784
+ if (!responseData.isEmpty()) {
2785
+ try {
2786
+ jsonResponse = new JSONObject(responseData);
2787
+ } catch (JSONException ignored) {
2788
+ // Non-JSON responses are handled as response or parse errors below.
2789
+ }
2790
+ }
2791
+
2792
+ if (jsonResponse != null && (jsonResponse.has("error") || jsonResponse.has("kind"))) {
2793
+ if (statusCode == 429) {
2794
+ final RemoteBlockResult rateLimit = checkAndHandleRateLimitResponse(response, responseData);
2795
+ Map<String, Object> retError = new HashMap<>();
2796
+ retError.put(
2797
+ "error",
2798
+ rateLimit.error.isEmpty() ? jsonResponse.optString("error", "too_many_requests") : rateLimit.error
2799
+ );
2800
+ retError.put(
2801
+ "message",
2802
+ rateLimit.message.isEmpty() ? jsonResponse.optString("message", "Too many requests") : rateLimit.message
2803
+ );
2804
+ if (jsonResponse.has("kind") && !jsonResponse.isNull("kind")) {
2805
+ retError.put("kind", jsonResponse.getString("kind"));
2806
+ } else {
2807
+ retError.put("kind", "failed");
2808
+ }
2809
+ if (jsonResponse.has("version") && !jsonResponse.isNull("version")) {
2810
+ retError.put("version", jsonResponse.getString("version"));
2811
+ }
2812
+ retError.put("statusCode", statusCode);
2813
+ callback.callback(retError);
2814
+ return;
2815
+ }
2816
+ Map<String, Object> retError = new HashMap<>();
2817
+ if (jsonResponse.has("error") && !jsonResponse.isNull("error")) {
2818
+ retError.put("error", jsonResponse.getString("error"));
2819
+ }
2820
+ if (jsonResponse.has("kind") && !jsonResponse.isNull("kind")) {
2821
+ retError.put("kind", jsonResponse.getString("kind"));
2822
+ }
2823
+ if (jsonResponse.has("message") && !jsonResponse.isNull("message")) {
2824
+ retError.put("message", jsonResponse.getString("message"));
2825
+ } else {
2826
+ retError.put("message", "server did not provide a message");
2827
+ }
2828
+ if (jsonResponse.has("version") && !jsonResponse.isNull("version")) {
2829
+ retError.put("version", jsonResponse.getString("version"));
2830
+ }
2831
+ retError.put("statusCode", statusCode);
2832
+ callback.callback(retError);
2833
+ return;
2834
+ }
2835
+
2836
+ // Check for 429 rate limit without JSON body
2837
+ final RemoteBlockResult rateLimit = checkAndHandleRateLimitResponse(response, responseData);
2838
+ if (rateLimit.blocked) {
2839
+ Map<String, Object> retError = new HashMap<>();
2840
+ retError.put("message", rateLimit.message);
2841
+ retError.put("error", rateLimit.error);
2842
+ retError.put("kind", "failed");
2843
+ retError.put("statusCode", statusCode);
2844
+ callback.callback(retError);
2845
+ return;
2846
+ }
2847
+
2848
+ if (!response.isSuccessful()) {
2849
+ Map<String, Object> retError = new HashMap<>();
2850
+ retError.put("message", "Server error: " + response.code());
2851
+ retError.put("error", "response_error");
2852
+ retError.put("kind", "failed");
2853
+ retError.put("statusCode", statusCode);
2854
+ callback.callback(retError);
2855
+ return;
2856
+ }
2857
+
2858
+ if (jsonResponse == null) {
2859
+ throw new JSONException("Response is not a JSON object");
2860
+ }
2861
+
2862
+ Map<String, Object> ret = new HashMap<>();
2863
+ ret.put("statusCode", statusCode);
2864
+
2865
+ Iterator<String> keys = jsonResponse.keys();
2866
+ while (keys.hasNext()) {
2867
+ String key = keys.next();
2868
+ if (jsonResponse.has(key)) {
2869
+ if ("session_key".equals(key)) {
2870
+ ret.put("sessionKey", jsonResponse.get(key));
2871
+ } else {
2872
+ ret.put(key, jsonResponse.get(key));
2873
+ }
2874
+ }
2875
+ }
2876
+ callback.callback(ret);
2877
+ } catch (JSONException e) {
2878
+ Map<String, Object> retError = new HashMap<>();
2879
+ retError.put("message", "JSON parse error: " + e.getMessage());
2880
+ retError.put("error", "parse_error");
2881
+ retError.put("kind", "failed");
2882
+ callback.callback(retError);
2883
+ }
2884
+ }
2885
+ }
2886
+ );
2887
+ }
2888
+
2889
+ public void getLatest(final String updateUrl, final String channel, final Callback callback) {
2890
+ this.getLatest(updateUrl, channel, null, callback);
2891
+ }
2892
+
2893
+ public void getLatest(final String updateUrl, final String channel, final String appIdOverride, final Callback callback) {
2894
+ if (isRemoteBlocked()) {
2895
+ final RemoteBlockResult blocked = remoteBlockedClientError();
2896
+ logger.debug("Skipping getLatest due to remote block (" + blocked.error + ").");
2897
+ final Map<String, Object> retError = new HashMap<>();
2898
+ retError.put("message", blocked.message);
2899
+ retError.put("error", blocked.error);
2900
+ retError.put("kind", "failed");
2901
+ callback.callback(retError);
2902
+ return;
2903
+ }
2904
+ JSONObject json;
2905
+ try {
2906
+ json = this.createInfoObject(appIdOverride);
2907
+ if (channel != null && json != null) {
2908
+ json.put("defaultChannel", channel);
2909
+ }
2910
+ } catch (JSONException e) {
2911
+ logger.error("Error getting latest version");
2912
+ logger.debug("JSONException: " + e.getMessage());
2913
+ final Map<String, Object> retError = new HashMap<>();
2914
+ retError.put("message", "Cannot get info: " + e);
2915
+ retError.put("error", "json_error");
2916
+ callback.callback(retError);
2917
+ return;
2918
+ }
2919
+
2920
+ if (logger != null) {
2921
+ logger.info("Auto-update parameters: " + json);
2922
+ }
2923
+
2924
+ makeJsonRequest(updateUrl, json, callback);
2925
+ }
2926
+
2927
+ public void unsetChannel(
2928
+ final SharedPreferences.Editor editor,
2929
+ final String defaultChannelKey,
2930
+ final String configDefaultChannel,
2931
+ final boolean allowSetDefaultChannel,
2932
+ final Callback callback
2933
+ ) {
2934
+ if (!allowSetDefaultChannel) {
2935
+ logger.error("unsetChannel is disabled by allowSetDefaultChannel config");
2936
+ final Map<String, Object> retError = new HashMap<>();
2937
+ retError.put("message", "unsetChannel is disabled by configuration");
2938
+ retError.put("error", "disabled_by_config");
2939
+ callback.callback(retError);
2940
+ return;
2941
+ }
2942
+
2943
+ // Clear persisted defaultChannel and revert to config value
2944
+ editor.remove(defaultChannelKey);
2945
+ editor.apply();
2946
+ this.defaultChannel = configDefaultChannel;
2947
+ logger.info("Persisted defaultChannel cleared, reverted to config value: " + configDefaultChannel);
2948
+
2949
+ Map<String, Object> ret = new HashMap<>();
2950
+ ret.put("status", "ok");
2951
+ ret.put("message", "Channel override removed");
2952
+ callback.callback(ret);
2953
+ }
2954
+
2955
+ public void setChannel(
2956
+ final String channel,
2957
+ final SharedPreferences.Editor editor,
2958
+ final String defaultChannelKey,
2959
+ final boolean allowSetDefaultChannel,
2960
+ final Callback callback
2961
+ ) {
2962
+ this.setChannel(channel, editor, defaultChannelKey, allowSetDefaultChannel, "", callback);
2963
+ }
2964
+
2965
+ public void setChannel(
2966
+ final String channel,
2967
+ final SharedPreferences.Editor editor,
2968
+ final String defaultChannelKey,
2969
+ final boolean allowSetDefaultChannel,
2970
+ final String configDefaultChannel,
2971
+ final Callback callback
2972
+ ) {
2973
+ // Check if setting defaultChannel is allowed
2974
+ if (!allowSetDefaultChannel) {
2975
+ logger.error("setChannel is disabled by allowSetDefaultChannel config");
2976
+ final Map<String, Object> retError = new HashMap<>();
2977
+ retError.put("message", "setChannel is disabled by configuration");
2978
+ retError.put("error", "disabled_by_config");
2979
+ callback.callback(retError);
2980
+ return;
2981
+ }
2982
+
2983
+ if (isRemoteBlocked()) {
2984
+ final RemoteBlockResult blocked = remoteBlockedClientError();
2985
+ logger.debug("Skipping setChannel due to remote block (" + blocked.error + ").");
2986
+ final Map<String, Object> retError = new HashMap<>();
2987
+ retError.put("message", blocked.message);
2988
+ retError.put("error", blocked.error);
2989
+ callback.callback(retError);
2990
+ return;
2991
+ }
2992
+
2993
+ String channelUrl = this.channelUrl;
2994
+ if (channelUrl == null || channelUrl.isEmpty()) {
2995
+ logger.error("Channel URL is not set");
2996
+ final Map<String, Object> retError = new HashMap<>();
2997
+ retError.put("message", "channelUrl missing");
2998
+ retError.put("error", "missing_config");
2999
+ callback.callback(retError);
3000
+ return;
3001
+ }
3002
+ JSONObject json;
3003
+ try {
3004
+ json = this.createInfoObject();
3005
+ json.put("channel", channel);
3006
+ } catch (JSONException e) {
3007
+ logger.error("Error setting channel");
3008
+ logger.debug("JSONException: " + e.getMessage());
3009
+ final Map<String, Object> retError = new HashMap<>();
3010
+ retError.put("message", "Cannot get info: " + e);
3011
+ retError.put("error", "json_error");
3012
+ callback.callback(retError);
3013
+ return;
3014
+ }
3015
+
3016
+ makeJsonRequest(channelUrl, json, (res) -> {
3017
+ if (res.containsKey("error")) {
3018
+ callback.callback(res);
3019
+ } else if (Boolean.TRUE.equals(res.get("unset"))) {
3020
+ // Server requested to unset channel (public channel was requested)
3021
+ // Clear persisted defaultChannel and revert to config value
3022
+ editor.remove(defaultChannelKey);
3023
+ editor.apply();
3024
+ this.defaultChannel = configDefaultChannel;
3025
+ logger.info("Public channel requested, channel override removed");
3026
+ callback.callback(res);
670
3027
  } else {
671
- final PeriodicWorkRequest work = new PeriodicWorkRequest.Builder(workerClass, config.interval, TimeUnit.MINUTES)
672
- .setInitialDelay(config.interval, TimeUnit.MINUTES)
673
- .setInputData(data)
674
- .addTag(config.label)
675
- .setConstraints(constraints)
676
- .build();
677
- workManager.enqueueUniquePeriodicWork(config.label, ExistingPeriodicWorkPolicy.UPDATE, work);
3028
+ this.defaultChannel = channel;
3029
+ editor.putString(defaultChannelKey, channel);
3030
+ editor.apply();
3031
+ logger.info("defaultChannel persisted locally: " + channel);
3032
+ callback.callback(res);
3033
+ }
3034
+ });
3035
+ }
3036
+
3037
+ public void getChannel(final Callback callback) {
3038
+ this.getChannel(callback, null, null);
3039
+ }
3040
+
3041
+ public void getChannel(final Callback callback, final SharedPreferences.Editor editor, final String defaultChannelKey) {
3042
+ if (isRemoteBlocked()) {
3043
+ final RemoteBlockResult blocked = remoteBlockedClientError();
3044
+ logger.debug("Skipping getChannel due to remote block (" + blocked.error + ").");
3045
+ final Map<String, Object> retError = new HashMap<>();
3046
+ retError.put("message", blocked.message);
3047
+ retError.put("error", blocked.error);
3048
+ callback.callback(retError);
3049
+ return;
3050
+ }
3051
+
3052
+ String channelUrl = this.channelUrl;
3053
+ if (channelUrl == null || channelUrl.isEmpty()) {
3054
+ logger.error("Channel URL is not set");
3055
+ final Map<String, Object> retError = new HashMap<>();
3056
+ retError.put("message", "Channel URL is not set");
3057
+ retError.put("error", "missing_config");
3058
+ callback.callback(retError);
3059
+ return;
3060
+ }
3061
+ JSONObject json;
3062
+ try {
3063
+ json = this.createInfoObject();
3064
+ } catch (JSONException e) {
3065
+ logger.error("Error getting channel");
3066
+ logger.debug("JSONException: " + e.getMessage());
3067
+ final Map<String, Object> retError = new HashMap<>();
3068
+ retError.put("message", "Cannot get info: " + e);
3069
+ retError.put("error", "json_error");
3070
+ callback.callback(retError);
3071
+ return;
3072
+ }
3073
+
3074
+ Request request = new Request.Builder()
3075
+ .url(channelUrl)
3076
+ .put(RequestBody.create(json.toString(), MediaType.get("application/json")))
3077
+ .build();
3078
+
3079
+ DownloadService.sharedClient.newCall(request).enqueue(
3080
+ new okhttp3.Callback() {
3081
+ @Override
3082
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
3083
+ Map<String, Object> retError = new HashMap<>();
3084
+ retError.put("message", "Request failed: " + e.getMessage());
3085
+ retError.put("error", "network_error");
3086
+ callback.callback(retError);
3087
+ }
3088
+
3089
+ @Override
3090
+ public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
3091
+ try (ResponseBody responseBody = response.body()) {
3092
+ final String responseData = responseBody != null ? responseBody.string() : "";
3093
+ final RemoteBlockResult rateLimit = checkAndHandleRateLimitResponse(response, responseData);
3094
+ if (rateLimit.blocked) {
3095
+ Map<String, Object> retError = new HashMap<>();
3096
+ retError.put("message", rateLimit.message);
3097
+ retError.put("error", rateLimit.error);
3098
+ callback.callback(retError);
3099
+ return;
3100
+ }
3101
+
3102
+ if (response.code() == 400) {
3103
+ if (responseData.contains("channel_not_found") && !defaultChannel.isEmpty()) {
3104
+ Map<String, Object> ret = new HashMap<>();
3105
+ ret.put("channel", defaultChannel);
3106
+ ret.put("status", "default");
3107
+ logger.info("Channel get to \"" + ret);
3108
+ callback.callback(ret);
3109
+ return;
3110
+ }
3111
+ }
3112
+
3113
+ if (!response.isSuccessful()) {
3114
+ Map<String, Object> retError = new HashMap<>();
3115
+ retError.put("message", "Server error: " + response.code());
3116
+ retError.put("error", "response_error");
3117
+ callback.callback(retError);
3118
+ return;
3119
+ }
3120
+
3121
+ if (responseData.isEmpty()) {
3122
+ Map<String, Object> retError = new HashMap<>();
3123
+ retError.put("message", "Empty response body");
3124
+ retError.put("error", "no_response_body");
3125
+ callback.callback(retError);
3126
+ return;
3127
+ }
3128
+ JSONObject jsonResponse = new JSONObject(responseData);
3129
+
3130
+ // Check for server-side errors first
3131
+ if (jsonResponse.has("error")) {
3132
+ Map<String, Object> retError = new HashMap<>();
3133
+ retError.put("error", jsonResponse.getString("error"));
3134
+ if (jsonResponse.has("message")) {
3135
+ retError.put("message", jsonResponse.getString("message"));
3136
+ } else {
3137
+ retError.put("message", "server did not provide a message");
3138
+ }
3139
+ callback.callback(retError);
3140
+ return;
3141
+ }
3142
+
3143
+ Map<String, Object> ret = new HashMap<>();
3144
+
3145
+ Iterator<String> keys = jsonResponse.keys();
3146
+ while (keys.hasNext()) {
3147
+ String key = keys.next();
3148
+ if (jsonResponse.has(key)) {
3149
+ ret.put(key, jsonResponse.get(key));
3150
+ }
3151
+ }
3152
+ persistDefaultChannelFromResponse(ret.get("channel"), editor, defaultChannelKey);
3153
+ logger.info("Channel get to \"" + ret);
3154
+ callback.callback(ret);
3155
+ } catch (JSONException e) {
3156
+ Map<String, Object> retError = new HashMap<>();
3157
+ retError.put("message", "JSON parse error: " + e.getMessage());
3158
+ retError.put("error", "parse_error");
3159
+ callback.callback(retError);
3160
+ }
3161
+ }
3162
+ }
3163
+ );
3164
+ }
3165
+
3166
+ void persistDefaultChannelFromResponse(final Object channel, final SharedPreferences.Editor editor, final String defaultChannelKey) {
3167
+ if (!(channel instanceof String)) {
3168
+ return;
3169
+ }
3170
+
3171
+ final String channelName = ((String) channel).trim();
3172
+ if (channelName.isEmpty() || BundleInfo.ID_BUILTIN.equals(channelName)) {
3173
+ return;
3174
+ }
3175
+
3176
+ this.defaultChannel = channelName;
3177
+ if (editor != null && defaultChannelKey != null && !defaultChannelKey.isEmpty()) {
3178
+ editor.putString(defaultChannelKey, channelName);
3179
+ editor.apply();
3180
+ }
3181
+ logger.info("defaultChannel synchronized from getChannel(): " + channelName);
3182
+ }
3183
+
3184
+ public void listChannels(final Callback callback) {
3185
+ if (isRemoteBlocked()) {
3186
+ final RemoteBlockResult blocked = remoteBlockedClientError();
3187
+ logger.debug("Skipping listChannels due to remote block (" + blocked.error + ").");
3188
+ final Map<String, Object> retError = new HashMap<>();
3189
+ retError.put("message", blocked.message);
3190
+ retError.put("error", blocked.error);
3191
+ callback.callback(retError);
3192
+ return;
3193
+ }
3194
+
3195
+ String channelUrl = this.channelUrl;
3196
+ if (channelUrl == null || channelUrl.isEmpty()) {
3197
+ logger.error("Channel URL is not set");
3198
+ final Map<String, Object> retError = new HashMap<>();
3199
+ retError.put("message", "Channel URL is not set");
3200
+ retError.put("error", "missing_config");
3201
+ callback.callback(retError);
3202
+ return;
3203
+ }
3204
+
3205
+ JSONObject json;
3206
+ try {
3207
+ json = this.createInfoObject();
3208
+ } catch (JSONException e) {
3209
+ logger.error("Error creating info object");
3210
+ logger.debug("JSONException: " + e.getMessage());
3211
+ final Map<String, Object> retError = new HashMap<>();
3212
+ retError.put("message", "Cannot get info: " + e);
3213
+ retError.put("error", "json_error");
3214
+ callback.callback(retError);
3215
+ return;
3216
+ }
3217
+
3218
+ // Build URL with query parameters from JSON
3219
+ HttpUrl.Builder urlBuilder = HttpUrl.parse(channelUrl).newBuilder();
3220
+ try {
3221
+ Iterator<String> keys = json.keys();
3222
+ while (keys.hasNext()) {
3223
+ String key = keys.next();
3224
+ Object value = json.get(key);
3225
+ if (value != null) {
3226
+ urlBuilder.addQueryParameter(key, value.toString());
3227
+ }
3228
+ }
3229
+ } catch (JSONException e) {
3230
+ logger.error("Error adding query parameters");
3231
+ logger.debug("JSONException: " + e.getMessage());
3232
+ }
3233
+
3234
+ Request request = new Request.Builder().url(urlBuilder.build()).get().build();
3235
+
3236
+ DownloadService.sharedClient.newCall(request).enqueue(
3237
+ new okhttp3.Callback() {
3238
+ @Override
3239
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
3240
+ Map<String, Object> retError = new HashMap<>();
3241
+ retError.put("message", "Request failed: " + e.getMessage());
3242
+ retError.put("error", "network_error");
3243
+ callback.callback(retError);
3244
+ }
3245
+
3246
+ @Override
3247
+ public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
3248
+ try (ResponseBody responseBody = response.body()) {
3249
+ final String data = responseBody != null ? responseBody.string() : "";
3250
+ final RemoteBlockResult rateLimit = checkAndHandleRateLimitResponse(response, data);
3251
+ if (rateLimit.blocked) {
3252
+ Map<String, Object> retError = new HashMap<>();
3253
+ retError.put("message", rateLimit.message);
3254
+ retError.put("error", rateLimit.error);
3255
+ callback.callback(retError);
3256
+ return;
3257
+ }
3258
+
3259
+ if (!response.isSuccessful()) {
3260
+ Map<String, Object> retError = new HashMap<>();
3261
+ retError.put("message", "Server error: " + response.code());
3262
+ retError.put("error", "response_error");
3263
+ callback.callback(retError);
3264
+ return;
3265
+ }
3266
+
3267
+ if (data.isEmpty()) {
3268
+ Map<String, Object> retError = new HashMap<>();
3269
+ retError.put("message", "Empty response body");
3270
+ retError.put("error", "no_response_body");
3271
+ callback.callback(retError);
3272
+ return;
3273
+ }
3274
+
3275
+ try {
3276
+ Map<String, Object> ret = parseListChannelsResponse(data);
3277
+
3278
+ logger.info("Channels listed successfully");
3279
+ callback.callback(ret);
3280
+ } catch (JSONException arrayException) {
3281
+ // If not an array, try to parse as error object
3282
+ try {
3283
+ JSONObject json = new JSONObject(data);
3284
+ if (json.has("error")) {
3285
+ Map<String, Object> retError = new HashMap<>();
3286
+ retError.put("error", json.getString("error"));
3287
+ if (json.has("message")) {
3288
+ retError.put("message", json.getString("message"));
3289
+ } else {
3290
+ retError.put("message", "server did not provide a message");
3291
+ }
3292
+ callback.callback(retError);
3293
+ return;
3294
+ }
3295
+ Map<String, Object> retError = new HashMap<>();
3296
+ retError.put("message", "Unexpected channels response format");
3297
+ retError.put("error", "parse_error");
3298
+ callback.callback(retError);
3299
+ return;
3300
+ } catch (JSONException objException) {
3301
+ // If neither array nor object, throw parse error
3302
+ arrayException.addSuppressed(objException);
3303
+ Map<String, Object> retError = new HashMap<>();
3304
+ retError.put("message", "JSON parse error: " + arrayException.getMessage());
3305
+ retError.put("error", "parse_error");
3306
+ callback.callback(retError);
3307
+ }
3308
+ }
3309
+ }
3310
+ }
3311
+ }
3312
+ );
3313
+ }
3314
+
3315
+ static Map<String, Object> parseListChannelsResponse(final String data) throws JSONException {
3316
+ JSONArray channelsJson = new JSONArray(data);
3317
+ List<Map<String, Object>> channelsList = new ArrayList<>();
3318
+
3319
+ for (int i = 0; i < channelsJson.length(); i++) {
3320
+ JSONObject channelJson = channelsJson.getJSONObject(i);
3321
+ Object channelId = channelJson.get("id");
3322
+ if (!(channelId instanceof Number)) {
3323
+ throw new JSONException("Channel id must be a number");
3324
+ }
3325
+ Map<String, Object> channel = new HashMap<>();
3326
+ channel.put("id", channelId);
3327
+ channel.put("name", channelJson.optString("name", ""));
3328
+ channel.put("public", channelJson.optBoolean("public", false));
3329
+ channel.put("allow_self_set", channelJson.optBoolean("allow_self_set", false));
3330
+ channelsList.add(channel);
3331
+ }
3332
+
3333
+ Map<String, Object> ret = new HashMap<>();
3334
+ ret.put("channels", channelsList);
3335
+ return ret;
3336
+ }
3337
+
3338
+ public void sendStats(final String action) {
3339
+ this.sendStats(action, this.getCurrentBundle().getVersionName());
3340
+ }
3341
+
3342
+ public void sendStats(final String action, final String versionName) {
3343
+ this.sendStats(action, versionName, "");
3344
+ }
3345
+
3346
+ public void sendStats(final String action, final String versionName, final String oldVersionName) {
3347
+ this.sendStats(action, versionName, oldVersionName, null);
3348
+ }
3349
+
3350
+ public void sendStats(final String action, final String versionName, final String oldVersionName, final Map<String, String> metadata) {
3351
+ this.sendStats(action, versionName, oldVersionName, metadata, null);
3352
+ }
3353
+
3354
+ public void sendStats(
3355
+ final String action,
3356
+ final String versionName,
3357
+ final String oldVersionName,
3358
+ final Map<String, String> metadata,
3359
+ final Runnable onSent
3360
+ ) {
3361
+ if (statsStopped.get()) {
3362
+ return;
3363
+ }
3364
+
3365
+ if (this.previewSession) {
3366
+ if (logger != null) {
3367
+ logger.debug("Skipping sendStats during preview session.");
3368
+ }
3369
+ return;
3370
+ }
3371
+
3372
+ String statsUrl = this.statsUrl;
3373
+ if (statsUrl == null || statsUrl.isEmpty()) {
3374
+ return;
3375
+ }
3376
+
3377
+ JSONObject json;
3378
+ try {
3379
+ json = this.createInfoObject();
3380
+ json.put("version_name", versionName);
3381
+ json.put("old_version_name", oldVersionName);
3382
+ json.put("action", action);
3383
+ json.put("timestamp", System.currentTimeMillis());
3384
+ if (metadata != null && !metadata.isEmpty()) {
3385
+ json.put("metadata", new JSONObject(metadata));
3386
+ }
3387
+ } catch (JSONException e) {
3388
+ if (logger != null) {
3389
+ logger.error("Error preparing stats");
3390
+ logger.debug("JSONException: " + e.getMessage());
3391
+ }
3392
+ return;
3393
+ }
3394
+
3395
+ synchronized (statsQueue) {
3396
+ if (statsStopped.get()) {
3397
+ return;
3398
+ }
3399
+ while (statsQueue.size() >= MAX_PENDING_STATS) {
3400
+ statsQueue.remove(0);
3401
+ }
3402
+ statsQueue.add(new QueuedStatsEvent(json, onSent));
3403
+ }
3404
+ ensureStatsTimerStarted();
3405
+ }
3406
+
3407
+ public void restorePendingStats() {
3408
+ File file = pendingStatsFile();
3409
+ if (file == null) {
3410
+ return;
3411
+ }
3412
+ File backup = new File(file.getAbsolutePath() + ".bak");
3413
+ if (!file.exists() && backup.exists() && !backup.renameTo(file)) {
3414
+ if (logger != null) {
3415
+ logger.error("Failed to restore stats backup");
3416
+ }
3417
+ return;
3418
+ }
3419
+ if (!file.exists()) {
3420
+ return;
3421
+ }
3422
+ try {
3423
+ String raw = readFileUtf8(file);
3424
+ JSONArray arr = new JSONArray(raw);
3425
+ synchronized (statsQueue) {
3426
+ for (int i = 0; i < arr.length(); i++) {
3427
+ if (statsQueue.size() >= MAX_PENDING_STATS) {
3428
+ break;
3429
+ }
3430
+ statsQueue.add(new QueuedStatsEvent(arr.getJSONObject(i), null));
3431
+ }
3432
+ }
3433
+ if (backup.exists() && !backup.delete()) {
3434
+ if (logger != null) {
3435
+ logger.error("Failed to delete stats backup");
3436
+ }
3437
+ }
3438
+ if (!statsQueue.isEmpty()) {
3439
+ if (logger != null) {
3440
+ logger.info("Restored " + statsQueue.size() + " pending stats events");
3441
+ }
3442
+ ensureStatsTimerStarted();
678
3443
  }
679
- logger.info("Rescheduled Background Runner work after bundle switch.");
680
- } catch (ClassNotFoundException ignored) {
681
- logger.debug("Background Runner plugin not installed, skipping reschedule.");
682
3444
  } catch (Exception e) {
683
- logger.warn("Failed to reschedule Background Runner work after bundle switch.");
684
- logger.debug("Background Runner reschedule error: " + e.getMessage());
3445
+ if (logger != null) {
3446
+ logger.error("Failed to restore pending stats");
3447
+ logger.debug("Error: " + e.getMessage());
3448
+ }
3449
+ }
3450
+ }
3451
+
3452
+ int pendingStatsCount() {
3453
+ return statsQueue.size();
3454
+ }
3455
+
3456
+ public void persistPendingStats() {
3457
+ persistStatsQueue();
3458
+ }
3459
+
3460
+ private File pendingStatsFile() {
3461
+ final File dir = this.noBackupDir != null ? this.noBackupDir : this.documentsDir;
3462
+ if (dir == null) {
3463
+ return null;
3464
+ }
3465
+ return new File(dir, PENDING_STATS_FILE);
3466
+ }
3467
+
3468
+ private void persistStatsQueue() {
3469
+ persistStatsQueue(false);
3470
+ }
3471
+
3472
+ private void persistStatsQueue(final boolean force) {
3473
+ File file = pendingStatsFile();
3474
+ if (file == null) {
3475
+ return;
3476
+ }
3477
+ synchronized (pendingStatsPersistLock) {
3478
+ if (statsStopped.get() && !force) {
3479
+ return;
3480
+ }
3481
+ JSONArray arr = new JSONArray();
3482
+ synchronized (statsQueue) {
3483
+ final List<QueuedStatsEvent> combined = new ArrayList<>(statsInFlight.size() + statsQueue.size());
3484
+ combined.addAll(statsInFlight);
3485
+ combined.addAll(statsQueue);
3486
+ final int start = Math.max(0, combined.size() - MAX_PENDING_STATS);
3487
+ for (int i = start; i < combined.size(); i++) {
3488
+ arr.put(combined.get(i).event);
3489
+ }
3490
+ }
3491
+ try {
3492
+ if (arr.length() == 0) {
3493
+ writeFileAtomically(file, "[]".getBytes(StandardCharsets.UTF_8));
3494
+ File backup = new File(file.getAbsolutePath() + ".bak");
3495
+ if (backup.exists() && !backup.delete()) {
3496
+ if (logger != null) {
3497
+ logger.error("Failed to delete empty stats backup");
3498
+ }
3499
+ }
3500
+ return;
3501
+ }
3502
+ writeFileAtomically(file, arr.toString().getBytes(StandardCharsets.UTF_8));
3503
+ } catch (Exception e) {
3504
+ if (logger != null) {
3505
+ logger.error("Failed to persist stats queue");
3506
+ logger.debug("Error: " + e.getMessage());
3507
+ }
3508
+ }
3509
+ }
3510
+ }
3511
+
3512
+ private static String readFileUtf8(final File file) throws IOException {
3513
+ final long length = file.length();
3514
+ final byte[] buf = new byte[length > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) length];
3515
+ try (FileInputStream in = new FileInputStream(file)) {
3516
+ int offset = 0;
3517
+ while (offset < buf.length) {
3518
+ final int read = in.read(buf, offset, buf.length - offset);
3519
+ if (read < 0) {
3520
+ break;
3521
+ }
3522
+ offset += read;
3523
+ }
3524
+ return new String(buf, 0, offset, StandardCharsets.UTF_8);
3525
+ }
3526
+ }
3527
+
3528
+ private void writeFileAtomically(final File file, final byte[] bytes) throws IOException {
3529
+ final File tmp = new File(file.getAbsolutePath() + ".tmp");
3530
+ File backup = null;
3531
+ try {
3532
+ try (FileOutputStream out = new FileOutputStream(tmp)) {
3533
+ out.write(bytes);
3534
+ out.flush();
3535
+ }
3536
+ if (tmp.renameTo(file)) {
3537
+ return;
3538
+ }
3539
+ if (file.exists()) {
3540
+ backup = new File(file.getAbsolutePath() + ".bak");
3541
+ if (backup.exists() && !backup.delete()) {
3542
+ throw new IOException("Failed to replace " + file.getAbsolutePath());
3543
+ }
3544
+ if (!file.renameTo(backup)) {
3545
+ throw new IOException("Failed to replace " + file.getAbsolutePath());
3546
+ }
3547
+ }
3548
+ if (tmp.renameTo(file)) {
3549
+ if (backup != null && backup.exists() && !backup.delete()) {
3550
+ if (logger != null) {
3551
+ logger.error("Failed to delete stats backup");
3552
+ }
3553
+ }
3554
+ backup = null;
3555
+ return;
3556
+ }
3557
+ throw new IOException("Failed to persist " + file.getAbsolutePath());
3558
+ } finally {
3559
+ if (backup != null && !file.exists()) {
3560
+ backup.renameTo(file);
3561
+ }
3562
+ if (tmp.exists() && !tmp.delete()) {
3563
+ tmp.deleteOnExit();
3564
+ }
3565
+ }
3566
+ }
3567
+
3568
+ private synchronized void ensureStatsTimerStarted() {
3569
+ if (statsStopped.get()) {
3570
+ return;
3571
+ }
3572
+ if (statsFlushTask == null || statsFlushTask.isCancelled() || statsFlushTask.isDone()) {
3573
+ statsFlushTask = statsScheduler.scheduleAtFixedRate(
3574
+ this::flushStatsQueue,
3575
+ STATS_FLUSH_INTERVAL_MS,
3576
+ STATS_FLUSH_INTERVAL_MS,
3577
+ TimeUnit.MILLISECONDS
3578
+ );
3579
+ }
3580
+ }
3581
+
3582
+ private void flushStatsQueue() {
3583
+ if (statsStopped.get()) {
3584
+ return;
3585
+ }
3586
+ if (statsQueue.isEmpty()) {
3587
+ return;
3588
+ }
3589
+
3590
+ // While Retry-After is active, keep stats queued and skip the network call.
3591
+ if (isRemoteBlocked()) {
3592
+ logger.debug("Deferring stats flush until Retry-After expires.");
3593
+ return;
3594
+ }
3595
+
3596
+ String statsUrl = this.statsUrl;
3597
+ if (statsUrl == null || statsUrl.isEmpty()) {
3598
+ synchronized (statsQueue) {
3599
+ statsQueue.clear();
3600
+ statsInFlight.clear();
3601
+ }
3602
+ persistStatsQueue();
3603
+ return;
3604
+ }
3605
+
3606
+ if (!statsFlushInFlight.compareAndSet(false, true)) {
3607
+ return;
3608
+ }
3609
+
3610
+ final List<QueuedStatsEvent> eventsToSend;
3611
+ synchronized (statsQueue) {
3612
+ if (statsQueue.isEmpty()) {
3613
+ statsFlushInFlight.set(false);
3614
+ return;
3615
+ }
3616
+ eventsToSend = new ArrayList<>(statsQueue);
3617
+ statsQueue.clear();
3618
+ statsInFlight.clear();
3619
+ statsInFlight.addAll(eventsToSend);
3620
+ }
3621
+ persistStatsQueue();
3622
+
3623
+ JSONArray jsonArray = new JSONArray();
3624
+ for (QueuedStatsEvent queuedEvent : eventsToSend) {
3625
+ jsonArray.put(queuedEvent.event);
3626
+ }
3627
+
3628
+ Request request = new Request.Builder()
3629
+ .url(statsUrl)
3630
+ .post(RequestBody.create(jsonArray.toString(), MediaType.get("application/json")))
3631
+ .build();
3632
+
3633
+ final int eventCount = eventsToSend.size();
3634
+ DownloadService.sharedClient.newCall(request).enqueue(
3635
+ new okhttp3.Callback() {
3636
+ @Override
3637
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
3638
+ if (abandonStoppedStatsFlush()) {
3639
+ return;
3640
+ }
3641
+ requeueStatsEvents(eventsToSend);
3642
+ if (logger != null) {
3643
+ logger.error("Failed to send stats batch");
3644
+ logger.debug("Error: " + e.getMessage());
3645
+ }
3646
+ statsFlushInFlight.set(false);
3647
+ }
3648
+
3649
+ @Override
3650
+ public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
3651
+ try (ResponseBody responseBody = response.body()) {
3652
+ if (abandonStoppedStatsFlush()) {
3653
+ return;
3654
+ }
3655
+ final String responseData = responseBody != null ? responseBody.string() : "";
3656
+ if (checkAndHandleRateLimitResponse(response, responseData).blocked) {
3657
+ requeueStatsEvents(eventsToSend);
3658
+ return;
3659
+ }
3660
+
3661
+ if (response.isSuccessful()) {
3662
+ synchronized (statsQueue) {
3663
+ statsInFlight.clear();
3664
+ }
3665
+ persistStatsQueue();
3666
+ if (logger != null) {
3667
+ logger.info("Stats batch sent successfully");
3668
+ logger.debug("Sent " + eventCount + " events");
3669
+ }
3670
+ runStatsCallbacks(eventsToSend);
3671
+ } else if (isTransientStatsFailure(response.code())) {
3672
+ requeueStatsEvents(eventsToSend);
3673
+ if (logger != null) {
3674
+ logger.error("Error sending stats batch");
3675
+ logger.debug("Retrying later, response code: " + response.code());
3676
+ }
3677
+ } else {
3678
+ synchronized (statsQueue) {
3679
+ statsInFlight.clear();
3680
+ }
3681
+ persistStatsQueue();
3682
+ if (logger != null) {
3683
+ logger.error("Dropping stats batch after permanent error");
3684
+ logger.debug("Response code: " + response.code());
3685
+ }
3686
+ }
3687
+ } finally {
3688
+ statsFlushInFlight.set(false);
3689
+ }
3690
+ }
3691
+ }
3692
+ );
3693
+ }
3694
+
3695
+ private boolean abandonStoppedStatsFlush() {
3696
+ if (!statsStopped.get()) {
3697
+ return false;
3698
+ }
3699
+ statsFlushInFlight.set(false);
3700
+ return true;
3701
+ }
3702
+
3703
+ /**
3704
+ * Only 429, request timeout and 5xx are worth retrying; other 4xx are permanent rejections.
3705
+ */
3706
+ private static boolean isTransientStatsFailure(final int statusCode) {
3707
+ return statusCode == 429 || statusCode == 408 || statusCode >= 500;
3708
+ }
3709
+
3710
+ private void requeueStatsEvents(final List<QueuedStatsEvent> events) {
3711
+ if (statsStopped.get() || events == null || events.isEmpty()) {
3712
+ return;
3713
+ }
3714
+ synchronized (statsQueue) {
3715
+ statsInFlight.clear();
3716
+ statsQueue.addAll(0, events);
3717
+ while (statsQueue.size() > MAX_PENDING_STATS) {
3718
+ statsQueue.remove(0);
3719
+ }
3720
+ }
3721
+ persistStatsQueue();
3722
+ ensureStatsTimerStarted();
3723
+ }
3724
+
3725
+ private void runStatsCallbacks(final List<QueuedStatsEvent> sentEvents) {
3726
+ for (final QueuedStatsEvent sentEvent : sentEvents) {
3727
+ if (sentEvent.onSent == null) {
3728
+ continue;
3729
+ }
3730
+
3731
+ try {
3732
+ sentEvent.onSent.run();
3733
+ } catch (Exception e) {
3734
+ if (logger != null) {
3735
+ logger.error("Error running stats sent callback");
3736
+ logger.debug("Error: " + e.getMessage());
3737
+ }
3738
+ }
3739
+ }
3740
+ }
3741
+
3742
+ public BundleInfo getBundleInfo(final String id) {
3743
+ String trueId = BundleInfo.VERSION_UNKNOWN;
3744
+ if (id != null) {
3745
+ trueId = id;
3746
+ }
3747
+ BundleInfo result;
3748
+ if (BundleInfo.ID_BUILTIN.equals(trueId)) {
3749
+ result = new BundleInfo(
3750
+ trueId,
3751
+ this.versionBuild == null || this.versionBuild.isEmpty() ? null : this.versionBuild,
3752
+ BundleStatus.SUCCESS,
3753
+ "",
3754
+ ""
3755
+ );
3756
+ } else if (BundleInfo.VERSION_UNKNOWN.equals(trueId)) {
3757
+ result = new BundleInfo(trueId, null, BundleStatus.ERROR, "", "");
3758
+ } else {
3759
+ try {
3760
+ String stored = this.prefs.getString(trueId + INFO_SUFFIX, "");
3761
+ if (stored.isEmpty()) {
3762
+ result = new BundleInfo(trueId, null, BundleStatus.PENDING, "", "");
3763
+ } else {
3764
+ result = BundleInfo.fromJSON(stored);
3765
+ }
3766
+ } catch (JSONException e) {
3767
+ logger.error("Failed to parse bundle info");
3768
+ logger.debug("Bundle ID: " + trueId + ", Error: " + e.getMessage());
3769
+ // Clear corrupted data
3770
+ this.editor.remove(trueId + INFO_SUFFIX);
3771
+ this.editor.commit();
3772
+ result = new BundleInfo(trueId, null, BundleStatus.ERROR, "", "");
3773
+ }
3774
+ }
3775
+ return result;
3776
+ }
3777
+
3778
+ public BundleInfo getBundleInfoByName(final String versionName) {
3779
+ final List<BundleInfo> installed = this.list(false);
3780
+ for (final BundleInfo i : installed) {
3781
+ if (i.getVersionName().equals(versionName)) {
3782
+ return i;
3783
+ }
3784
+ }
3785
+ return null;
3786
+ }
3787
+
3788
+ private void removeBundleInfo(final String id) {
3789
+ this.saveBundleInfo(id, null);
3790
+ }
3791
+
3792
+ public boolean saveBundleInfo(final String id, final BundleInfo info) {
3793
+ if (id == null || (info != null && (info.isBuiltin() || info.isUnknown()))) {
3794
+ logger.debug("Not saving info for bundle: [" + id + "] " + info);
3795
+ return false;
3796
+ }
3797
+
3798
+ if (info == null) {
3799
+ logger.debug("Removing info for bundle [" + id + "]");
3800
+ this.editor.remove(id + INFO_SUFFIX);
3801
+ } else {
3802
+ final BundleInfo update = info.setId(id);
3803
+ String jsonString = update.toString();
3804
+ logger.debug("Storing info for bundle [" + id + "] " + update.getClass().getName() + " -> " + jsonString);
3805
+ this.editor.putString(id + INFO_SUFFIX, jsonString);
3806
+ }
3807
+ return this.editor.commit();
3808
+ }
3809
+
3810
+ private void setBundleStatus(final String id, final BundleStatus status) {
3811
+ if (id != null && status != null) {
3812
+ BundleInfo info = this.getBundleInfo(id);
3813
+ logger.debug("Setting status for bundle [" + id + "] to " + status);
3814
+ this.saveBundleInfo(id, info.setStatus(status));
3815
+ }
3816
+ }
3817
+
3818
+ private String getCurrentBundleId() {
3819
+ if (this.isUsingBuiltin()) {
3820
+ return BundleInfo.ID_BUILTIN;
3821
+ } else {
3822
+ final String path = this.getCurrentBundlePath();
3823
+ return path.substring(path.lastIndexOf('/') + 1);
3824
+ }
3825
+ }
3826
+
3827
+ public BundleInfo getCurrentBundle() {
3828
+ return this.getBundleInfo(this.getCurrentBundleId());
3829
+ }
3830
+
3831
+ public String getCurrentBundlePath() {
3832
+ String path = this.prefs.getString(this.CAP_SERVER_PATH, "public");
3833
+ if (path.trim().isEmpty()) {
3834
+ return "public";
3835
+ }
3836
+ return path;
3837
+ }
3838
+
3839
+ public Boolean isUsingBuiltin() {
3840
+ return this.getCurrentBundlePath().equals("public");
3841
+ }
3842
+
3843
+ public BundleInfo getFallbackBundle() {
3844
+ final String id = this.prefs.getString(FALLBACK_VERSION, BundleInfo.ID_BUILTIN);
3845
+ return this.getBundleInfo(id);
3846
+ }
3847
+
3848
+ private void setFallbackBundle(final BundleInfo fallback) {
3849
+ this.editor.putString(FALLBACK_VERSION, fallback == null ? BundleInfo.ID_BUILTIN : fallback.getId());
3850
+ this.editor.commit();
3851
+ }
3852
+
3853
+ public BundleInfo getNextBundle() {
3854
+ final String id = this.prefs.getString(NEXT_VERSION, null);
3855
+ if (id == null) return null;
3856
+ return this.getBundleInfo(id);
3857
+ }
3858
+
3859
+ public boolean clearNextBundleIfCurrent() {
3860
+ final BundleInfo next = this.getNextBundle();
3861
+ if (next == null || !next.getId().equals(this.getCurrentBundle().getId())) {
3862
+ return false;
3863
+ }
3864
+ logger.info("Next bundle " + next.getId() + " is already the current bundle. Clearing next.");
3865
+ this.setNextBundle(null);
3866
+ return true;
3867
+ }
3868
+
3869
+ public BundleInfo getPreviewFallbackBundle() {
3870
+ final String id = this.prefs.getString(PREVIEW_FALLBACK_VERSION, null);
3871
+ if (id == null) return null;
3872
+ final BundleInfo bundle = this.getBundleInfo(id);
3873
+ if (bundle.isErrorStatus() || (!bundle.isBuiltin() && !this.bundleExists(id))) {
3874
+ this.setPreviewFallbackBundle(null);
3875
+ return null;
3876
+ }
3877
+ return bundle;
3878
+ }
3879
+
3880
+ public boolean setPreviewFallbackBundle(final String fallback) {
3881
+ if (fallback == null) {
3882
+ this.editor.remove(PREVIEW_FALLBACK_VERSION);
3883
+ } else {
3884
+ final BundleInfo newBundle = this.getBundleInfo(fallback);
3885
+ if (newBundle.isErrorStatus() || (!newBundle.isBuiltin() && !this.bundleExists(fallback))) {
3886
+ return false;
3887
+ }
3888
+ this.editor.putString(PREVIEW_FALLBACK_VERSION, fallback);
3889
+ }
3890
+ this.editor.commit();
3891
+ return true;
3892
+ }
3893
+
3894
+ public boolean setNextBundle(final String next) {
3895
+ BundleInfo bundleToNotify = null;
3896
+ if (next == null) {
3897
+ this.editor.remove(NEXT_VERSION);
3898
+ } else {
3899
+ final BundleInfo newBundle = this.getBundleInfo(next);
3900
+ if (!newBundle.isBuiltin() && !this.bundleExists(next)) {
3901
+ return false;
3902
+ }
3903
+ if (next.equals(this.getCurrentBundleId()) && BundleStatus.SUCCESS == newBundle.getStatus()) {
3904
+ logger.info("Bundle " + next + " is already the current successful bundle. Skip next().");
3905
+ return true;
3906
+ }
3907
+ this.editor.putString(NEXT_VERSION, next);
3908
+ this.setBundleStatus(next, BundleStatus.PENDING);
3909
+ bundleToNotify = newBundle;
3910
+ }
3911
+ this.editor.commit();
3912
+ if (bundleToNotify != null) {
3913
+ this.sendStats("set_next", bundleToNotify.getVersionName(), this.getCurrentBundle().getVersionName());
3914
+ final Map<String, Object> payload = new HashMap<>();
3915
+ payload.put("bundle", bundleToNotify.toJSONMap());
3916
+ this.notifyListeners("setNext", payload);
3917
+ }
3918
+ return true;
3919
+ }
3920
+
3921
+ /**
3922
+ * Shuts down the stats scheduler and flushes any pending stats.
3923
+ * Should be called when the plugin is destroyed to prevent resource leaks.
3924
+ */
3925
+ public void shutdown() {
3926
+ statsStopped.set(true);
3927
+ // Cancel the scheduled task
3928
+ if (statsFlushTask != null) {
3929
+ statsFlushTask.cancel(false);
3930
+ statsFlushTask = null;
3931
+ }
3932
+
3933
+ // Write once, then ignore later callbacks so they cannot delete a newer instance's file.
3934
+ persistStatsQueue(true);
3935
+
3936
+ // Shutdown the scheduler
3937
+ statsScheduler.shutdown();
3938
+ try {
3939
+ if (!statsScheduler.awaitTermination(2, TimeUnit.SECONDS)) {
3940
+ statsScheduler.shutdownNow();
3941
+ }
3942
+ } catch (InterruptedException e) {
3943
+ statsScheduler.shutdownNow();
3944
+ Thread.currentThread().interrupt();
685
3945
  }
686
3946
  }
687
3947
  }