@capgo/capacitor-updater 6.51.23 → 6.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/CapgoCapacitorUpdater.podspec +0 -3
  2. package/Package.swift +3 -11
  3. package/README.md +201 -66
  4. package/android/build.gradle +2 -3
  5. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +593 -176
  6. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +775 -162
  7. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +2 -1
  8. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +226 -106
  9. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +107 -30
  10. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +325 -0
  11. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +63 -4
  12. package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +306 -0
  14. package/dist/docs.json +394 -27
  15. package/dist/esm/definitions.d.ts +220 -7
  16. package/dist/esm/definitions.js.map +1 -1
  17. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +472 -144
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +162 -0
  20. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +392 -82
  21. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +2 -1
  22. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +204 -93
  23. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +75 -5
  24. package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
  25. package/ios/Sources/CapacitorUpdaterPlugin/RedirectPolicyDelegate.swift +53 -0
  26. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +5 -2
  27. package/ios/Sources/CapacitorUpdaterPlugin/ZipArchiveReader.swift +247 -0
  28. package/ios/Sources/CapacitorUpdaterPlugin/ZipCentralDirectory.swift +280 -0
  29. package/package.json +7 -3
@@ -150,11 +150,12 @@ public class CryptoCipher {
150
150
  }
151
151
  return;
152
152
  }
153
+ // The bundle is encrypted from here on: an unusable key must fail, never leave it encrypted.
153
154
  if (!publicKey.startsWith("-----BEGIN RSA PUBLIC KEY-----")) {
154
155
  if (logger != null) {
155
156
  logger.error("The public key is not a valid RSA Public key");
156
157
  }
157
- return;
158
+ throw new IOException("AES file decryption failed: the public key is not a valid RSA public key");
158
159
  }
159
160
 
160
161
  try {
@@ -1,7 +1,6 @@
1
1
  package ee.forgr.capacitor_updater;
2
2
 
3
3
  import android.content.SharedPreferences;
4
- import io.github.g00fy2.versioncompare.Version;
5
4
  import java.text.ParsePosition;
6
5
  import java.text.SimpleDateFormat;
7
6
  import java.util.ArrayList;
@@ -17,6 +16,9 @@ public class DelayUpdateUtils {
17
16
  private final Logger logger;
18
17
 
19
18
  public static final String DELAY_CONDITION_PREFERENCES = "DELAY_CONDITION_PREFERENCES_CAPGO";
19
+ public static final String DELAY_CONDITION_MODE_PREFERENCES = "DELAY_CONDITION_MODE_PREFERENCES_CAPGO";
20
+ public static final String DELAY_CONDITION_MODE_AND = "and";
21
+ public static final String DELAY_CONDITION_MODE_OR = "or";
20
22
  public static final String BACKGROUND_TIMESTAMP_KEY = "BACKGROUND_TIMESTAMP_KEY_CAPGO";
21
23
 
22
24
  private final SharedPreferences prefs;
@@ -39,128 +41,242 @@ public class DelayUpdateUtils {
39
41
  public void checkCancelDelay(CancelDelaySource source) {
40
42
  String delayUpdatePreferences = prefs.getString(DELAY_CONDITION_PREFERENCES, "[]");
41
43
  ArrayList<DelayCondition> delayConditionList = parseDelayConditions(delayUpdatePreferences);
44
+ if (delayConditionList.isEmpty()) {
45
+ return;
46
+ }
47
+
48
+ final boolean useOrMode = isOrConditionMode();
42
49
  ArrayList<DelayCondition> delayConditionListToKeep = new ArrayList<>(delayConditionList.size());
43
50
  int index = 0;
51
+ boolean anyConditionMet = false;
44
52
 
45
53
  for (DelayCondition condition : delayConditionList) {
46
- DelayUntilNext kind = condition.getKind();
47
- String value = condition.getValue();
48
- switch (kind) {
49
- case background:
50
- if (source == CancelDelaySource.FOREGROUND) {
51
- long backgroundedAt = getBackgroundTimestamp();
52
- long now = System.currentTimeMillis();
53
- long delta = Math.max(0, now - backgroundedAt);
54
- long longValue = 0L;
55
- try {
56
- longValue = Long.parseLong(value);
57
- } catch (NumberFormatException e) {
58
- logger.error(
59
- "Background condition (value: " +
60
- value +
61
- ") had an invalid value at index " +
62
- index +
63
- ". We will likely remove it."
64
- );
65
- }
66
-
67
- if (delta > longValue) {
68
- logger.info(
69
- "Background condition (value: " +
70
- value +
71
- ") deleted at index " +
72
- index +
73
- ". Delta: " +
74
- delta +
75
- ", longValue: " +
76
- longValue
77
- );
78
- } else {
79
- delayConditionListToKeep.add(condition);
80
- logger.info(
81
- "Background delay (value: " +
82
- value +
83
- ") condition kept at index " +
84
- index +
85
- " (source: " +
86
- source.toString() +
87
- ")"
88
- );
89
- }
54
+ ConditionCheckResult result = evaluateCondition(condition, source, index);
55
+ if (result.met) {
56
+ anyConditionMet = true;
57
+ if (!useOrMode) {
58
+ logger.info(result.logMessage);
59
+ }
60
+ } else if (!useOrMode) {
61
+ if (result.keep) {
62
+ delayConditionListToKeep.add(condition);
63
+ }
64
+ if (result.logMessage != null) {
65
+ if (result.error) {
66
+ logger.error(result.logMessage);
90
67
  } else {
91
- delayConditionListToKeep.add(condition);
92
- logger.info(
93
- "Background delay (value: " +
68
+ logger.info(result.logMessage);
69
+ }
70
+ }
71
+ } else if (result.keep) {
72
+ delayConditionListToKeep.add(condition);
73
+ }
74
+ index++;
75
+ }
76
+
77
+ if (useOrMode) {
78
+ if (anyConditionMet || delayConditionListToKeep.isEmpty()) {
79
+ logger.info("Delay condition met in OR mode (source: " + source + "), canceling delay");
80
+ this.cancelDelay("checkCancelDelay");
81
+ } else if (delayConditionListToKeep.size() != delayConditionList.size()) {
82
+ this.setMultiDelay(convertDelayConditionsToJson(delayConditionListToKeep));
83
+ }
84
+ return;
85
+ }
86
+
87
+ if (delayConditionListToKeep.isEmpty()) {
88
+ this.cancelDelay("checkCancelDelay");
89
+ } else {
90
+ this.setMultiDelay(convertDelayConditionsToJson(delayConditionListToKeep));
91
+ }
92
+ }
93
+
94
+ private static final class ConditionCheckResult {
95
+
96
+ final boolean met;
97
+ final boolean keep;
98
+ final boolean error;
99
+ final String logMessage;
100
+
101
+ ConditionCheckResult(boolean met, boolean keep, boolean error, String logMessage) {
102
+ this.met = met;
103
+ this.keep = keep;
104
+ this.error = error;
105
+ this.logMessage = logMessage;
106
+ }
107
+ }
108
+
109
+ private ConditionCheckResult evaluateCondition(DelayCondition condition, CancelDelaySource source, int index) {
110
+ DelayUntilNext kind = condition.getKind();
111
+ String value = condition.getValue();
112
+ switch (kind) {
113
+ case background:
114
+ if (source == CancelDelaySource.FOREGROUND) {
115
+ long backgroundedAt = getBackgroundTimestamp();
116
+ long now = System.currentTimeMillis();
117
+ long delta = Math.max(0, now - backgroundedAt);
118
+ long longValue = 0L;
119
+ try {
120
+ longValue = Long.parseLong(value);
121
+ } catch (NumberFormatException e) {
122
+ return new ConditionCheckResult(
123
+ false,
124
+ false,
125
+ true,
126
+ "Background condition (value: " +
94
127
  value +
95
- ") condition kept at index " +
128
+ ") had an invalid value at index " +
96
129
  index +
97
- " (source: " +
98
- source.toString() +
99
- ")"
130
+ ". We will likely remove it."
100
131
  );
101
132
  }
102
- break;
103
- case kill:
104
- if (source == CancelDelaySource.KILLED) {
105
- logger.info("Kill delay (value: " + value + ") condition removed at index " + index + " after app kill");
106
- } else {
107
- delayConditionListToKeep.add(condition);
108
- logger.info(
109
- "Kill delay (value: " + value + ") condition kept at index " + index + " (source: " + source.toString() + ")"
133
+
134
+ if (delta > longValue) {
135
+ return new ConditionCheckResult(
136
+ true,
137
+ false,
138
+ false,
139
+ "Background condition (value: " +
140
+ value +
141
+ ") deleted at index " +
142
+ index +
143
+ ". Delta: " +
144
+ delta +
145
+ ", longValue: " +
146
+ longValue
110
147
  );
111
148
  }
112
- break;
113
- case date:
114
- if (!"".equals(value)) {
115
- Date date = parseDateCondition(value);
116
- if (date != null) {
117
- if (new Date().compareTo(date) > 0) {
118
- logger.info("Date delay (value: " + value + ") condition removed due to expired date at index " + index);
119
- } else {
120
- delayConditionListToKeep.add(condition);
121
- logger.info("Date delay (value: " + value + ") condition kept at index " + index);
122
- }
123
- } else {
124
- logger.error("Date delay (value: " + value + ") condition removed due to parsing issue at index " + index);
149
+ return new ConditionCheckResult(
150
+ false,
151
+ true,
152
+ false,
153
+ "Background delay (value: " + value + ") condition kept at index " + index + " (source: " + source + ")"
154
+ );
155
+ }
156
+ return new ConditionCheckResult(
157
+ false,
158
+ true,
159
+ false,
160
+ "Background delay (value: " + value + ") condition kept at index " + index + " (source: " + source + ")"
161
+ );
162
+ case kill:
163
+ if (source == CancelDelaySource.KILLED) {
164
+ return new ConditionCheckResult(
165
+ true,
166
+ false,
167
+ false,
168
+ "Kill delay (value: " + value + ") condition removed at index " + index + " after app kill"
169
+ );
170
+ }
171
+ return new ConditionCheckResult(
172
+ false,
173
+ true,
174
+ false,
175
+ "Kill delay (value: " + value + ") condition kept at index " + index + " (source: " + source + ")"
176
+ );
177
+ case date:
178
+ if (!"".equals(value)) {
179
+ Date date = parseDateCondition(value);
180
+ if (date != null) {
181
+ if (new Date().compareTo(date) > 0) {
182
+ return new ConditionCheckResult(
183
+ true,
184
+ false,
185
+ false,
186
+ "Date delay (value: " + value + ") condition removed due to expired date at index " + index
187
+ );
125
188
  }
126
- } else {
127
- logger.debug("Date delay (value: " + value + ") condition removed due to empty value at index " + index);
189
+ return new ConditionCheckResult(
190
+ false,
191
+ true,
192
+ false,
193
+ "Date delay (value: " + value + ") condition kept at index " + index
194
+ );
128
195
  }
129
- break;
130
- case nativeVersion:
131
- if (!"".equals(value)) {
132
- try {
133
- final Version versionLimit = new Version(value);
134
- if (this.currentVersionNative.isAtLeast(versionLimit)) {
135
- logger.info(
136
- "Native version delay (value: " + value + ") condition removed due to above limit at index " + index
137
- );
138
- } else {
139
- delayConditionListToKeep.add(condition);
140
- logger.info("Native version delay (value: " + value + ") condition kept at index " + index);
141
- }
142
- } catch (final Exception e) {
143
- logger.error(
144
- "Native version delay (value: " +
145
- value +
146
- ") condition removed due to parsing issue at index " +
147
- index +
148
- " " +
149
- e.getMessage()
196
+ return new ConditionCheckResult(
197
+ false,
198
+ false,
199
+ true,
200
+ "Date delay (value: " + value + ") condition removed due to parsing issue at index " + index
201
+ );
202
+ }
203
+ return new ConditionCheckResult(
204
+ false,
205
+ false,
206
+ false,
207
+ "Date delay (value: " + value + ") condition removed due to empty value at index " + index
208
+ );
209
+ case nativeVersion:
210
+ if (!"".equals(value)) {
211
+ try {
212
+ final Version versionLimit = new Version(value);
213
+ if (this.currentVersionNative.isAtLeast(versionLimit)) {
214
+ return new ConditionCheckResult(
215
+ true,
216
+ false,
217
+ false,
218
+ "Native version delay (value: " + value + ") condition removed due to above limit at index " + index
150
219
  );
151
220
  }
152
- } else {
153
- logger.debug("Native version delay (value: " + value + ") condition removed due to empty value at index " + index);
221
+ return new ConditionCheckResult(
222
+ false,
223
+ true,
224
+ false,
225
+ "Native version delay (value: " + value + ") condition kept at index " + index
226
+ );
227
+ } catch (final Exception e) {
228
+ return new ConditionCheckResult(
229
+ false,
230
+ false,
231
+ true,
232
+ "Native version delay (value: " +
233
+ value +
234
+ ") condition removed due to parsing issue at index " +
235
+ index +
236
+ " " +
237
+ e.getMessage()
238
+ );
154
239
  }
155
- break;
156
- }
157
- index++;
240
+ }
241
+ return new ConditionCheckResult(
242
+ false,
243
+ false,
244
+ false,
245
+ "Native version delay (value: " + value + ") condition removed due to empty value at index " + index
246
+ );
247
+ default:
248
+ return new ConditionCheckResult(false, false, true, "Unknown delay condition kind at index " + index);
158
249
  }
250
+ }
159
251
 
160
- if (delayConditionListToKeep.isEmpty()) {
161
- this.cancelDelay("checkCancelDelay");
162
- } else {
163
- this.setMultiDelay(convertDelayConditionsToJson(delayConditionListToKeep));
252
+ public boolean isOrConditionMode() {
253
+ return DELAY_CONDITION_MODE_OR.equals(getConditionMode());
254
+ }
255
+
256
+ public String getConditionMode() {
257
+ String mode = prefs.getString(DELAY_CONDITION_MODE_PREFERENCES, DELAY_CONDITION_MODE_AND);
258
+ if (DELAY_CONDITION_MODE_OR.equals(mode)) {
259
+ return DELAY_CONDITION_MODE_OR;
260
+ }
261
+ return DELAY_CONDITION_MODE_AND;
262
+ }
263
+
264
+ public Boolean setConditionMode(String conditionMode) {
265
+ try {
266
+ String normalized = DELAY_CONDITION_MODE_OR.equals(conditionMode) ? DELAY_CONDITION_MODE_OR : DELAY_CONDITION_MODE_AND;
267
+ if (!DELAY_CONDITION_MODE_AND.equals(conditionMode) && !DELAY_CONDITION_MODE_OR.equals(conditionMode)) {
268
+ logger.warn("Unknown delay condition mode '" + conditionMode + "', defaulting to '" + DELAY_CONDITION_MODE_AND + "'");
269
+ }
270
+ this.editor.putString(DELAY_CONDITION_MODE_PREFERENCES, normalized);
271
+ if (!this.editor.commit()) {
272
+ logger.error("Failed to save delay condition mode: commit returned false");
273
+ return false;
274
+ }
275
+ logger.info("Delay condition mode saved: " + normalized);
276
+ return true;
277
+ } catch (final Exception e) {
278
+ logger.error("Failed to save delay condition mode: " + e.getMessage());
279
+ return false;
164
280
  }
165
281
  }
166
282
 
@@ -255,7 +371,10 @@ public class DelayUpdateUtils {
255
371
  public Boolean setMultiDelay(String delayConditions) {
256
372
  try {
257
373
  this.editor.putString(DELAY_CONDITION_PREFERENCES, delayConditions);
258
- this.editor.commit();
374
+ if (!this.editor.commit()) {
375
+ logger.error("Failed to delay update: commit returned false");
376
+ return false;
377
+ }
259
378
  logger.info("Delay update saved");
260
379
  return true;
261
380
  } catch (final Exception e) {
@@ -296,6 +415,7 @@ public class DelayUpdateUtils {
296
415
  public boolean cancelDelay(String source) {
297
416
  try {
298
417
  this.editor.remove(DELAY_CONDITION_PREFERENCES);
418
+ this.editor.remove(DELAY_CONDITION_MODE_PREFERENCES);
299
419
  this.editor.commit();
300
420
  logger.info("All delays canceled from " + source);
301
421
  return true;
@@ -15,7 +15,6 @@ import java.io.*;
15
15
  import java.io.FileInputStream;
16
16
  import java.net.HttpURLConnection;
17
17
  import java.net.MalformedURLException;
18
- import java.net.URL;
19
18
  import java.nio.channels.FileChannel;
20
19
  import java.security.MessageDigest;
21
20
  import java.util.ArrayList;
@@ -35,7 +34,9 @@ import java.util.function.BooleanSupplier;
35
34
  import java.util.function.LongConsumer;
36
35
  import okhttp3.Call;
37
36
  import okhttp3.Callback;
37
+ import okhttp3.CookieJar;
38
38
  import okhttp3.Dispatcher;
39
+ import okhttp3.HttpUrl;
39
40
  import okhttp3.Interceptor;
40
41
  import okhttp3.MediaType;
41
42
  import okhttp3.OkHttpClient;
@@ -50,6 +51,14 @@ import org.json.JSONObject;
50
51
 
51
52
  public class DownloadService extends Worker {
52
53
 
54
+ /** A refused HTTPS to HTTP redirect. Permanent for the given URL, so downloads must not retry it. */
55
+ static final class BlockedRedirectException extends IOException {
56
+
57
+ BlockedRedirectException() {
58
+ super("Blocked HTTPS to HTTP redirect; set allowHttpsToHttpRedirect to true to allow it");
59
+ }
60
+ }
61
+
53
62
  static final class DownloadRetryException extends RuntimeException {
54
63
 
55
64
  DownloadRetryException(String message) {
@@ -126,6 +135,8 @@ public class DownloadService extends Worker {
126
135
  // Match CapgoUpdater.timeout / responseTimeout default (20s). OkHttp's 10s
127
136
  // defaults were unused by the plugin config and aborted slow manifest GETs.
128
137
  private static volatile int httpTimeoutMs = 20_000;
138
+ // Off by default: a redirect must never downgrade updater traffic from HTTPS to plain HTTP.
139
+ private static volatile boolean allowHttpsToHttpRedirect = false;
129
140
  private static String currentAppId = "unknown";
130
141
  private static String currentPluginVersion = "unknown";
131
142
  private static String currentVersionOs = "unknown";
@@ -138,6 +149,9 @@ public class DownloadService extends Worker {
138
149
  sharedClient = new OkHttpClient.Builder()
139
150
  .dispatcher(dispatcher)
140
151
  .protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1))
152
+ // Never share cookies with Capgo endpoints: the app's java.net.CookieHandler default is
153
+ // Capacitor's WebView cookie manager, and it must not see (or be fed by) plugin traffic.
154
+ .cookieJar(CookieJar.NO_COOKIES)
141
155
  .connectTimeout(httpTimeoutMs, TimeUnit.MILLISECONDS)
142
156
  .readTimeout(httpTimeoutMs, TimeUnit.MILLISECONDS)
143
157
  .writeTimeout(httpTimeoutMs, TimeUnit.MILLISECONDS)
@@ -147,9 +161,33 @@ public class DownloadService extends Worker {
147
161
  Request requestWithUserAgent = originalRequest.newBuilder().header("User-Agent", userAgent).build();
148
162
  return chain.proceed(requestWithUserAgent);
149
163
  })
164
+ .addNetworkInterceptor((chain) -> {
165
+ Response response = chain.proceed(chain.request());
166
+ if (!allowHttpsToHttpRedirect && isHttpsToHttpRedirect(response)) {
167
+ response.close();
168
+ throw new BlockedRedirectException();
169
+ }
170
+ return response;
171
+ })
150
172
  .build();
151
173
  }
152
174
 
175
+ static void setAllowHttpsToHttpRedirect(boolean allow) {
176
+ allowHttpsToHttpRedirect = allow;
177
+ }
178
+
179
+ static boolean isHttpsToHttpRedirect(Response response) {
180
+ if (!response.isRedirect() || !response.request().isHttps()) {
181
+ return false;
182
+ }
183
+ String location = response.header("Location");
184
+ if (location == null) {
185
+ return false;
186
+ }
187
+ HttpUrl target = response.request().url().resolve(location);
188
+ return target != null && !target.isHttps();
189
+ }
190
+
153
191
  static int httpTimeoutMs() {
154
192
  return httpTimeoutMs;
155
193
  }
@@ -239,8 +277,21 @@ public class DownloadService extends Worker {
239
277
  }
240
278
 
241
279
  private Result createFailureResult(String error) {
242
- Data output = new Data.Builder().putString(ERROR, error).build();
243
- return Result.failure(output);
280
+ return createFailureResult(error, null, null, false);
281
+ }
282
+
283
+ private Result createFailureResult(String error, String version, String dest, boolean isManifest) {
284
+ Data.Builder builder = new Data.Builder().putString(ERROR, error);
285
+ if (version != null) {
286
+ builder.putString(VERSION, version);
287
+ }
288
+ if (dest != null) {
289
+ builder.putString(FILEDEST, dest);
290
+ }
291
+ if (isManifest) {
292
+ builder.putBoolean(IS_MANIFEST, true);
293
+ }
294
+ return Result.failure(builder.build());
244
295
  }
245
296
 
246
297
  private Result createSuccessResult(String dest, String version, String sessionKey, String checksum, boolean isManifest) {
@@ -431,16 +482,16 @@ public class DownloadService extends Worker {
431
482
  @NonNull
432
483
  @Override
433
484
  public Result doWork() {
485
+ final String documentsDir = getInputData().getString(DOCDIR);
486
+ final String dest = getInputData().getString(FILEDEST);
487
+ final String version = getInputData().getString(VERSION);
488
+ final boolean isManifest = getInputData().getBoolean(IS_MANIFEST, false);
434
489
  try {
435
490
  String url = getInputData().getString(URL);
436
491
  String id = getInputData().getString(ID);
437
- String documentsDir = getInputData().getString(DOCDIR);
438
- String dest = getInputData().getString(FILEDEST);
439
- String version = getInputData().getString(VERSION);
440
492
  String sessionKey = getInputData().getString(SESSIONKEY);
441
493
  String checksum = getInputData().getString(CHECKSUM);
442
494
  String publicKey = getInputData().getString(PUBLIC_KEY);
443
- boolean isManifest = getInputData().getBoolean(IS_MANIFEST, false);
444
495
 
445
496
  logger.debug("doWork isManifest: " + isManifest);
446
497
 
@@ -450,10 +501,12 @@ public class DownloadService extends Worker {
450
501
  handleManifestDownload(id, documentsDir, dest, version, sessionKey, publicKey, manifest);
451
502
  return createSuccessResult(dest, version, sessionKey, checksum, true);
452
503
  } else if (isStopped()) {
453
- return createFailureResult("download_cancelled");
504
+ CapgoUpdater.deleteManifestStagingFolderAt(documentsDir != null ? new File(documentsDir) : null, dest, logger);
505
+ return createFailureResult("download_cancelled", version, dest, true);
454
506
  } else {
455
507
  logger.error("Manifest is null");
456
- return createFailureResult("Manifest is null");
508
+ CapgoUpdater.deleteManifestStagingFolderAt(documentsDir != null ? new File(documentsDir) : null, dest, logger);
509
+ return createFailureResult("Manifest is null", version, dest, true);
457
510
  }
458
511
  } else {
459
512
  handleSingleFileDownload(url, id, documentsDir, dest, version, sessionKey, checksum, publicKey);
@@ -465,7 +518,10 @@ public class DownloadService extends Worker {
465
518
  }
466
519
  return Result.retry();
467
520
  } catch (Exception e) {
468
- return createFailureResult(e.getMessage());
521
+ if (isManifest) {
522
+ CapgoUpdater.deleteManifestStagingFolderAt(documentsDir != null ? new File(documentsDir) : null, dest, logger);
523
+ }
524
+ return createFailureResult(e.getMessage(), version, dest, isManifest);
469
525
  }
470
526
  }
471
527
 
@@ -768,20 +824,16 @@ public class DownloadService extends Worker {
768
824
  throw new RuntimeException("insufficient_disk_space");
769
825
  }
770
826
 
771
- HttpURLConnection httpConn = null;
827
+ Response response = null;
772
828
  InputStream inputStream = null;
773
829
  BufferedReader reader = null;
774
830
  BufferedWriter writer = null;
775
831
 
776
832
  try {
777
- URL u = new URL(url);
778
- httpConn = (HttpURLConnection) u.openConnection();
779
-
780
- // Zip can stall longer than a JSON API call; keep a floor so
781
- // responseTimeout cannot shrink large-bundle downloads.
782
- int zipTimeoutMs = Math.max(httpTimeoutMs, 60_000);
783
- httpConn.setConnectTimeout(zipTimeoutMs);
784
- httpConn.setReadTimeout(zipTimeoutMs);
833
+ HttpUrl zipUrl = url != null ? HttpUrl.parse(url) : null;
834
+ if (zipUrl == null) {
835
+ throw new MalformedURLException("Expected an http or https URL");
836
+ }
785
837
 
786
838
  // Reading progress file (if exist)
787
839
  long downloadedBytes = 0;
@@ -810,15 +862,16 @@ public class DownloadService extends Worker {
810
862
  throw new DownloadRetryException("download_stopped");
811
863
  }
812
864
 
813
- if (downloadedBytes > 0) {
814
- httpConn.setRequestProperty("Range", "bytes=" + downloadedBytes + "-");
815
- }
816
-
817
- int responseCode = httpConn.getResponseCode();
865
+ response = executeZipRequest(zipUrl, downloadedBytes);
866
+ int responseCode = response.code();
818
867
 
819
868
  if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL) {
820
- ZipWritePlan writePlan = planZipResumeWrite(responseCode, downloadedBytes, httpConn.getHeaderField("Content-Range"));
821
- long responseBodyLength = httpConn.getContentLength();
869
+ ResponseBody responseBody = response.body();
870
+ if (responseBody == null) {
871
+ throw new IOException("Response body is null");
872
+ }
873
+ ZipWritePlan writePlan = planZipResumeWrite(responseCode, downloadedBytes, response.header("Content-Range"));
874
+ long responseBodyLength = responseBody.contentLength();
822
875
  long contentLength = shouldAppendHttpBody(writePlan.statusCode, writePlan.writeOffset)
823
876
  ? responseBodyLength >= 0
824
877
  ? responseBodyLength + writePlan.writeOffset
@@ -831,7 +884,7 @@ public class DownloadService extends Worker {
831
884
  }
832
885
 
833
886
  try {
834
- inputStream = httpConn.getInputStream();
887
+ inputStream = responseBody.byteStream();
835
888
 
836
889
  if (writePlan.writeOffset == 0 && downloadedBytes == 0) {
837
890
  writer = new BufferedWriter(new FileWriter(infoFile));
@@ -842,7 +895,7 @@ public class DownloadService extends Worker {
842
895
 
843
896
  final int[] lastNotifiedPercent = { 0 };
844
897
  final long totalContentLength = contentLength;
845
- String contentRangeHeader = httpConn.getHeaderField("Content-Range");
898
+ String contentRangeHeader = response.header("Content-Range");
846
899
  writeHttpBody(tempFile, inputStream, writePlan.statusCode, writePlan.writeOffset, this::isStopped, (written) -> {
847
900
  int percent = calcTotalPercent(written, totalContentLength);
848
901
  if (percent >= lastNotifiedPercent[0] + 10) {
@@ -910,6 +963,9 @@ public class DownloadService extends Worker {
910
963
  } catch (MalformedURLException e) {
911
964
  logger.error("Invalid download URL: " + e.getMessage());
912
965
  throw new RuntimeException("invalid_url: " + e.getMessage());
966
+ } catch (BlockedRedirectException e) {
967
+ logger.error("Download error: " + e.getMessage());
968
+ throw new RuntimeException("blocked_redirect: " + e.getMessage());
913
969
  } catch (IOException e) {
914
970
  logger.error("Download error: " + e.getMessage());
915
971
  throw new DownloadRetryException(e.getMessage(), e);
@@ -918,14 +974,35 @@ public class DownloadService extends Worker {
918
974
  throw new RuntimeException(e.getMessage());
919
975
  } finally {
920
976
  // Ensure connection is closed
921
- if (httpConn != null) {
977
+ if (response != null) {
922
978
  try {
923
- httpConn.disconnect();
979
+ response.close();
924
980
  } catch (Exception ignored) {}
925
981
  }
926
982
  }
927
983
  }
928
984
 
985
+ /**
986
+ * Zip bundle request on the shared client (no cookies, same User-Agent), resuming from
987
+ * {@code downloadedBytes} with a Range header. The caller closes the response.
988
+ */
989
+ static Response executeZipRequest(HttpUrl url, long downloadedBytes) throws IOException {
990
+ // Zip can stall longer than a JSON API call; keep a floor so
991
+ // responseTimeout cannot shrink large-bundle downloads.
992
+ int zipTimeoutMs = Math.max(httpTimeoutMs, 60_000);
993
+ OkHttpClient zipClient = sharedClient
994
+ .newBuilder()
995
+ .connectTimeout(zipTimeoutMs, TimeUnit.MILLISECONDS)
996
+ .readTimeout(zipTimeoutMs, TimeUnit.MILLISECONDS)
997
+ .writeTimeout(zipTimeoutMs, TimeUnit.MILLISECONDS)
998
+ .build();
999
+ Request.Builder builder = new Request.Builder().url(url);
1000
+ if (downloadedBytes > 0) {
1001
+ builder.header("Range", "bytes=" + downloadedBytes + "-");
1002
+ }
1003
+ return zipClient.newCall(builder.build()).execute();
1004
+ }
1005
+
929
1006
  static boolean isRetryableHttpStatus(int responseCode) {
930
1007
  return responseCode >= 500 || responseCode == 408 || responseCode == 429;
931
1008
  }