capacitor-background-transfer 0.0.0-stage → 0.2.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 (60) hide show
  1. package/CapacitorBackgroundTransfer.podspec +19 -0
  2. package/LICENSE +21 -0
  3. package/Package.swift +31 -0
  4. package/README.md +552 -2
  5. package/android/build.gradle +71 -0
  6. package/android/src/main/AndroidManifest.xml +20 -0
  7. package/android/src/main/java/io/github/sandman92/backgroundtransfer/AzureBlockUploader.java +148 -0
  8. package/android/src/main/java/io/github/sandman92/backgroundtransfer/BackgroundTransferPlugin.java +279 -0
  9. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Downloader.java +244 -0
  10. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Http.java +238 -0
  11. package/android/src/main/java/io/github/sandman92/backgroundtransfer/JobRuns.java +40 -0
  12. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Notifications.java +54 -0
  13. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Parts.java +25 -0
  14. package/android/src/main/java/io/github/sandman92/backgroundtransfer/PartsXml.java +199 -0
  15. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Pause.java +28 -0
  16. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Progress.java +13 -0
  17. package/android/src/main/java/io/github/sandman92/backgroundtransfer/PutUploader.java +47 -0
  18. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Runner.java +369 -0
  19. package/android/src/main/java/io/github/sandman92/backgroundtransfer/S3MultipartUploader.java +143 -0
  20. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Scheduler.java +144 -0
  21. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferException.java +65 -0
  22. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferJobService.java +115 -0
  23. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferPaths.java +129 -0
  24. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferRecord.java +163 -0
  25. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferStore.java +121 -0
  26. package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferWorker.java +85 -0
  27. package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadAdapter.java +11 -0
  28. package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadAdapters.java +89 -0
  29. package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadOptionsCheck.java +104 -0
  30. package/android/src/main/java/io/github/sandman92/backgroundtransfer/Uploader.java +225 -0
  31. package/android/src/main/res/.gitkeep +0 -0
  32. package/dist/docs.json +527 -0
  33. package/dist/esm/definitions.d.ts +277 -0
  34. package/dist/esm/definitions.js +24 -0
  35. package/dist/esm/definitions.js.map +1 -0
  36. package/dist/esm/index.d.ts +10 -0
  37. package/dist/esm/index.js +26 -0
  38. package/dist/esm/index.js.map +1 -0
  39. package/dist/esm/validate.d.ts +18 -0
  40. package/dist/esm/validate.js +113 -0
  41. package/dist/esm/validate.js.map +1 -0
  42. package/dist/esm/web.d.ts +17 -0
  43. package/dist/esm/web.js +27 -0
  44. package/dist/esm/web.js.map +1 -0
  45. package/dist/plugin.cjs.js +200 -0
  46. package/dist/plugin.cjs.js.map +1 -0
  47. package/dist/plugin.js +203 -0
  48. package/dist/plugin.js.map +1 -0
  49. package/ios/Sources/BackgroundTransferCore/Files.swift +166 -0
  50. package/ios/Sources/BackgroundTransferCore/PartsUpload.swift +327 -0
  51. package/ios/Sources/BackgroundTransferCore/PartsXML.swift +137 -0
  52. package/ios/Sources/BackgroundTransferCore/TransferPaths.swift +103 -0
  53. package/ios/Sources/BackgroundTransferCore/TransferRecord.swift +141 -0
  54. package/ios/Sources/BackgroundTransferCore/TransferStore.swift +69 -0
  55. package/ios/Sources/BackgroundTransferCore/UploadOptionsCheck.swift +90 -0
  56. package/ios/Sources/BackgroundTransferCore/UploadOutcome.swift +96 -0
  57. package/ios/Sources/BackgroundTransferCore/UploadProtocol.swift +30 -0
  58. package/ios/Sources/BackgroundTransferPlugin/BackgroundTransferPlugin.swift +168 -0
  59. package/ios/Sources/BackgroundTransferPlugin/TransferManager.swift +1074 -0
  60. package/package.json +97 -4
@@ -0,0 +1,143 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.io.File;
4
+ import java.util.Map;
5
+ import java.util.TreeMap;
6
+
7
+ /**
8
+ * An S3 multipart upload the app has created, with every part URL, the completion URL and
9
+ * optionally a ListParts URL presigned up front. Sends the parts one at a time from the file in
10
+ * place, keeps each {@code ETag} on the record, skips the parts already stored when it resumes
11
+ * (asking ListParts when it has the URL, trusting its record otherwise), then completes the upload
12
+ * listing every part. Finished only when S3 answers the completion with the completed object.
13
+ */
14
+ final class S3MultipartUploader implements UploadAdapter {
15
+
16
+ private final int retries;
17
+ private final long backoffMillis;
18
+
19
+ S3MultipartUploader(int retries, long backoffMillis) {
20
+ this.retries = retries;
21
+ this.backoffMillis = backoffMillis;
22
+ }
23
+
24
+ @Override
25
+ public long run(TransferRecord r, Progress progress) throws TransferException {
26
+ return UploadAdapters.withRetries(retries, backoffMillis, progress, () -> attempt(r, progress));
27
+ }
28
+
29
+ private static long attempt(TransferRecord r, Progress progress) throws TransferException {
30
+ File file = UploadAdapters.fileOf(r);
31
+ long total = file.length();
32
+ if (r.committing) throw UploadAdapters.commitUnconfirmed("the completion");
33
+ long partSize = r.partSize > 0 ? r.partSize : UploadOptionsCheck.DEFAULT_PART_SIZE;
34
+ int count = Parts.count(total, partSize, true);
35
+ String bad = UploadOptionsCheck.checkSize(UploadAdapters.S3_MULTIPART, r.partUrls.size(), partSize, 0, total);
36
+ if (bad != null) throw new TransferException(TransferException.Reason.SIZE_MISMATCH, bad);
37
+ if (r.listPartsUrl != null) {
38
+ r.parts = held(r, progress, total, partSize, count);
39
+ progress.saveState();
40
+ }
41
+ long stored = 0;
42
+ for (int n : r.parts.keySet()) if (n <= count) stored += Parts.length(n, total, partSize);
43
+ progress.onBytes(UploadAdapters.pending(stored, total), total);
44
+ for (int n = 1; n <= count; n++) {
45
+ if (r.parts.containsKey(n)) continue;
46
+ Pause.check(progress);
47
+ final long base = stored;
48
+ long length = Parts.length(n, total, partSize);
49
+ String what = "part " + n + " of " + count;
50
+ Http.Answer a = Http.send(
51
+ "PUT",
52
+ r.partUrls.get(n - 1),
53
+ r.headers,
54
+ "application/octet-stream",
55
+ file,
56
+ Parts.offset(n, partSize),
57
+ length,
58
+ null,
59
+ progress,
60
+ (w) -> progress.onBytes(UploadAdapters.pending(base + w, total), total),
61
+ null,
62
+ what
63
+ );
64
+ if (a.status != 200) throw TransferException.forStatus(a.status, what);
65
+ if (a.etag == null || a.etag.isEmpty()) {
66
+ throw new TransferException(TransferException.Reason.UNKNOWN, what + " answered without an ETag", a.status, null);
67
+ }
68
+ r.parts.put(n, a.etag);
69
+ stored += length;
70
+ progress.saveState();
71
+ progress.onBytes(UploadAdapters.pending(stored, total), total);
72
+ }
73
+ Pause.check(progress);
74
+ byte[] body = PartsXml.completeBody(r.parts, count).getBytes(java.nio.charset.StandardCharsets.UTF_8);
75
+ Http.Answer a = Http.send(
76
+ "POST",
77
+ r.url,
78
+ r.headers,
79
+ "application/xml",
80
+ null,
81
+ 0,
82
+ 0,
83
+ body,
84
+ progress,
85
+ null,
86
+ () -> {
87
+ // From here a lost answer can't be told from a completed upload.
88
+ r.committing = true;
89
+ progress.saveState();
90
+ },
91
+ "complete"
92
+ );
93
+ if (a.status == 200 && PartsXml.isCompleteResult(a.body)) {
94
+ progress.onBytes(total, total);
95
+ return total;
96
+ }
97
+ // An answer came, so the completion wasn't lost: it can be tried again.
98
+ r.committing = false;
99
+ progress.saveState();
100
+ if (a.status == 404) {
101
+ // NoSuchUpload: completed (perhaps by a completion whose answer was lost) or aborted.
102
+ throw new TransferException(
103
+ TransferException.Reason.SESSION_CLOSED,
104
+ "complete HTTP 404: the upload is no longer open (completed or aborted): check the object",
105
+ 404,
106
+ null
107
+ );
108
+ }
109
+ if (a.status != 200) throw TransferException.forStatus(a.status, "complete");
110
+ String code = PartsXml.errorCode(a.body);
111
+ if (code == null) throw new TransferException(
112
+ TransferException.Reason.UNKNOWN,
113
+ "complete answered 200 without the completed object",
114
+ 200,
115
+ null
116
+ );
117
+ boolean busy = code.equals("InternalError") || code.equals("SlowDown") || code.equals("ServiceUnavailable");
118
+ throw new TransferException(
119
+ busy ? TransferException.Reason.SERVER_ERROR : TransferException.Reason.SESSION_REFUSED,
120
+ "complete answered 200 with " + code,
121
+ 200,
122
+ null
123
+ );
124
+ }
125
+
126
+ /** The parts S3 holds at their full size, by number; past a truncated list, the record's. */
127
+ private static Map<Integer, String> held(TransferRecord r, Progress progress, long total, long partSize, int count)
128
+ throws TransferException {
129
+ Http.Answer a = Http.send("GET", r.listPartsUrl, r.headers, null, null, 0, 0, null, progress, null, null, "ListParts");
130
+ if (a.status != 200) throw TransferException.forStatus(a.status, "ListParts");
131
+ PartsXml.Listed listed = PartsXml.listParts(a.body);
132
+ Map<Integer, String> kept = new TreeMap<>();
133
+ for (int n = 1; n <= count; n++) {
134
+ PartsXml.Held h = listed.parts.get(n);
135
+ if (h != null) {
136
+ if (h.size == Parts.length(n, total, partSize)) kept.put(n, h.tag);
137
+ } else if (listed.truncated && n > listed.highest && r.parts.containsKey(n)) {
138
+ kept.put(n, r.parts.get(n));
139
+ }
140
+ }
141
+ return kept;
142
+ }
143
+ }
@@ -0,0 +1,144 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import android.app.job.JobInfo;
4
+ import android.app.job.JobScheduler;
5
+ import android.content.ComponentName;
6
+ import android.content.Context;
7
+ import android.os.Build;
8
+ import androidx.work.Data;
9
+ import androidx.work.ExistingWorkPolicy;
10
+ import androidx.work.OneTimeWorkRequest;
11
+ import androidx.work.OutOfQuotaPolicy;
12
+ import androidx.work.WorkInfo;
13
+ import androidx.work.WorkManager;
14
+ import java.io.File;
15
+ import java.util.List;
16
+
17
+ /** Starts the host for a direction: the user-initiated job on Android 14+, the worker below. */
18
+ final class Scheduler {
19
+
20
+ static final int UPLOAD_JOB = 0x0B7A0001;
21
+ static final int DOWNLOAD_JOB = 0x0B7A0002;
22
+
23
+ private Scheduler() {}
24
+
25
+ static boolean usesJob() {
26
+ return Build.VERSION.SDK_INT >= 34;
27
+ }
28
+
29
+ /**
30
+ * Below Android 14 the worker runs as WorkManager's foreground service with the {@code dataSync}
31
+ * type, which the app's manifest must declare (the plugin doesn't, so it can't clash with an
32
+ * app that declares other types too). Returns what is wrong, or null.
33
+ */
34
+ static String foregroundServiceProblem(Context context) {
35
+ if (usesJob() || Build.VERSION.SDK_INT < 29) return null;
36
+ try {
37
+ android.content.pm.ServiceInfo info = context
38
+ .getPackageManager()
39
+ .getServiceInfo(new ComponentName(context, "androidx.work.impl.foreground.SystemForegroundService"), 0);
40
+ if ((info.getForegroundServiceType() & android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) == 0) {
41
+ return (
42
+ "androidx.work.impl.foreground.SystemForegroundService is not declared with foregroundServiceType dataSync: " +
43
+ "transfers stop when the app leaves the screen"
44
+ );
45
+ }
46
+ return null;
47
+ } catch (android.content.pm.PackageManager.NameNotFoundException e) {
48
+ return "androidx.work.impl.foreground.SystemForegroundService is not in the manifest";
49
+ }
50
+ }
51
+
52
+ static TransferStore store(Context context) {
53
+ return TransferStore.in(storeDir(context));
54
+ }
55
+
56
+ /**
57
+ * The plugin's own directory: under the no-backup files, so the records (with their headers and
58
+ * tokens) are never in Auto Backup. A store an earlier version kept under {@code filesDir} is
59
+ * moved here the first time, so transfers in flight across the upgrade are kept.
60
+ */
61
+ static File storeDir(Context context) {
62
+ Context app = context.getApplicationContext();
63
+ File dir = new File(app.getNoBackupFilesDir(), "background-transfer");
64
+ File old = new File(app.getFilesDir(), "background-transfer");
65
+ if (!dir.exists() && old.isDirectory() && !old.renameTo(dir)) {
66
+ android.util.Log.w("BackgroundTransfer", "could not move the transfer store out of the backed-up files");
67
+ }
68
+ return dir;
69
+ }
70
+
71
+ static int jobIdFor(String direction) {
72
+ return TransferRecord.UPLOAD.equals(direction) ? UPLOAD_JOB : DOWNLOAD_JOB;
73
+ }
74
+
75
+ static String directionOfJob(int jobId) {
76
+ if (jobId == UPLOAD_JOB) return TransferRecord.UPLOAD;
77
+ if (jobId == DOWNLOAD_JOB) return TransferRecord.DOWNLOAD;
78
+ return null;
79
+ }
80
+
81
+ private static String workName(String direction) {
82
+ return "background-transfer-" + direction;
83
+ }
84
+
85
+ /** Whether the system still holds a host for {@code direction} (a pending or running job, or unfinished work). */
86
+ static boolean hostScheduled(Context context, String direction) {
87
+ if (usesJob()) {
88
+ JobScheduler js = context.getSystemService(JobScheduler.class);
89
+ return js != null && js.getPendingJob(jobIdFor(direction)) != null;
90
+ }
91
+ try {
92
+ List<WorkInfo> infos = WorkManager.getInstance(context).getWorkInfosForUniqueWork(workName(direction)).get();
93
+ for (WorkInfo info : infos) if (!info.getState().isFinished()) return true;
94
+ } catch (Exception ignored) {
95
+ // Unknown: say no, and the caller schedules one, which is harmless.
96
+ }
97
+ return false;
98
+ }
99
+
100
+ /**
101
+ * Schedules the host. On Android 14+ this must happen while the app is
102
+ * visible, which is when the plugin's methods and its load run. Throws
103
+ * when the system refuses.
104
+ */
105
+ static void schedule(Context context, String direction) {
106
+ if (usesJob()) {
107
+ scheduleJob(context, direction);
108
+ return;
109
+ }
110
+ OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(TransferWorker.class)
111
+ .setInputData(new Data.Builder().putString(TransferWorker.KEY_DIRECTION, direction).build())
112
+ .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
113
+ .addTag("background-transfer")
114
+ .build();
115
+ // Appended: a worker already draining finishes, then this one finds the queue empty or carries on.
116
+ WorkManager.getInstance(context).enqueueUniqueWork(workName(direction), ExistingWorkPolicy.APPEND_OR_REPLACE, request);
117
+ }
118
+
119
+ private static void scheduleJob(Context context, String direction) {
120
+ if (Build.VERSION.SDK_INT < 34) return;
121
+ long bytes = 0;
122
+ for (TransferRecord r : store(context).all()) {
123
+ if (!direction.equals(r.direction) || !TransferRecord.QUEUED.equals(r.state)) continue;
124
+ if (TransferRecord.UPLOAD.equals(direction)) {
125
+ long size = new File(r.path).length();
126
+ bytes += Math.max(0, size - Math.max(0, r.bytes));
127
+ } else if (r.total > 0) {
128
+ bytes += Math.max(0, r.total - r.bytes);
129
+ }
130
+ }
131
+ long estimate = bytes > 0 ? bytes : JobInfo.NETWORK_BYTES_UNKNOWN;
132
+ boolean upload = TransferRecord.UPLOAD.equals(direction);
133
+ JobInfo job = new JobInfo.Builder(jobIdFor(direction), new ComponentName(context, TransferJobService.class))
134
+ .setUserInitiated(true)
135
+ .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
136
+ .setEstimatedNetworkBytes(upload ? JobInfo.NETWORK_BYTES_UNKNOWN : estimate, upload ? estimate : JobInfo.NETWORK_BYTES_UNKNOWN)
137
+ .setPersisted(true)
138
+ .build();
139
+ JobScheduler js = context.getSystemService(JobScheduler.class);
140
+ if (js == null || js.schedule(job) != JobScheduler.RESULT_SUCCESS) {
141
+ throw new IllegalStateException("the system refused to schedule the transfer job");
142
+ }
143
+ }
144
+ }
@@ -0,0 +1,65 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ /**
4
+ * Why a transfer stopped. {@link #reason} is one of the {@code Reason}
5
+ * strings, which are the TypeScript {@code TransferFailureReason} values.
6
+ */
7
+ public class TransferException extends Exception {
8
+
9
+ public static final class Reason {
10
+
11
+ public static final String FILE_MISSING = "file-missing";
12
+ public static final String DISK_FULL = "disk-full";
13
+ public static final String SESSION_REFUSED = "session-refused";
14
+ public static final String SESSION_EXPIRED = "session-expired";
15
+ /** The session was already closed: whether the object was accepted only its metadata can say. */
16
+ public static final String SESSION_CLOSED = "session-closed";
17
+ public static final String SIZE_MISMATCH = "size-mismatch";
18
+ public static final String NETWORK = "network";
19
+ public static final String STOPPED_BY_SYSTEM = "stopped-by-system";
20
+ public static final String CANCELLED = "cancelled";
21
+ public static final String SERVER_ERROR = "server-error";
22
+ public static final String UNKNOWN = "unknown";
23
+
24
+ private Reason() {}
25
+ }
26
+
27
+ public final String reason;
28
+ /** The HTTP status that stopped it, or 0. */
29
+ public final int httpStatus;
30
+
31
+ public TransferException(String reason, String message) {
32
+ this(reason, message, 0, null);
33
+ }
34
+
35
+ public TransferException(String reason, String message, int httpStatus, Throwable cause) {
36
+ super(message, cause);
37
+ this.reason = reason;
38
+ this.httpStatus = httpStatus;
39
+ }
40
+
41
+ /** Worth trying again later from where it stopped (the network, the system, a 5xx). */
42
+ public boolean isResumable() {
43
+ return Reason.NETWORK.equals(reason) || Reason.STOPPED_BY_SYSTEM.equals(reason) || Reason.SERVER_ERROR.equals(reason);
44
+ }
45
+
46
+ /** The reason for an HTTP status that isn't a success. */
47
+ public static TransferException forStatus(int status, String what) {
48
+ String reason;
49
+ if (status == 404 || status == 410) reason = Reason.SESSION_EXPIRED;
50
+ else if (status == 408 || status == 429 || status >= 500) reason = Reason.SERVER_ERROR;
51
+ else reason = Reason.SESSION_REFUSED;
52
+ String message = what + " HTTP " + status;
53
+ if (status >= 300 && status < 400) message += " (a redirect, which an upload never follows)";
54
+ return new TransferException(reason, message, status, null);
55
+ }
56
+
57
+ /** An I/O error while writing to local disk: full, or something else. */
58
+ public static TransferException forDisk(java.io.IOException e) {
59
+ String m = String.valueOf(e.getMessage());
60
+ if (m.contains("ENOSPC") || m.toLowerCase(java.util.Locale.ROOT).contains("no space")) {
61
+ return new TransferException(Reason.DISK_FULL, "no space left on the device", 0, e);
62
+ }
63
+ return new TransferException(Reason.UNKNOWN, "disk: " + m, 0, e);
64
+ }
65
+ }
@@ -0,0 +1,115 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import android.app.job.JobParameters;
4
+ import android.app.job.JobService;
5
+ import android.os.Build;
6
+ import androidx.annotation.RequiresApi;
7
+
8
+ /**
9
+ * Android 14+: a user-initiated data transfer job, one per direction, that
10
+ * works through that direction's queue. It keeps running with the device
11
+ * locked, in Doze and after the app is removed from Recents, and when the
12
+ * network goes the system stops it and starts it again once the network is
13
+ * back. Only force-stop, or the user stopping it from the
14
+ * Task Manager, ends it for good; the next open reports those transfers as
15
+ * interrupted.
16
+ */
17
+ @RequiresApi(34)
18
+ public class TransferJobService extends JobService {
19
+
20
+ private final JobRuns runs = new JobRuns();
21
+
22
+ /** How long a new run waits for the previous run's thread (stopped by the system, still closing its connection). */
23
+ private static final long WAIT_FOR_PREVIOUS_MS = 60_000;
24
+
25
+ @Override
26
+ public boolean onStartJob(JobParameters params) {
27
+ int jobId = params.getJobId();
28
+ String direction = Scheduler.directionOfJob(jobId);
29
+ if (direction == null) return false;
30
+ JobRuns.Run run = runs.start(jobId);
31
+ TransferStore store = Scheduler.store(this);
32
+ // A user-initiated job must post its notification as soon as it starts.
33
+ setNotification(
34
+ params,
35
+ Notifications.idFor(direction),
36
+ Notifications.build(this, direction, store.nextQueued(direction)),
37
+ JOB_END_NOTIFICATION_POLICY_REMOVE
38
+ );
39
+ new Thread(() -> {
40
+ // The previous run may still be in its last request after onStopJob: let it end first.
41
+ long until = System.currentTimeMillis() + WAIT_FOR_PREVIOUS_MS;
42
+ while (!Runner.begin(direction)) {
43
+ if (run.stopReason != null) {
44
+ runs.end(jobId, run);
45
+ return;
46
+ }
47
+ if (System.currentTimeMillis() > until) {
48
+ runs.end(jobId, run);
49
+ jobFinished(params, true);
50
+ return;
51
+ }
52
+ try {
53
+ Thread.sleep(250);
54
+ } catch (InterruptedException e) {
55
+ Thread.currentThread().interrupt();
56
+ return;
57
+ }
58
+ }
59
+ Runner.Outcome outcome = Runner.drain(
60
+ store,
61
+ direction,
62
+ new Runner.Host() {
63
+ @Override
64
+ public void onProgress(TransferRecord r) {
65
+ if (run.stopReason != null) return;
66
+ setNotification(
67
+ params,
68
+ Notifications.idFor(direction),
69
+ Notifications.build(TransferJobService.this, direction, r),
70
+ JOB_END_NOTIFICATION_POLICY_REMOVE
71
+ );
72
+ if (TransferRecord.UPLOAD.equals(direction)) updateTransferredNetworkBytes(params, 0, r.bytes);
73
+ else updateTransferredNetworkBytes(params, r.bytes, 0);
74
+ }
75
+
76
+ @Override
77
+ public boolean waitsForNetwork() {
78
+ return !run.byUser;
79
+ }
80
+
81
+ @Override
82
+ public String systemStopReason() {
83
+ return run.stopReason;
84
+ }
85
+ }
86
+ );
87
+ runs.end(jobId, run);
88
+ // After onStopJob the system has already decided; jobFinished must not be called.
89
+ if (run.stopReason == null) jobFinished(params, outcome == Runner.Outcome.RESCHEDULE);
90
+ }, "BackgroundTransferJob-" + direction).start();
91
+ return true;
92
+ }
93
+
94
+ @Override
95
+ public void onNetworkChanged(JobParameters params) {
96
+ // Each request opens its own connection on the default network; nothing to move.
97
+ }
98
+
99
+ @Override
100
+ public boolean onStopJob(JobParameters params) {
101
+ boolean byUser = Build.VERSION.SDK_INT >= 34 && params.getStopReason() == JobParameters.STOP_REASON_USER;
102
+ boolean known = runs.stop(params.getJobId(), byUser);
103
+ android.util.Log.i(
104
+ "BackgroundTransfer",
105
+ "job " +
106
+ params.getJobId() +
107
+ " stopped by the system, reason " +
108
+ (Build.VERSION.SDK_INT >= 31 ? params.getStopReason() : -1) +
109
+ (byUser ? " (the user)" : "") +
110
+ (known ? "" : ", no run known")
111
+ );
112
+ // Network lost, quota, the device state: the system runs it again later. Stopped by the user: it doesn't.
113
+ return !byUser;
114
+ }
115
+ }
@@ -0,0 +1,129 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.io.File;
4
+ import java.io.IOException;
5
+ import java.nio.file.Files;
6
+ import java.util.ArrayList;
7
+ import java.util.List;
8
+ import java.util.Map;
9
+ import java.util.regex.Pattern;
10
+
11
+ /**
12
+ * The checks on a transfer's options that the native side repeats, whatever the JavaScript wrapper
13
+ * did: a script in the web view can call the plugin directly and skip {@code validate.ts}. The
14
+ * refusals use the wrapper's words. Plain Java, so it runs under JUnit.
15
+ */
16
+ final class TransferPaths {
17
+
18
+ private static final Pattern HTTP_URL = Pattern.compile("^https?://[^/]+.*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
19
+ private static final Pattern CONTROL = Pattern.compile("[\\x00-\\x1f\\x7f]");
20
+
21
+ static final String NOT_HTTP = "url must be an http or https URL";
22
+ static final String OUTSIDE = "path must be inside the app's storage";
23
+ static final String PLUGIN_DIR = "path must not be inside the plugin's own storage";
24
+ static final String SYMLINK = "path must not be a symbolic link";
25
+
26
+ /** How many hops a redirect is followed on the same host before the transfer is refused. */
27
+ static final int MAX_REDIRECTS = 5;
28
+
29
+ private TransferPaths() {}
30
+
31
+ /** What is wrong with {@code url}, or null. */
32
+ static String checkUrl(String url) {
33
+ return url != null && HTTP_URL.matcher(url).matches() ? null : NOT_HTTP;
34
+ }
35
+
36
+ /** What is wrong with the headers (a name or value with a line break or another control character), or null. */
37
+ static String checkHeaders(Map<String, String> headers) {
38
+ if (headers == null) return null;
39
+ for (Map.Entry<String, String> h : headers.entrySet()) {
40
+ String name = h.getKey();
41
+ if (
42
+ name == null ||
43
+ name.isEmpty() ||
44
+ CONTROL.matcher(name).find() ||
45
+ h.getValue() == null ||
46
+ CONTROL.matcher(h.getValue()).find()
47
+ ) {
48
+ return "header " + name + " must be one line";
49
+ }
50
+ }
51
+ return null;
52
+ }
53
+
54
+ /** The wrapper's checks on the path's shape: absolute, naming a file, no {@code ..} segment. */
55
+ static String checkShape(String path) {
56
+ if (path == null || path.isEmpty()) return "path is required";
57
+ if (!path.startsWith("/")) return "path must be absolute or a file:// URI";
58
+ if (path.endsWith("/")) return "path must name a file";
59
+ for (String segment : path.split("/")) if ("..".equals(segment)) return "path must not contain ..";
60
+ return null;
61
+ }
62
+
63
+ /**
64
+ * Refuses a path that isn't under one of {@code roots} (the app's own directories) once symbolic
65
+ * links are resolved, or that is inside {@code refused} (the plugin's own storage, which holds
66
+ * other transfers' headers). For a download, the destination and its {@code .part} must not be
67
+ * symbolic links either, since both are replaced. Returns what is wrong, or null.
68
+ */
69
+ static String confine(String path, List<File> roots, File refused, boolean download) {
70
+ String shape = checkShape(path);
71
+ if (shape != null) return shape;
72
+ File file = new File(path);
73
+ File canonical;
74
+ try {
75
+ canonical = canonical(file);
76
+ } catch (IOException e) {
77
+ return OUTSIDE;
78
+ }
79
+ if (refused != null) {
80
+ try {
81
+ if (isUnder(canonical, canonical(refused))) return PLUGIN_DIR;
82
+ } catch (IOException ignored) {
83
+ // The plugin's directory can't be resolved: nothing to be inside of.
84
+ }
85
+ }
86
+ boolean inside = false;
87
+ for (File root : roots) {
88
+ if (root == null) continue;
89
+ try {
90
+ if (isUnder(canonical, canonical(root))) {
91
+ inside = true;
92
+ break;
93
+ }
94
+ } catch (IOException ignored) {
95
+ // A root that can't be resolved (an unmounted volume) admits nothing.
96
+ }
97
+ }
98
+ if (!inside) return OUTSIDE;
99
+ if (download && (Files.isSymbolicLink(file.toPath()) || Files.isSymbolicLink(Downloader.partFile(file).toPath()))) {
100
+ return SYMLINK;
101
+ }
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * {@code file} with every symbolic link resolved: its deepest existing ancestor is canonicalised
107
+ * and the rest appended, so a file not yet written (a download's destination) resolves too.
108
+ */
109
+ static File canonical(File file) throws IOException {
110
+ File absolute = file.getAbsoluteFile();
111
+ List<String> rest = new ArrayList<>();
112
+ File existing = absolute;
113
+ while (existing != null && !existing.exists()) {
114
+ rest.add(0, existing.getName());
115
+ existing = existing.getParentFile();
116
+ }
117
+ if (existing == null) throw new IOException("no existing ancestor for " + file);
118
+ File resolved = existing.getCanonicalFile();
119
+ for (String name : rest) resolved = new File(resolved, name);
120
+ return resolved;
121
+ }
122
+
123
+ /** Whether {@code file} is {@code root} or inside it (both canonical). */
124
+ static boolean isUnder(File file, File root) {
125
+ String f = file.getPath();
126
+ String r = root.getPath();
127
+ return f.equals(r) || f.startsWith(r.endsWith(File.separator) ? r : r + File.separator);
128
+ }
129
+ }