@capgo/capacitor-updater 6.51.19 → 6.51.23

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;
@@ -327,6 +363,38 @@ public class DownloadService extends Worker {
327
363
  return seenTargets.add(targetFile.getCanonicalPath());
328
364
  }
329
365
 
366
+ private static final class ManifestDownloadTask {
367
+
368
+ final String fileName;
369
+ final String finalFileHash;
370
+ final String downloadUrl;
371
+ final boolean isBrotli;
372
+ final File targetFile;
373
+ final File builtinFile;
374
+ final File cacheFile;
375
+ final File legacyCacheFile;
376
+
377
+ ManifestDownloadTask(
378
+ final String fileName,
379
+ final String finalFileHash,
380
+ final String downloadUrl,
381
+ final boolean isBrotli,
382
+ final File targetFile,
383
+ final File builtinFile,
384
+ final File cacheFile,
385
+ final File legacyCacheFile
386
+ ) {
387
+ this.fileName = fileName;
388
+ this.finalFileHash = finalFileHash;
389
+ this.downloadUrl = downloadUrl;
390
+ this.isBrotli = isBrotli;
391
+ this.targetFile = targetFile;
392
+ this.builtinFile = builtinFile;
393
+ this.cacheFile = cacheFile;
394
+ this.legacyCacheFile = legacyCacheFile;
395
+ }
396
+ }
397
+
330
398
  static boolean tryCopyBuiltinAsset(final AssetManager assets, final String fileName, final File dest, final String expectedHash) {
331
399
  if (assets == null || fileName == null || dest == null) {
332
400
  return false;
@@ -388,9 +456,14 @@ public class DownloadService extends Worker {
388
456
  return createFailureResult("Manifest is null");
389
457
  }
390
458
  } else {
391
- handleSingleFileDownload(url, id, documentsDir, dest, version, sessionKey, checksum);
459
+ handleSingleFileDownload(url, id, documentsDir, dest, version, sessionKey, checksum, publicKey);
392
460
  return createSuccessResult(dest, version, sessionKey, checksum, false);
393
461
  }
462
+ } catch (DownloadRetryException e) {
463
+ if (logger != null) {
464
+ logger.debug("Download will retry: " + e.getMessage());
465
+ }
466
+ return Result.retry();
394
467
  } catch (Exception e) {
395
468
  return createFailureResult(e.getMessage());
396
469
  }
@@ -435,27 +508,26 @@ public class DownloadService extends Worker {
435
508
  .post(RequestBody.create(json.toString(), MediaType.get("application/json")))
436
509
  .build();
437
510
 
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
- }
511
+ sharedClient.newCall(request).enqueue(
512
+ new Callback() {
513
+ @Override
514
+ public void onFailure(@NonNull Call call, @NonNull IOException e) {
515
+ if (logger != null) {
516
+ logger.error("Failed to send stats: " + e.getMessage());
447
517
  }
518
+ }
448
519
 
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
- }
520
+ @Override
521
+ public void onResponse(@NonNull Call call, @NonNull Response response) {
522
+ try (ResponseBody body = response.body()) {
523
+ // nothing else to do, just closing body
524
+ } catch (Exception ignored) {
525
+ } finally {
526
+ response.close();
456
527
  }
457
528
  }
458
- );
529
+ }
530
+ );
459
531
  } catch (Exception e) {
460
532
  if (logger != null) {
461
533
  logger.error("sendStatsAsync error: " + e.getMessage());
@@ -475,6 +547,12 @@ public class DownloadService extends Worker {
475
547
  try {
476
548
  logger.debug("handleManifestDownload");
477
549
 
550
+ if (publicKey != null && !publicKey.isEmpty() && !CryptoCipher.isValidSessionKey(sessionKey)) {
551
+ logger.error("Public key present but no valid session key provided");
552
+ sendStatsAsync("session_key_required", version);
553
+ throw new IOException("Session key required when public key is present");
554
+ }
555
+
478
556
  // Send stats for manifest download start
479
557
  sendStatsAsync("download_manifest_start", version);
480
558
 
@@ -495,9 +573,7 @@ public class DownloadService extends Worker {
495
573
  int totalFiles = manifest.length();
496
574
  final AtomicLong completedFiles = new AtomicLong(0);
497
575
  final AtomicBoolean hasError = new AtomicBoolean(false);
498
-
499
- ExecutorService executor = Executors.newFixedThreadPool(Math.min(MANIFEST_MAX_CONCURRENT_FILES, Math.max(1, totalFiles)));
500
- List<Future<?>> futures = new ArrayList<>();
576
+ final List<ManifestDownloadTask> tasks = new ArrayList<>();
501
577
  final Set<String> seenTargets = new HashSet<>();
502
578
 
503
579
  for (int i = 0; i < totalFiles; i++) {
@@ -512,7 +588,13 @@ public class DownloadService extends Worker {
512
588
  continue;
513
589
  }
514
590
 
515
- if (publicKey != null && !publicKey.isEmpty() && sessionKey != null && !sessionKey.isEmpty()) {
591
+ if (publicKey != null && !publicKey.isEmpty()) {
592
+ if (!CryptoCipher.isValidSessionKey(sessionKey)) {
593
+ logger.error("Public key present but no valid session key provided");
594
+ sendStatsAsync("session_key_required", version);
595
+ hasError.set(true);
596
+ continue;
597
+ }
516
598
  try {
517
599
  fileHash = CryptoCipher.decryptChecksum(fileHash, publicKey);
518
600
  } catch (Exception e) {
@@ -549,39 +631,59 @@ public class DownloadService extends Worker {
549
631
  final File cacheFile = CapgoUpdater.isSafeCacheHash(finalFileHash)
550
632
  ? new File(cacheFolder, finalFileHash + "_" + cacheBaseName)
551
633
  : null;
552
- final File legacyCacheFile = isBrotli && cacheFile != null
553
- ? new File(cacheFolder, finalFileHash + "_" + new File(fileName).getName())
554
- : null;
634
+ final File legacyCacheFile =
635
+ isBrotli && cacheFile != null ? new File(cacheFolder, finalFileHash + "_" + new File(fileName).getName()) : null;
636
+
637
+ tasks.add(
638
+ new ManifestDownloadTask(
639
+ fileName,
640
+ finalFileHash,
641
+ downloadUrl,
642
+ isBrotli,
643
+ targetFile,
644
+ builtinFile,
645
+ cacheFile,
646
+ legacyCacheFile
647
+ )
648
+ );
649
+ }
555
650
 
556
- // Ensure parent directories of the target file exist
557
- if (!Objects.requireNonNull(targetFile.getParentFile()).exists() && !targetFile.getParentFile().mkdirs()) {
558
- logger.error("Failed to create parent directory for: " + targetFile.getAbsolutePath());
559
- hasError.set(true);
560
- continue;
651
+ if (hasError.get()) {
652
+ throw new IOException("Manifest contains invalid or duplicate file paths");
653
+ }
654
+
655
+ for (final ManifestDownloadTask task : tasks) {
656
+ if (!Objects.requireNonNull(task.targetFile.getParentFile()).exists() && !task.targetFile.getParentFile().mkdirs()) {
657
+ logger.error("Failed to create parent directory for: " + task.targetFile.getAbsolutePath());
658
+ throw new IOException("Failed to create parent directory for: " + task.targetFile.getAbsolutePath());
561
659
  }
660
+ }
661
+
662
+ ExecutorService executor = Executors.newFixedThreadPool(Math.min(MANIFEST_MAX_CONCURRENT_FILES, Math.max(1, totalFiles)));
663
+ List<Future<?>> futures = new ArrayList<>();
562
664
 
563
- final boolean finalIsBrotli = isBrotli;
665
+ for (final ManifestDownloadTask task : tasks) {
564
666
  Future<?> future = executor.submit(() -> {
565
667
  try {
566
- if (tryCopyBuiltinAsset(assets, fileName, targetFile, finalFileHash)) {
567
- logger.debug("using builtin asset " + fileName);
568
- } else if (tryCopyBuiltinFile(builtinFile, targetFile, finalFileHash)) {
569
- logger.debug("using builtin file " + fileName);
668
+ if (tryCopyBuiltinAsset(assets, task.fileName, task.targetFile, task.finalFileHash)) {
669
+ logger.debug("using builtin asset " + task.fileName);
670
+ } else if (tryCopyBuiltinFile(task.builtinFile, task.targetFile, task.finalFileHash)) {
671
+ logger.debug("using builtin file " + task.fileName);
570
672
  } else if (
571
- tryCopyFromCache(cacheFile, targetFile, finalFileHash) ||
572
- (legacyCacheFile != null && tryCopyFromCache(legacyCacheFile, targetFile, finalFileHash))
673
+ tryCopyFromCache(task.cacheFile, task.targetFile, task.finalFileHash) ||
674
+ (task.legacyCacheFile != null && tryCopyFromCache(task.legacyCacheFile, task.targetFile, task.finalFileHash))
573
675
  ) {
574
- logger.debug("already cached " + fileName);
676
+ logger.debug("already cached " + task.fileName);
575
677
  } else {
576
678
  downloadAndVerify(
577
- downloadUrl,
578
- targetFile,
579
- cacheFile,
580
- finalFileHash,
679
+ task.downloadUrl,
680
+ task.targetFile,
681
+ task.cacheFile,
682
+ task.finalFileHash,
581
683
  sessionKey,
582
684
  publicKey,
583
- finalIsBrotli,
584
- fileName
685
+ task.isBrotli,
686
+ task.fileName
585
687
  );
586
688
  }
587
689
 
@@ -589,8 +691,8 @@ public class DownloadService extends Worker {
589
691
  int percent = calcTotalPercent(completed, totalFiles);
590
692
  setProgress(percent);
591
693
  } catch (Exception e) {
592
- logger.error("Error processing file: " + fileName + " " + e.getMessage());
593
- sendStatsAsync("download_manifest_file_fail", version + ":" + fileName);
694
+ logger.error("Error processing file: " + task.fileName + " " + e.getMessage());
695
+ sendStatsAsync("download_manifest_file_fail", version + ":" + task.fileName);
594
696
  hasError.set(true);
595
697
  }
596
698
  });
@@ -637,8 +739,20 @@ public class DownloadService extends Worker {
637
739
  String dest,
638
740
  String version,
639
741
  String sessionKey,
640
- String checksum
742
+ String checksum,
743
+ String publicKey
641
744
  ) {
745
+ if (publicKey != null && !publicKey.isEmpty() && !CryptoCipher.isValidSessionKey(sessionKey)) {
746
+ logger.error("Public key present but no valid session key provided");
747
+ sendStatsAsync("session_key_required", version);
748
+ throw new RuntimeException("Session key required when public key is present");
749
+ }
750
+ if (checksum == null || checksum.isEmpty()) {
751
+ logger.error("No checksum provided");
752
+ sendStatsAsync("checksum_required", version);
753
+ throw new RuntimeException("Checksum required");
754
+ }
755
+
642
756
  // Send stats for zip download start
643
757
  sendStatsAsync("download_zip_start", version);
644
758
 
@@ -656,7 +770,6 @@ public class DownloadService extends Worker {
656
770
 
657
771
  HttpURLConnection httpConn = null;
658
772
  InputStream inputStream = null;
659
- FileOutputStream outputStream = null;
660
773
  BufferedReader reader = null;
661
774
  BufferedWriter writer = null;
662
775
 
@@ -693,6 +806,10 @@ public class DownloadService extends Worker {
693
806
  clearDownloadData(documentsDir, id);
694
807
  }
695
808
 
809
+ if (isStopped()) {
810
+ throw new DownloadRetryException("download_stopped");
811
+ }
812
+
696
813
  if (downloadedBytes > 0) {
697
814
  httpConn.setRequestProperty("Range", "bytes=" + downloadedBytes + "-");
698
815
  }
@@ -700,7 +817,13 @@ public class DownloadService extends Worker {
700
817
  int responseCode = httpConn.getResponseCode();
701
818
 
702
819
  if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL) {
703
- long contentLength = httpConn.getContentLength() + downloadedBytes;
820
+ ZipWritePlan writePlan = planZipResumeWrite(responseCode, downloadedBytes, httpConn.getHeaderField("Content-Range"));
821
+ long responseBodyLength = httpConn.getContentLength();
822
+ long contentLength = shouldAppendHttpBody(writePlan.statusCode, writePlan.writeOffset)
823
+ ? responseBodyLength >= 0
824
+ ? responseBodyLength + writePlan.writeOffset
825
+ : -1
826
+ : responseBodyLength;
704
827
 
705
828
  // Check if we have enough space for the actual file
706
829
  if (contentLength > 0 && availableSpace < contentLength * 2) {
@@ -709,44 +832,36 @@ public class DownloadService extends Worker {
709
832
 
710
833
  try {
711
834
  inputStream = httpConn.getInputStream();
712
- outputStream = new FileOutputStream(tempFile, downloadedBytes > 0);
713
835
 
714
- if (downloadedBytes == 0) {
836
+ if (writePlan.writeOffset == 0 && downloadedBytes == 0) {
715
837
  writer = new BufferedWriter(new FileWriter(infoFile));
716
838
  writer.write(String.valueOf(version));
717
839
  writer.close();
718
840
  writer = null;
719
841
  }
720
842
 
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();
843
+ final int[] lastNotifiedPercent = { 0 };
844
+ final long totalContentLength = contentLength;
845
+ String contentRangeHeader = httpConn.getHeaderField("Content-Range");
846
+ writeHttpBody(tempFile, inputStream, writePlan.statusCode, writePlan.writeOffset, this::isStopped, (written) -> {
847
+ int percent = calcTotalPercent(written, totalContentLength);
848
+ if (percent >= lastNotifiedPercent[0] + 10) {
849
+ lastNotifiedPercent[0] = (percent / 10) * 10;
850
+ setProgress(lastNotifiedPercent[0]);
732
851
  }
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;
852
+ });
746
853
 
747
854
  inputStream.close();
748
855
  inputStream = null;
749
856
 
857
+ validateZipDownloadComplete(
858
+ tempFile,
859
+ writePlan.statusCode,
860
+ contentRangeHeader,
861
+ writePlan.writeOffset,
862
+ responseBodyLength
863
+ );
864
+
750
865
  // Rename the temp file with the final name (dest)
751
866
  if (!tempFile.renameTo(new File(documentsDir, dest))) {
752
867
  throw new RuntimeException("Failed to rename temp file to final destination");
@@ -760,13 +875,12 @@ public class DownloadService extends Worker {
760
875
  // Try to free some memory
761
876
  System.gc();
762
877
  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) {}
878
+ } catch (IOException e) {
879
+ if ("download_stopped".equals(e.getMessage())) {
880
+ throw new DownloadRetryException("download_stopped", e);
769
881
  }
882
+ throw new DownloadRetryException(e.getMessage(), e);
883
+ } finally {
770
884
  if (inputStream != null) {
771
885
  try {
772
886
  inputStream.close();
@@ -778,10 +892,14 @@ public class DownloadService extends Worker {
778
892
  } catch (Exception ignored) {}
779
893
  }
780
894
  }
895
+ } else if (isRetryableHttpStatus(responseCode)) {
896
+ throw new DownloadRetryException("HTTP error: " + responseCode);
781
897
  } else {
782
898
  infoFile.delete();
783
899
  throw new RuntimeException("HTTP error: " + responseCode);
784
900
  }
901
+ } catch (DownloadRetryException e) {
902
+ throw e;
785
903
  } catch (OutOfMemoryError e) {
786
904
  logger.error("Critical memory error: " + e.getMessage());
787
905
  System.gc(); // Suggest garbage collection
@@ -789,6 +907,12 @@ public class DownloadService extends Worker {
789
907
  } catch (SecurityException e) {
790
908
  logger.error("Security error during download: " + e.getMessage());
791
909
  throw new RuntimeException("security_error: " + e.getMessage());
910
+ } catch (MalformedURLException e) {
911
+ logger.error("Invalid download URL: " + e.getMessage());
912
+ throw new RuntimeException("invalid_url: " + e.getMessage());
913
+ } catch (IOException e) {
914
+ logger.error("Download error: " + e.getMessage());
915
+ throw new DownloadRetryException(e.getMessage(), e);
792
916
  } catch (Exception e) {
793
917
  logger.error("Download error: " + e.getMessage());
794
918
  throw new RuntimeException(e.getMessage());
@@ -802,6 +926,93 @@ public class DownloadService extends Worker {
802
926
  }
803
927
  }
804
928
 
929
+ static boolean isRetryableHttpStatus(int responseCode) {
930
+ return responseCode >= 500 || responseCode == 408 || responseCode == 429;
931
+ }
932
+
933
+ static long parseContentRangeStart(String contentRange) {
934
+ ContentRangeInfo range = parseContentRange(contentRange);
935
+ return range == null ? -1 : range.start;
936
+ }
937
+
938
+ static ContentRangeInfo parseContentRange(String contentRange) {
939
+ if (contentRange == null || contentRange.isEmpty()) {
940
+ return null;
941
+ }
942
+ String trimmed = contentRange.trim();
943
+ if (!trimmed.startsWith("bytes ")) {
944
+ return null;
945
+ }
946
+ int slash = trimmed.indexOf('/');
947
+ if (slash < 0) {
948
+ return null;
949
+ }
950
+ int dash = trimmed.indexOf('-', 6);
951
+ if (dash < 0 || dash >= slash) {
952
+ return null;
953
+ }
954
+ try {
955
+ long start = Long.parseLong(trimmed.substring(6, dash).trim());
956
+ long end = Long.parseLong(trimmed.substring(dash + 1, slash).trim());
957
+ String totalPart = trimmed.substring(slash + 1).trim();
958
+ long total = "*".equals(totalPart) ? -1 : Long.parseLong(totalPart);
959
+ if (end < start) {
960
+ return null;
961
+ }
962
+ return new ContentRangeInfo(start, end, total);
963
+ } catch (NumberFormatException e) {
964
+ return null;
965
+ }
966
+ }
967
+
968
+ static void validateZipDownloadComplete(
969
+ File tempFile,
970
+ int responseCode,
971
+ String contentRangeHeader,
972
+ long writeOffset,
973
+ long responseBodyLength
974
+ ) {
975
+ long fileLen = tempFile.length();
976
+ if (responseCode == HttpURLConnection.HTTP_PARTIAL) {
977
+ ContentRangeInfo range = parseContentRange(contentRangeHeader);
978
+ if (range == null || range.total < 0) {
979
+ throw new DownloadRetryException("unknown_content_range_total");
980
+ }
981
+ if (range.start != writeOffset) {
982
+ throw new DownloadRetryException("content_range_mismatch");
983
+ }
984
+ long advertisedSpan = range.end - range.start + 1;
985
+ long receivedSpan = fileLen - writeOffset;
986
+ if (receivedSpan != advertisedSpan) {
987
+ throw new DownloadRetryException("incomplete_content_range");
988
+ }
989
+ if (fileLen != range.total) {
990
+ throw new DownloadRetryException("incomplete_download");
991
+ }
992
+ return;
993
+ }
994
+ if (responseBodyLength >= 0 && fileLen != responseBodyLength) {
995
+ throw new DownloadRetryException("incomplete_download");
996
+ }
997
+ }
998
+
999
+ static ZipWritePlan planZipResumeWrite(int responseCode, long downloadedBytes, String contentRange) {
1000
+ if (responseCode == HttpURLConnection.HTTP_PARTIAL) {
1001
+ long rangeStart = parseContentRangeStart(contentRange);
1002
+ if (rangeStart == downloadedBytes) {
1003
+ return new ZipWritePlan(HttpURLConnection.HTTP_PARTIAL, downloadedBytes);
1004
+ }
1005
+ if (rangeStart == 0) {
1006
+ return new ZipWritePlan(HttpURLConnection.HTTP_OK, 0);
1007
+ }
1008
+ throw new DownloadRetryException("invalid_content_range");
1009
+ }
1010
+ if (responseCode == HttpURLConnection.HTTP_OK && downloadedBytes > 0) {
1011
+ return new ZipWritePlan(HttpURLConnection.HTTP_OK, 0);
1012
+ }
1013
+ return new ZipWritePlan(responseCode, downloadedBytes);
1014
+ }
1015
+
805
1016
  private void clearDownloadData(String docDir, String id) {
806
1017
  File tempFile = new File(docDir, "temp_" + id + ".tmp");
807
1018
  File infoFile = new File(docDir, "update_" + id + ".dat");
@@ -925,7 +1136,7 @@ public class DownloadService extends Worker {
925
1136
  }
926
1137
  }
927
1138
 
928
- boolean needDecrypt = publicKey != null && !publicKey.isEmpty() && sessionKey != null && !sessionKey.isEmpty();
1139
+ boolean needDecrypt = publicKey != null && !publicKey.isEmpty() && CryptoCipher.isValidSessionKey(sessionKey);
929
1140
  File source = partial;
930
1141
  if (needDecrypt) {
931
1142
  workFile = new File(cacheFolder, "work_" + UUID.randomUUID() + "_" + targetFile.getName() + ".tmp");
@@ -999,17 +1210,44 @@ public class DownloadService extends Worker {
999
1210
  }
1000
1211
 
1001
1212
  static void writeHttpBody(File dest, InputStream body, int statusCode, long existingBytes) throws IOException {
1213
+ writeHttpBody(dest, body, statusCode, existingBytes, null, null);
1214
+ }
1215
+
1216
+ static void writeHttpBody(
1217
+ File dest,
1218
+ InputStream body,
1219
+ int statusCode,
1220
+ long existingBytes,
1221
+ BooleanSupplier shouldStop,
1222
+ LongConsumer onProgress
1223
+ ) throws IOException {
1224
+ if (shouldStop != null && shouldStop.getAsBoolean()) {
1225
+ throw new IOException("download_stopped");
1226
+ }
1002
1227
  boolean append = shouldAppendHttpBody(statusCode, existingBytes);
1003
1228
  byte[] buffer = new byte[CryptoCipher.ioBufferBytes()];
1004
1229
  try (FileOutputStream fos = new FileOutputStream(dest, append)) {
1005
1230
  int n;
1006
1231
  long written = append ? existingBytes : 0;
1007
- while ((n = body.read(buffer)) != -1) {
1232
+ while (true) {
1233
+ if (shouldStop != null && shouldStop.getAsBoolean()) {
1234
+ throw new IOException("download_stopped");
1235
+ }
1236
+ n = body.read(buffer);
1237
+ if (shouldStop != null && shouldStop.getAsBoolean()) {
1238
+ throw new IOException("download_stopped");
1239
+ }
1240
+ if (n == -1) {
1241
+ break;
1242
+ }
1008
1243
  fos.write(buffer, 0, n);
1009
1244
  written += n;
1010
1245
  if (written % (1024 * 1024) == 0) {
1011
1246
  fos.flush();
1012
1247
  }
1248
+ if (onProgress != null) {
1249
+ onProgress.accept(written);
1250
+ }
1013
1251
  }
1014
1252
  fos.flush();
1015
1253
  }
@@ -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) {