@capgo/capacitor-updater 6.51.19 → 6.51.21

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.
@@ -14,6 +14,7 @@ import androidx.work.WorkerParameters;
14
14
  import java.io.*;
15
15
  import java.io.FileInputStream;
16
16
  import java.net.HttpURLConnection;
17
+ import java.net.MalformedURLException;
17
18
  import java.net.URL;
18
19
  import java.nio.channels.FileChannel;
19
20
  import java.security.MessageDigest;
@@ -30,6 +31,8 @@ import java.util.concurrent.Future;
30
31
  import java.util.concurrent.TimeUnit;
31
32
  import java.util.concurrent.atomic.AtomicBoolean;
32
33
  import java.util.concurrent.atomic.AtomicLong;
34
+ import java.util.function.BooleanSupplier;
35
+ import java.util.function.LongConsumer;
33
36
  import okhttp3.Call;
34
37
  import okhttp3.Callback;
35
38
  import okhttp3.Dispatcher;
@@ -47,6 +50,41 @@ import org.json.JSONObject;
47
50
 
48
51
  public class DownloadService extends Worker {
49
52
 
53
+ static final class DownloadRetryException extends RuntimeException {
54
+
55
+ DownloadRetryException(String message) {
56
+ super(message);
57
+ }
58
+
59
+ DownloadRetryException(String message, Throwable cause) {
60
+ super(message, cause);
61
+ }
62
+ }
63
+
64
+ static final class ZipWritePlan {
65
+
66
+ final int statusCode;
67
+ final long writeOffset;
68
+
69
+ ZipWritePlan(int statusCode, long writeOffset) {
70
+ this.statusCode = statusCode;
71
+ this.writeOffset = writeOffset;
72
+ }
73
+ }
74
+
75
+ static final class ContentRangeInfo {
76
+
77
+ final long start;
78
+ final long end;
79
+ final long total;
80
+
81
+ ContentRangeInfo(long start, long end, long total) {
82
+ this.start = start;
83
+ this.end = end;
84
+ this.total = total;
85
+ }
86
+ }
87
+
50
88
  private static Logger logger;
51
89
 
52
90
  public static void setLogger(Logger loggerInstance) {
@@ -164,15 +202,13 @@ public class DownloadService extends Worker {
164
202
  }
165
203
 
166
204
  StringBuilder sanitized = new StringBuilder();
167
- value
168
- .codePoints()
169
- .forEach((cp) -> {
170
- boolean isVisibleAscii = cp >= 0x20 && cp <= 0x7E;
171
- boolean isIso88591 = cp >= 0xA0 && cp <= 0xFF;
172
- if (isVisibleAscii || isIso88591) {
173
- sanitized.appendCodePoint(cp);
174
- }
175
- });
205
+ value.codePoints().forEach((cp) -> {
206
+ boolean isVisibleAscii = cp >= 0x20 && cp <= 0x7E;
207
+ boolean isIso88591 = cp >= 0xA0 && cp <= 0xFF;
208
+ if (isVisibleAscii || isIso88591) {
209
+ sanitized.appendCodePoint(cp);
210
+ }
211
+ });
176
212
 
177
213
  String result = sanitized.toString().trim();
178
214
  return result.isEmpty() ? "unknown" : result;
@@ -391,6 +427,11 @@ public class DownloadService extends Worker {
391
427
  handleSingleFileDownload(url, id, documentsDir, dest, version, sessionKey, checksum);
392
428
  return createSuccessResult(dest, version, sessionKey, checksum, false);
393
429
  }
430
+ } catch (DownloadRetryException e) {
431
+ if (logger != null) {
432
+ logger.debug("Download will retry: " + e.getMessage());
433
+ }
434
+ return Result.retry();
394
435
  } catch (Exception e) {
395
436
  return createFailureResult(e.getMessage());
396
437
  }
@@ -435,27 +476,26 @@ public class DownloadService extends Worker {
435
476
  .post(RequestBody.create(json.toString(), MediaType.get("application/json")))
436
477
  .build();
437
478
 
438
- sharedClient
439
- .newCall(request)
440
- .enqueue(
441
- new Callback() {
442
- @Override
443
- public void onFailure(@NonNull Call call, @NonNull IOException e) {
444
- if (logger != null) {
445
- logger.error("Failed to send stats: " + e.getMessage());
446
- }
479
+ sharedClient.newCall(request).enqueue(
480
+ new Callback() {
481
+ @Override
482
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
483
+ if (logger != null) {
484
+ logger.error("Failed to send stats: " + e.getMessage());
447
485
  }
486
+ }
448
487
 
449
- @Override
450
- public void onResponse(@NonNull Call call, @NonNull Response response) {
451
- try (ResponseBody body = response.body()) {
452
- // nothing else to do, just closing body
453
- } catch (Exception ignored) {} finally {
454
- response.close();
455
- }
488
+ @Override
489
+ public void onResponse(@NonNull Call call, @NonNull Response response) {
490
+ try (ResponseBody body = response.body()) {
491
+ // nothing else to do, just closing body
492
+ } catch (Exception ignored) {
493
+ } finally {
494
+ response.close();
456
495
  }
457
496
  }
458
- );
497
+ }
498
+ );
459
499
  } catch (Exception e) {
460
500
  if (logger != null) {
461
501
  logger.error("sendStatsAsync error: " + e.getMessage());
@@ -549,9 +589,8 @@ public class DownloadService extends Worker {
549
589
  final File cacheFile = CapgoUpdater.isSafeCacheHash(finalFileHash)
550
590
  ? new File(cacheFolder, finalFileHash + "_" + cacheBaseName)
551
591
  : null;
552
- final File legacyCacheFile = isBrotli && cacheFile != null
553
- ? new File(cacheFolder, finalFileHash + "_" + new File(fileName).getName())
554
- : null;
592
+ final File legacyCacheFile =
593
+ isBrotli && cacheFile != null ? new File(cacheFolder, finalFileHash + "_" + new File(fileName).getName()) : null;
555
594
 
556
595
  // Ensure parent directories of the target file exist
557
596
  if (!Objects.requireNonNull(targetFile.getParentFile()).exists() && !targetFile.getParentFile().mkdirs()) {
@@ -656,7 +695,6 @@ public class DownloadService extends Worker {
656
695
 
657
696
  HttpURLConnection httpConn = null;
658
697
  InputStream inputStream = null;
659
- FileOutputStream outputStream = null;
660
698
  BufferedReader reader = null;
661
699
  BufferedWriter writer = null;
662
700
 
@@ -693,6 +731,10 @@ public class DownloadService extends Worker {
693
731
  clearDownloadData(documentsDir, id);
694
732
  }
695
733
 
734
+ if (isStopped()) {
735
+ throw new DownloadRetryException("download_stopped");
736
+ }
737
+
696
738
  if (downloadedBytes > 0) {
697
739
  httpConn.setRequestProperty("Range", "bytes=" + downloadedBytes + "-");
698
740
  }
@@ -700,7 +742,13 @@ public class DownloadService extends Worker {
700
742
  int responseCode = httpConn.getResponseCode();
701
743
 
702
744
  if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL) {
703
- long contentLength = httpConn.getContentLength() + downloadedBytes;
745
+ ZipWritePlan writePlan = planZipResumeWrite(responseCode, downloadedBytes, httpConn.getHeaderField("Content-Range"));
746
+ long responseBodyLength = httpConn.getContentLength();
747
+ long contentLength = shouldAppendHttpBody(writePlan.statusCode, writePlan.writeOffset)
748
+ ? responseBodyLength >= 0
749
+ ? responseBodyLength + writePlan.writeOffset
750
+ : -1
751
+ : responseBodyLength;
704
752
 
705
753
  // Check if we have enough space for the actual file
706
754
  if (contentLength > 0 && availableSpace < contentLength * 2) {
@@ -709,44 +757,36 @@ public class DownloadService extends Worker {
709
757
 
710
758
  try {
711
759
  inputStream = httpConn.getInputStream();
712
- outputStream = new FileOutputStream(tempFile, downloadedBytes > 0);
713
760
 
714
- if (downloadedBytes == 0) {
761
+ if (writePlan.writeOffset == 0 && downloadedBytes == 0) {
715
762
  writer = new BufferedWriter(new FileWriter(infoFile));
716
763
  writer.write(String.valueOf(version));
717
764
  writer.close();
718
765
  writer = null;
719
766
  }
720
767
 
721
- byte[] buffer = new byte[CryptoCipher.ioBufferBytes()];
722
- int lastNotifiedPercent = 0;
723
- int bytesRead;
724
-
725
- while ((bytesRead = inputStream.read(buffer)) != -1) {
726
- outputStream.write(buffer, 0, bytesRead);
727
- downloadedBytes += bytesRead;
728
-
729
- // Flush every 1MB to ensure progress is saved
730
- if (downloadedBytes % (1024 * 1024) == 0) {
731
- outputStream.flush();
768
+ final int[] lastNotifiedPercent = { 0 };
769
+ final long totalContentLength = contentLength;
770
+ String contentRangeHeader = httpConn.getHeaderField("Content-Range");
771
+ writeHttpBody(tempFile, inputStream, writePlan.statusCode, writePlan.writeOffset, this::isStopped, (written) -> {
772
+ int percent = calcTotalPercent(written, totalContentLength);
773
+ if (percent >= lastNotifiedPercent[0] + 10) {
774
+ lastNotifiedPercent[0] = (percent / 10) * 10;
775
+ setProgress(lastNotifiedPercent[0]);
732
776
  }
733
-
734
- // Computing percentage
735
- int percent = calcTotalPercent(downloadedBytes, contentLength);
736
- if (percent >= lastNotifiedPercent + 10) {
737
- lastNotifiedPercent = (percent / 10) * 10;
738
- setProgress(lastNotifiedPercent);
739
- }
740
- }
741
-
742
- // Final flush
743
- outputStream.flush();
744
- outputStream.close();
745
- outputStream = null;
777
+ });
746
778
 
747
779
  inputStream.close();
748
780
  inputStream = null;
749
781
 
782
+ validateZipDownloadComplete(
783
+ tempFile,
784
+ writePlan.statusCode,
785
+ contentRangeHeader,
786
+ writePlan.writeOffset,
787
+ responseBodyLength
788
+ );
789
+
750
790
  // Rename the temp file with the final name (dest)
751
791
  if (!tempFile.renameTo(new File(documentsDir, dest))) {
752
792
  throw new RuntimeException("Failed to rename temp file to final destination");
@@ -760,13 +800,12 @@ public class DownloadService extends Worker {
760
800
  // Try to free some memory
761
801
  System.gc();
762
802
  throw new RuntimeException("low_mem_fail");
763
- } finally {
764
- // Ensure all resources are closed
765
- if (outputStream != null) {
766
- try {
767
- outputStream.close();
768
- } catch (Exception ignored) {}
803
+ } catch (IOException e) {
804
+ if ("download_stopped".equals(e.getMessage())) {
805
+ throw new DownloadRetryException("download_stopped", e);
769
806
  }
807
+ throw new DownloadRetryException(e.getMessage(), e);
808
+ } finally {
770
809
  if (inputStream != null) {
771
810
  try {
772
811
  inputStream.close();
@@ -778,10 +817,14 @@ public class DownloadService extends Worker {
778
817
  } catch (Exception ignored) {}
779
818
  }
780
819
  }
820
+ } else if (isRetryableHttpStatus(responseCode)) {
821
+ throw new DownloadRetryException("HTTP error: " + responseCode);
781
822
  } else {
782
823
  infoFile.delete();
783
824
  throw new RuntimeException("HTTP error: " + responseCode);
784
825
  }
826
+ } catch (DownloadRetryException e) {
827
+ throw e;
785
828
  } catch (OutOfMemoryError e) {
786
829
  logger.error("Critical memory error: " + e.getMessage());
787
830
  System.gc(); // Suggest garbage collection
@@ -789,6 +832,12 @@ public class DownloadService extends Worker {
789
832
  } catch (SecurityException e) {
790
833
  logger.error("Security error during download: " + e.getMessage());
791
834
  throw new RuntimeException("security_error: " + e.getMessage());
835
+ } catch (MalformedURLException e) {
836
+ logger.error("Invalid download URL: " + e.getMessage());
837
+ throw new RuntimeException("invalid_url: " + e.getMessage());
838
+ } catch (IOException e) {
839
+ logger.error("Download error: " + e.getMessage());
840
+ throw new DownloadRetryException(e.getMessage(), e);
792
841
  } catch (Exception e) {
793
842
  logger.error("Download error: " + e.getMessage());
794
843
  throw new RuntimeException(e.getMessage());
@@ -802,6 +851,93 @@ public class DownloadService extends Worker {
802
851
  }
803
852
  }
804
853
 
854
+ static boolean isRetryableHttpStatus(int responseCode) {
855
+ return responseCode >= 500 || responseCode == 408 || responseCode == 429;
856
+ }
857
+
858
+ static long parseContentRangeStart(String contentRange) {
859
+ ContentRangeInfo range = parseContentRange(contentRange);
860
+ return range == null ? -1 : range.start;
861
+ }
862
+
863
+ static ContentRangeInfo parseContentRange(String contentRange) {
864
+ if (contentRange == null || contentRange.isEmpty()) {
865
+ return null;
866
+ }
867
+ String trimmed = contentRange.trim();
868
+ if (!trimmed.startsWith("bytes ")) {
869
+ return null;
870
+ }
871
+ int slash = trimmed.indexOf('/');
872
+ if (slash < 0) {
873
+ return null;
874
+ }
875
+ int dash = trimmed.indexOf('-', 6);
876
+ if (dash < 0 || dash >= slash) {
877
+ return null;
878
+ }
879
+ try {
880
+ long start = Long.parseLong(trimmed.substring(6, dash).trim());
881
+ long end = Long.parseLong(trimmed.substring(dash + 1, slash).trim());
882
+ String totalPart = trimmed.substring(slash + 1).trim();
883
+ long total = "*".equals(totalPart) ? -1 : Long.parseLong(totalPart);
884
+ if (end < start) {
885
+ return null;
886
+ }
887
+ return new ContentRangeInfo(start, end, total);
888
+ } catch (NumberFormatException e) {
889
+ return null;
890
+ }
891
+ }
892
+
893
+ static void validateZipDownloadComplete(
894
+ File tempFile,
895
+ int responseCode,
896
+ String contentRangeHeader,
897
+ long writeOffset,
898
+ long responseBodyLength
899
+ ) {
900
+ long fileLen = tempFile.length();
901
+ if (responseCode == HttpURLConnection.HTTP_PARTIAL) {
902
+ ContentRangeInfo range = parseContentRange(contentRangeHeader);
903
+ if (range == null || range.total < 0) {
904
+ throw new DownloadRetryException("unknown_content_range_total");
905
+ }
906
+ if (range.start != writeOffset) {
907
+ throw new DownloadRetryException("content_range_mismatch");
908
+ }
909
+ long advertisedSpan = range.end - range.start + 1;
910
+ long receivedSpan = fileLen - writeOffset;
911
+ if (receivedSpan != advertisedSpan) {
912
+ throw new DownloadRetryException("incomplete_content_range");
913
+ }
914
+ if (fileLen != range.total) {
915
+ throw new DownloadRetryException("incomplete_download");
916
+ }
917
+ return;
918
+ }
919
+ if (responseBodyLength >= 0 && fileLen != responseBodyLength) {
920
+ throw new DownloadRetryException("incomplete_download");
921
+ }
922
+ }
923
+
924
+ static ZipWritePlan planZipResumeWrite(int responseCode, long downloadedBytes, String contentRange) {
925
+ if (responseCode == HttpURLConnection.HTTP_PARTIAL) {
926
+ long rangeStart = parseContentRangeStart(contentRange);
927
+ if (rangeStart == downloadedBytes) {
928
+ return new ZipWritePlan(HttpURLConnection.HTTP_PARTIAL, downloadedBytes);
929
+ }
930
+ if (rangeStart == 0) {
931
+ return new ZipWritePlan(HttpURLConnection.HTTP_OK, 0);
932
+ }
933
+ throw new DownloadRetryException("invalid_content_range");
934
+ }
935
+ if (responseCode == HttpURLConnection.HTTP_OK && downloadedBytes > 0) {
936
+ return new ZipWritePlan(HttpURLConnection.HTTP_OK, 0);
937
+ }
938
+ return new ZipWritePlan(responseCode, downloadedBytes);
939
+ }
940
+
805
941
  private void clearDownloadData(String docDir, String id) {
806
942
  File tempFile = new File(docDir, "temp_" + id + ".tmp");
807
943
  File infoFile = new File(docDir, "update_" + id + ".dat");
@@ -999,17 +1135,44 @@ public class DownloadService extends Worker {
999
1135
  }
1000
1136
 
1001
1137
  static void writeHttpBody(File dest, InputStream body, int statusCode, long existingBytes) throws IOException {
1138
+ writeHttpBody(dest, body, statusCode, existingBytes, null, null);
1139
+ }
1140
+
1141
+ static void writeHttpBody(
1142
+ File dest,
1143
+ InputStream body,
1144
+ int statusCode,
1145
+ long existingBytes,
1146
+ BooleanSupplier shouldStop,
1147
+ LongConsumer onProgress
1148
+ ) throws IOException {
1149
+ if (shouldStop != null && shouldStop.getAsBoolean()) {
1150
+ throw new IOException("download_stopped");
1151
+ }
1002
1152
  boolean append = shouldAppendHttpBody(statusCode, existingBytes);
1003
1153
  byte[] buffer = new byte[CryptoCipher.ioBufferBytes()];
1004
1154
  try (FileOutputStream fos = new FileOutputStream(dest, append)) {
1005
1155
  int n;
1006
1156
  long written = append ? existingBytes : 0;
1007
- while ((n = body.read(buffer)) != -1) {
1157
+ while (true) {
1158
+ if (shouldStop != null && shouldStop.getAsBoolean()) {
1159
+ throw new IOException("download_stopped");
1160
+ }
1161
+ n = body.read(buffer);
1162
+ if (shouldStop != null && shouldStop.getAsBoolean()) {
1163
+ throw new IOException("download_stopped");
1164
+ }
1165
+ if (n == -1) {
1166
+ break;
1167
+ }
1008
1168
  fos.write(buffer, 0, n);
1009
1169
  written += n;
1010
1170
  if (written % (1024 * 1024) == 0) {
1011
1171
  fos.flush();
1012
1172
  }
1173
+ if (onProgress != null) {
1174
+ onProgress.accept(written);
1175
+ }
1013
1176
  }
1014
1177
  fos.flush();
1015
1178
  }
@@ -98,7 +98,18 @@ public class Logger {
98
98
  this.level = options.level;
99
99
  this.useSystemLog = options.useSystemLog;
100
100
  this.labels.putAll(
101
- Map.of(LogLevel.silent, "", LogLevel.error, "🔴", LogLevel.warn, "🟠", LogLevel.info, "🟢", LogLevel.debug, "\uD83D\uDD0E")
101
+ Map.of(
102
+ LogLevel.silent,
103
+ "",
104
+ LogLevel.error,
105
+ "\uD83D\uDD34",
106
+ LogLevel.warn,
107
+ "\uD83D\uDFE0",
108
+ LogLevel.info,
109
+ "\uD83D\uDFE2",
110
+ LogLevel.debug,
111
+ "\uD83D\uDD0E"
112
+ )
102
113
  );
103
114
 
104
115
  if (options.labels != null) {
@@ -233,8 +233,7 @@ public class ShakeMenu implements ShakeDetector.Listener, ThreeFingerPinchDetect
233
233
  isShowing = false;
234
234
  });
235
235
  }
236
- })
237
- .start();
236
+ }).start();
238
237
  }
239
238
 
240
239
  private void setPreviewMenuButtonsEnabled(List<Button> buttons, boolean enabled) {
@@ -383,8 +382,7 @@ public class ShakeMenu implements ShakeDetector.Listener, ThreeFingerPinchDetect
383
382
  } finally {
384
383
  isShowing = false;
385
384
  }
386
- })
387
- .start();
385
+ }).start();
388
386
  }
389
387
 
390
388
  private void showConfiguredDefaultMenu() {
@@ -571,8 +569,7 @@ public class ShakeMenu implements ShakeDetector.Listener, ThreeFingerPinchDetect
571
569
  presentChannelPicker(channels);
572
570
  });
573
571
  });
574
- })
575
- .start();
572
+ }).start();
576
573
  } catch (Exception e) {
577
574
  logger.error("Error showing channel selector: " + e.getMessage());
578
575
  isShowing = false;
@@ -765,11 +762,12 @@ public class ShakeMenu implements ShakeDetector.Listener, ThreeFingerPinchDetect
765
762
  String latestKind = getString(latestRes, "kind");
766
763
  String latestMessage = getString(latestRes, "message");
767
764
 
768
- String detail = latestMessage != null && !latestMessage.isEmpty()
769
- ? latestMessage
770
- : latestError != null && !latestError.isEmpty()
771
- ? latestError
772
- : latestKind != null && !latestKind.isEmpty()
765
+ String detail =
766
+ latestMessage != null && !latestMessage.isEmpty()
767
+ ? latestMessage
768
+ : latestError != null && !latestError.isEmpty()
769
+ ? latestError
770
+ : latestKind != null && !latestKind.isEmpty()
773
771
  ? latestKind
774
772
  : "server did not provide a message";
775
773
 
@@ -837,9 +835,8 @@ public class ShakeMenu implements ShakeDetector.Listener, ThreeFingerPinchDetect
837
835
 
838
836
  // A manifest-only response has no zip URL; downloadManifest
839
837
  // tolerates the placeholder URL the plugin already uses.
840
- final String downloadUrl = latestUrl == null || latestUrl.isEmpty()
841
- ? "https://404.capgo.app/no.zip"
842
- : latestUrl;
838
+ final String downloadUrl =
839
+ latestUrl == null || latestUrl.isEmpty() ? "https://404.capgo.app/no.zip" : latestUrl;
843
840
 
844
841
  // Download the update
845
842
  try {
@@ -896,8 +893,7 @@ public class ShakeMenu implements ShakeDetector.Listener, ThreeFingerPinchDetect
896
893
  });
897
894
  }
898
895
  );
899
- })
900
- .start();
896
+ }).start();
901
897
  } catch (Exception e) {
902
898
  logger.error("Error selecting channel: " + e.getMessage());
903
899
  isShowing = false;
@@ -15,13 +15,13 @@ if (isBrowser) {
15
15
  return true;
16
16
  }
17
17
  }
18
- catch (err) {
18
+ catch (_a) {
19
19
  // ignore access issues
20
20
  }
21
21
  try {
22
22
  return window.localStorage.getItem(KEEP_FLAG_KEY) === '1';
23
23
  }
24
- catch (err) {
24
+ catch (_b) {
25
25
  return false;
26
26
  }
27
27
  };
@@ -37,7 +37,7 @@ if (isBrowser) {
37
37
  }
38
38
  return parsed;
39
39
  }
40
- catch (err) {
40
+ catch (_a) {
41
41
  return { stack: [], index: -1 };
42
42
  }
43
43
  };
@@ -45,7 +45,7 @@ if (isBrowser) {
45
45
  try {
46
46
  window.sessionStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify({ stack, index }));
47
47
  }
48
- catch (err) {
48
+ catch (_a) {
49
49
  // Storage might be unavailable; fail silently.
50
50
  }
51
51
  };
@@ -53,7 +53,7 @@ if (isBrowser) {
53
53
  try {
54
54
  window.sessionStorage.removeItem(HISTORY_STORAGE_KEY);
55
55
  }
56
- catch (err) {
56
+ catch (_a) {
57
57
  // ignore
58
58
  }
59
59
  };
@@ -63,7 +63,7 @@ if (isBrowser) {
63
63
  const parsed = new URL(base instanceof URL ? base.toString() : base, window.location.href);
64
64
  return `${parsed.pathname}${parsed.search}${parsed.hash}`;
65
65
  }
66
- catch (err) {
66
+ catch (_a) {
67
67
  return null;
68
68
  }
69
69
  };
@@ -168,7 +168,7 @@ if (isBrowser) {
168
168
  history.pushState(history.state, document.title, stored.stack[i]);
169
169
  }
170
170
  }
171
- catch (err) {
171
+ catch (_a) {
172
172
  isRestoring = false;
173
173
  return;
174
174
  }