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,163 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.util.ArrayList;
4
+ import java.util.Iterator;
5
+ import java.util.LinkedHashMap;
6
+ import java.util.List;
7
+ import java.util.Map;
8
+ import java.util.TreeMap;
9
+ import org.json.JSONArray;
10
+ import org.json.JSONException;
11
+ import org.json.JSONObject;
12
+
13
+ /** One transfer, as stored and as reported to JavaScript ({@code TransferRecord} in definitions.ts). */
14
+ public final class TransferRecord {
15
+
16
+ public static final String UPLOAD = "upload";
17
+ public static final String DOWNLOAD = "download";
18
+
19
+ public static final String QUEUED = "queued";
20
+ public static final String RUNNING = "running";
21
+ public static final String INTERRUPTED = "interrupted";
22
+ public static final String FINISHED = "finished";
23
+ public static final String FAILED = "failed";
24
+ public static final String CANCELLED = "cancelled";
25
+
26
+ public String id;
27
+ public String direction;
28
+ public String state;
29
+ public String url;
30
+ public String path;
31
+ /** Uploads: the protocol the session speaks ({@link UploadAdapters}). */
32
+ public String protocol = UploadAdapters.DEFAULT;
33
+ public long bytes;
34
+ public long total = -1;
35
+ public String reason;
36
+ public String message;
37
+ public int httpStatus;
38
+ public long updatedAt;
39
+ /** When it was queued, for first-in first-out. */
40
+ public long queuedAt;
41
+ /** Runs in a row that ended without moving a byte; caps the job's retries. */
42
+ public int idleRuns;
43
+ public Map<String, String> headers = new LinkedHashMap<>();
44
+ /** {@code s3-multipart}: the presigned part URLs, part 1 first. */
45
+ public List<String> partUrls = new ArrayList<>();
46
+ /** {@code s3-multipart}: bytes per part, or 0 for the default. */
47
+ public long partSize;
48
+ /** {@code s3-multipart}: the presigned ListParts URL, or null. */
49
+ public String listPartsUrl;
50
+ /** {@code azure-blocks}: bytes per block, or 0 for the default. */
51
+ public long blockSize;
52
+ /** Parts or blocks the server holds, by number: the S3 {@code ETag} or the Azure block id. */
53
+ public Map<Integer, String> parts = new TreeMap<>();
54
+ /** The commit (S3 completion, Azure block list) has been sent: a lost answer isn't taken as success. */
55
+ public boolean committing;
56
+ public String channelId;
57
+ public String channelName;
58
+ public String title;
59
+ public String text;
60
+
61
+ public String key() {
62
+ return keyOf(direction, id);
63
+ }
64
+
65
+ public static String keyOf(String direction, String id) {
66
+ return direction + ":" + id;
67
+ }
68
+
69
+ /** Still to run or running: not to be forgotten or started twice. */
70
+ public boolean isActive() {
71
+ return QUEUED.equals(state) || RUNNING.equals(state);
72
+ }
73
+
74
+ /** Can be started again with the same id. */
75
+ public boolean isRestartable() {
76
+ return INTERRUPTED.equals(state) || FAILED.equals(state) || CANCELLED.equals(state);
77
+ }
78
+
79
+ public JSONObject toJson(boolean forJs) throws JSONException {
80
+ JSONObject o = new JSONObject();
81
+ o.put("id", id);
82
+ o.put("direction", direction);
83
+ o.put("state", state);
84
+ o.put("url", url);
85
+ o.put("path", path);
86
+ if (UPLOAD.equals(direction)) o.put("protocol", protocol);
87
+ o.put("bytes", bytes);
88
+ o.put("total", total);
89
+ if (reason != null) o.put("reason", reason);
90
+ if (message != null) o.put("message", message);
91
+ if (httpStatus != 0) o.put("httpStatus", httpStatus);
92
+ o.put("updatedAt", updatedAt);
93
+ if (!forJs) {
94
+ o.put("queuedAt", queuedAt);
95
+ o.put("idleRuns", idleRuns);
96
+ o.put("headers", new JSONObject(headers));
97
+ putOpt(o, "channelId", channelId);
98
+ putOpt(o, "channelName", channelName);
99
+ putOpt(o, "title", title);
100
+ putOpt(o, "text", text);
101
+ if (!partUrls.isEmpty()) o.put("partUrls", new JSONArray(partUrls));
102
+ if (partSize > 0) o.put("partSize", partSize);
103
+ putOpt(o, "listPartsUrl", listPartsUrl);
104
+ if (blockSize > 0) o.put("blockSize", blockSize);
105
+ if (!parts.isEmpty()) {
106
+ JSONObject p = new JSONObject();
107
+ for (Map.Entry<Integer, String> e : parts.entrySet()) p.put(String.valueOf(e.getKey()), e.getValue());
108
+ o.put("parts", p);
109
+ }
110
+ if (committing) o.put("committing", true);
111
+ }
112
+ return o;
113
+ }
114
+
115
+ private static void putOpt(JSONObject o, String k, String v) throws JSONException {
116
+ if (v != null) o.put(k, v);
117
+ }
118
+
119
+ public static TransferRecord fromJson(JSONObject o) throws JSONException {
120
+ TransferRecord r = new TransferRecord();
121
+ r.id = o.getString("id");
122
+ r.direction = o.getString("direction");
123
+ r.state = o.getString("state");
124
+ r.url = o.getString("url");
125
+ r.path = o.getString("path");
126
+ r.protocol = o.optString("protocol", UploadAdapters.DEFAULT);
127
+ r.bytes = o.optLong("bytes", 0);
128
+ r.total = o.optLong("total", -1);
129
+ r.reason = o.has("reason") ? o.getString("reason") : null;
130
+ r.message = o.has("message") ? o.getString("message") : null;
131
+ r.httpStatus = o.optInt("httpStatus", 0);
132
+ r.updatedAt = o.optLong("updatedAt", 0);
133
+ r.queuedAt = o.optLong("queuedAt", 0);
134
+ r.idleRuns = o.optInt("idleRuns", 0);
135
+ JSONObject h = o.optJSONObject("headers");
136
+ if (h != null) {
137
+ java.util.Iterator<String> names = h.keys();
138
+ while (names.hasNext()) {
139
+ String name = names.next();
140
+ r.headers.put(name, h.getString(name));
141
+ }
142
+ }
143
+ r.channelId = o.has("channelId") ? o.getString("channelId") : null;
144
+ r.channelName = o.has("channelName") ? o.getString("channelName") : null;
145
+ r.title = o.has("title") ? o.getString("title") : null;
146
+ r.text = o.has("text") ? o.getString("text") : null;
147
+ JSONArray urls = o.optJSONArray("partUrls");
148
+ if (urls != null) for (int i = 0; i < urls.length(); i++) r.partUrls.add(urls.getString(i));
149
+ r.partSize = o.optLong("partSize", 0);
150
+ r.listPartsUrl = o.has("listPartsUrl") ? o.getString("listPartsUrl") : null;
151
+ r.blockSize = o.optLong("blockSize", 0);
152
+ JSONObject p = o.optJSONObject("parts");
153
+ if (p != null) {
154
+ Iterator<String> numbers = p.keys();
155
+ while (numbers.hasNext()) {
156
+ String n = numbers.next();
157
+ r.parts.put(Integer.parseInt(n), p.getString(n));
158
+ }
159
+ }
160
+ r.committing = o.optBoolean("committing", false);
161
+ return r;
162
+ }
163
+ }
@@ -0,0 +1,121 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.io.File;
4
+ import java.io.FileOutputStream;
5
+ import java.io.IOException;
6
+ import java.nio.charset.StandardCharsets;
7
+ import java.nio.file.Files;
8
+ import java.util.ArrayList;
9
+ import java.util.LinkedHashMap;
10
+ import java.util.List;
11
+ import java.util.Map;
12
+ import org.json.JSONArray;
13
+ import org.json.JSONException;
14
+ import org.json.JSONObject;
15
+
16
+ /**
17
+ * Every transfer's record, kept in one small JSON file so the state survives
18
+ * the app's process (the job or worker may run, finish or fail with the app
19
+ * closed). Records handed out are copies; change one with {@link #put}.
20
+ */
21
+ public final class TransferStore {
22
+
23
+ private static final Map<String, TransferStore> stores = new LinkedHashMap<>();
24
+
25
+ private final File file;
26
+ private final Map<String, TransferRecord> records = new LinkedHashMap<>();
27
+
28
+ /** The store kept in {@code dir} (one per directory per process). */
29
+ public static synchronized TransferStore in(File dir) {
30
+ String key = dir.getAbsolutePath();
31
+ TransferStore s = stores.get(key);
32
+ if (s == null) {
33
+ s = new TransferStore(new File(dir, "transfers.json"));
34
+ stores.put(key, s);
35
+ }
36
+ return s;
37
+ }
38
+
39
+ TransferStore(File file) {
40
+ this.file = file;
41
+ load();
42
+ }
43
+
44
+ private void load() {
45
+ if (!file.isFile()) return;
46
+ try {
47
+ JSONArray list = new JSONArray(new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8));
48
+ for (int i = 0; i < list.length(); i++) {
49
+ TransferRecord r = TransferRecord.fromJson(list.getJSONObject(i));
50
+ records.put(r.key(), r);
51
+ }
52
+ } catch (IOException | JSONException e) {
53
+ // A damaged file loses the history, never the transfers' files.
54
+ records.clear();
55
+ }
56
+ }
57
+
58
+ private void save() {
59
+ File dir = file.getParentFile();
60
+ if (dir != null && !dir.isDirectory()) dir.mkdirs();
61
+ File tmp = new File(file.getPath() + ".tmp");
62
+ try {
63
+ JSONArray list = new JSONArray();
64
+ for (TransferRecord r : records.values()) list.put(r.toJson(false));
65
+ try (FileOutputStream out = new FileOutputStream(tmp)) {
66
+ out.write(list.toString().getBytes(StandardCharsets.UTF_8));
67
+ out.getFD().sync();
68
+ }
69
+ if (!tmp.renameTo(file)) throw new IOException("rename failed");
70
+ } catch (IOException | JSONException e) {
71
+ tmp.delete();
72
+ }
73
+ }
74
+
75
+ private static TransferRecord copy(TransferRecord r) {
76
+ if (r == null) return null;
77
+ try {
78
+ return TransferRecord.fromJson(r.toJson(false));
79
+ } catch (JSONException e) {
80
+ throw new IllegalStateException(e);
81
+ }
82
+ }
83
+
84
+ public synchronized TransferRecord get(String direction, String id) {
85
+ return copy(records.get(TransferRecord.keyOf(direction, id)));
86
+ }
87
+
88
+ public synchronized List<TransferRecord> all() {
89
+ List<TransferRecord> out = new ArrayList<>();
90
+ for (TransferRecord r : records.values()) out.add(copy(r));
91
+ return out;
92
+ }
93
+
94
+ /**
95
+ * Stores {@code r} (stamping {@code updatedAt}) and returns a copy of what was stored. A record
96
+ * that has stopped (finished, interrupted, failed or cancelled) is kept without its headers: a
97
+ * restart brings its own, and a token has no business on the disk after the request it was for.
98
+ */
99
+ public synchronized TransferRecord put(TransferRecord r) {
100
+ r.updatedAt = System.currentTimeMillis();
101
+ TransferRecord stored = copy(r);
102
+ if (!stored.isActive()) stored.headers.clear();
103
+ records.put(stored.key(), stored);
104
+ save();
105
+ return copy(stored);
106
+ }
107
+
108
+ public synchronized void remove(String direction, String id) {
109
+ if (records.remove(TransferRecord.keyOf(direction, id)) != null) save();
110
+ }
111
+
112
+ /** The oldest queued transfer in {@code direction}, or null. */
113
+ public synchronized TransferRecord nextQueued(String direction) {
114
+ TransferRecord next = null;
115
+ for (TransferRecord r : records.values()) {
116
+ if (!direction.equals(r.direction) || !TransferRecord.QUEUED.equals(r.state)) continue;
117
+ if (next == null || r.queuedAt < next.queuedAt) next = r;
118
+ }
119
+ return copy(next);
120
+ }
121
+ }
@@ -0,0 +1,85 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import android.content.Context;
4
+ import android.content.pm.ServiceInfo;
5
+ import android.os.Build;
6
+ import android.util.Log;
7
+ import androidx.annotation.NonNull;
8
+ import androidx.work.ForegroundInfo;
9
+ import androidx.work.Worker;
10
+ import androidx.work.WorkerParameters;
11
+
12
+ /**
13
+ * Below Android 14: a WorkManager worker promoted to a {@code dataSync}
14
+ * foreground service, working through
15
+ * one direction's queue. It survives the lock screen and removal from
16
+ * Recents, but after a network drop with the app off-screen it can't promote
17
+ * itself again ({@code ForegroundServiceStartNotAllowedException}), so
18
+ * an interrupted transfer is reported as interrupted and the rest of the
19
+ * queue waits for the app's next open. The six-hour daily {@code dataSync}
20
+ * limit applies here only.
21
+ */
22
+ public class TransferWorker extends Worker {
23
+
24
+ static final String KEY_DIRECTION = "direction";
25
+ private static final String TAG = "BackgroundTransfer";
26
+
27
+ public TransferWorker(@NonNull Context context, @NonNull WorkerParameters params) {
28
+ super(context, params);
29
+ }
30
+
31
+ private ForegroundInfo info(String direction, TransferRecord r) {
32
+ Context c = getApplicationContext();
33
+ int id = Notifications.idFor(direction);
34
+ return Build.VERSION.SDK_INT >= 29
35
+ ? new ForegroundInfo(id, Notifications.build(c, direction, r), ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
36
+ : new ForegroundInfo(id, Notifications.build(c, direction, r));
37
+ }
38
+
39
+ @NonNull
40
+ @Override
41
+ public Result doWork() {
42
+ String direction = getInputData().getString(KEY_DIRECTION);
43
+ if (direction == null) return Result.failure();
44
+ TransferStore store = Scheduler.store(getApplicationContext());
45
+ if (!Runner.begin(direction)) return Result.success();
46
+ TransferRecord first = store.nextQueued(direction);
47
+ if (first == null) {
48
+ Runner.end(direction);
49
+ return Result.success();
50
+ }
51
+ try {
52
+ setForegroundAsync(info(direction, first)).get();
53
+ } catch (Exception e) {
54
+ // Refused from the background. Carry on: with the network up it still finishes while the process lives.
55
+ String problem = Scheduler.foregroundServiceProblem(getApplicationContext());
56
+ Log.w(TAG, "could not run as a foreground service: " + (problem != null ? problem : e.toString()));
57
+ }
58
+ Runner.drain(
59
+ store,
60
+ direction,
61
+ new Runner.Host() {
62
+ private long last;
63
+
64
+ @Override
65
+ public void onProgress(TransferRecord r) {
66
+ long now = System.currentTimeMillis();
67
+ if (now - last < 1000 && !(r.total > 0 && r.bytes >= r.total)) return;
68
+ last = now;
69
+ setForegroundAsync(info(direction, r));
70
+ }
71
+
72
+ @Override
73
+ public boolean waitsForNetwork() {
74
+ return false;
75
+ }
76
+
77
+ @Override
78
+ public String systemStopReason() {
79
+ return isStopped() ? TransferException.Reason.STOPPED_BY_SYSTEM : null;
80
+ }
81
+ }
82
+ );
83
+ return Result.success();
84
+ }
85
+ }
@@ -0,0 +1,11 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ /**
4
+ * Sends a transfer's file in one protocol ({@link UploadAdapters}). An adapter that resumes from
5
+ * its own record keeps that state on the record ({@code parts}, {@code committing}) and saves it
6
+ * with {@link Progress#saveState()} as soon as it changes, so it survives the process.
7
+ */
8
+ public interface UploadAdapter {
9
+ /** Uploads {@code r}'s file; returns its size once the server has confirmed the whole object. */
10
+ long run(TransferRecord r, Progress progress) throws TransferException;
11
+ }
@@ -0,0 +1,89 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.util.Arrays;
4
+ import java.util.Collections;
5
+ import java.util.List;
6
+
7
+ /**
8
+ * The upload protocols this version speaks, by the name the JavaScript side passes in
9
+ * {@code protocol}. Another protocol plugs in here: a name, and an {@link UploadAdapter} for it.
10
+ */
11
+ public final class UploadAdapters {
12
+
13
+ /** A Firebase Storage resumable upload: the {@code X-Goog-Upload-*} protocol. */
14
+ public static final String FIREBASE_RESUMABLE = "firebase-resumable";
15
+ /** The whole file in one {@code PUT}. */
16
+ public static final String PUT = "put";
17
+ /** An S3 multipart upload with every URL presigned up front. */
18
+ public static final String S3_MULTIPART = "s3-multipart";
19
+ /** An Azure block blob through one SAS URL. */
20
+ public static final String AZURE_BLOCKS = "azure-blocks";
21
+
22
+ public static final String DEFAULT = FIREBASE_RESUMABLE;
23
+
24
+ public static final List<String> KNOWN = Collections.unmodifiableList(
25
+ Arrays.asList(FIREBASE_RESUMABLE, PUT, S3_MULTIPART, AZURE_BLOCKS)
26
+ );
27
+
28
+ private UploadAdapters() {}
29
+
30
+ /** The protocol to use for {@code name}: the default when null, or null when unknown. */
31
+ public static String resolve(String name) {
32
+ if (name == null) return DEFAULT;
33
+ return KNOWN.contains(name) ? name : null;
34
+ }
35
+
36
+ /** What the plugin says when it refuses an unknown protocol. */
37
+ public static String refusal() {
38
+ return "protocol must be one of " + String.join(", ", KNOWN);
39
+ }
40
+
41
+ /** The adapter for a known protocol; throws for an unknown one (a record from a later version). */
42
+ public static UploadAdapter forProtocol(String name, int retries, long backoffMillis) throws TransferException {
43
+ String protocol = resolve(name);
44
+ if (FIREBASE_RESUMABLE.equals(protocol)) return new Uploader(Uploader.CHUNK, retries, backoffMillis);
45
+ if (PUT.equals(protocol)) return new PutUploader(retries, backoffMillis);
46
+ if (S3_MULTIPART.equals(protocol)) return new S3MultipartUploader(retries, backoffMillis);
47
+ if (AZURE_BLOCKS.equals(protocol)) return new AzureBlockUploader(retries, backoffMillis);
48
+ throw new TransferException(TransferException.Reason.UNKNOWN, "unknown upload protocol " + name);
49
+ }
50
+
51
+ /** One try at an upload. */
52
+ interface Attempt {
53
+ long run() throws TransferException;
54
+ }
55
+
56
+ /** Runs {@code attempt}, trying again after a dropped connection up to {@code retries} times. */
57
+ static long withRetries(int retries, long backoffMillis, Progress progress, Attempt attempt) throws TransferException {
58
+ int tries = 0;
59
+ while (true) {
60
+ try {
61
+ return attempt.run();
62
+ } catch (TransferException e) {
63
+ if (!TransferException.Reason.NETWORK.equals(e.reason) || tries >= retries) throw e;
64
+ tries++;
65
+ Pause.sleep(backoffMillis << (tries - 1), progress);
66
+ }
67
+ }
68
+ }
69
+
70
+ /** The file to send, or {@code file-missing}. */
71
+ static java.io.File fileOf(TransferRecord r) throws TransferException {
72
+ java.io.File file = new java.io.File(r.path);
73
+ if (!file.isFile()) throw new TransferException(TransferException.Reason.FILE_MISSING, "no file at " + file);
74
+ return file;
75
+ }
76
+
77
+ /** Bytes to report before the server has confirmed the object: never the whole of it. */
78
+ static long pending(long bytes, long total) {
79
+ return total <= 0 ? 0 : Math.min(bytes, total - 1);
80
+ }
81
+
82
+ /** The commit was sent in an earlier try and its answer never came. */
83
+ static TransferException commitUnconfirmed(String what) {
84
+ return new TransferException(
85
+ TransferException.Reason.SESSION_CLOSED,
86
+ what + " was sent earlier and its answer never came: check the object before starting a new upload"
87
+ );
88
+ }
89
+ }
@@ -0,0 +1,104 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.util.List;
4
+ import java.util.regex.Pattern;
5
+
6
+ /**
7
+ * Checks an upload's protocol options the way {@code checkUploadOptions} in validate.ts does, with
8
+ * the same words, and the part count against the file's size, which only the native side can
9
+ * read. Plain Java, for the tests.
10
+ */
11
+ public final class UploadOptionsCheck {
12
+
13
+ public static final long MIB = 1024L * 1024L;
14
+ public static final long DEFAULT_PART_SIZE = 8 * MIB;
15
+ public static final long S3_MIN_PART_SIZE = 5 * MIB;
16
+ public static final long S3_MAX_PART_SIZE = 5 * 1024 * MIB;
17
+ public static final int S3_MAX_PARTS = 10_000;
18
+ public static final long AZURE_MAX_BLOCK_SIZE = 4000 * MIB;
19
+ public static final int AZURE_MAX_BLOCKS = 50_000;
20
+
21
+ private static final Pattern HTTP_URL = Pattern.compile("^https?://[^/]+.*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
22
+
23
+ private UploadOptionsCheck() {}
24
+
25
+ /**
26
+ * What is wrong with the options, or null. {@code partSize} and {@code blockSize} are null when
27
+ * not given; a number that isn't whole arrives as NaN-free {@link Double} and is checked here.
28
+ */
29
+ public static String check(String protocol, String url, List<Object> partUrls, Double partSize, Object listPartsUrl, Double blockSize) {
30
+ boolean s3 = UploadAdapters.S3_MULTIPART.equals(protocol);
31
+ boolean azure = UploadAdapters.AZURE_BLOCKS.equals(protocol);
32
+ if (!s3 && (partUrls != null || partSize != null || listPartsUrl != null)) {
33
+ return "partUrls, partSize and listPartsUrl are only for s3-multipart";
34
+ }
35
+ if (!azure && blockSize != null) return "blockSize is only for azure-blocks";
36
+ if (s3) {
37
+ if (partUrls == null || partUrls.isEmpty()) return "partUrls is required for s3-multipart";
38
+ if (partUrls.size() > S3_MAX_PARTS) return "partUrls holds more than " + S3_MAX_PARTS + " parts";
39
+ for (Object u : partUrls) {
40
+ if (!(u instanceof String) || !HTTP_URL.matcher((String) u).matches()) return "partUrls must be http or https URLs";
41
+ }
42
+ double size = partSize != null ? partSize : DEFAULT_PART_SIZE;
43
+ if (!isWhole(size) || size < 1 || size > S3_MAX_PART_SIZE) return "partSize must be a whole number of bytes up to 5 GiB";
44
+ if (partUrls.size() > 1 && size < S3_MIN_PART_SIZE) return "partSize must be at least 5 MiB when there is more than one part";
45
+ if (listPartsUrl != null && (!(listPartsUrl instanceof String) || !HTTP_URL.matcher((String) listPartsUrl).matches())) {
46
+ return "listPartsUrl must be an http or https URL";
47
+ }
48
+ }
49
+ if (azure) {
50
+ if (!isSasUrl(url)) return "url must be a blob SAS URL (with a sig parameter)";
51
+ double size = blockSize != null ? blockSize : DEFAULT_PART_SIZE;
52
+ if (
53
+ !isWhole(size) || size < 1 || size > AZURE_MAX_BLOCK_SIZE
54
+ ) return "blockSize must be a whole number of bytes up to 4000 MiB";
55
+ }
56
+ return null;
57
+ }
58
+
59
+ /** What is wrong with the part or block count for a {@code fileSize}-byte file, or null. */
60
+ public static String checkSize(String protocol, int partUrlCount, long partSize, long blockSize, long fileSize) {
61
+ if (UploadAdapters.S3_MULTIPART.equals(protocol)) {
62
+ int needed = Parts.count(fileSize, partSize, true);
63
+ if (needed > S3_MAX_PARTS) return (
64
+ "a " + fileSize + "-byte file in " + partSize + "-byte parts needs more than " + S3_MAX_PARTS + " parts"
65
+ );
66
+ if (needed != partUrlCount) {
67
+ return (
68
+ "partUrls holds " +
69
+ partUrlCount +
70
+ " parts but a " +
71
+ fileSize +
72
+ "-byte file in " +
73
+ partSize +
74
+ "-byte parts needs " +
75
+ needed
76
+ );
77
+ }
78
+ }
79
+ if (UploadAdapters.AZURE_BLOCKS.equals(protocol) && Parts.count(fileSize, blockSize, false) > AZURE_MAX_BLOCKS) {
80
+ return "a " + fileSize + "-byte file in " + blockSize + "-byte blocks needs more than " + AZURE_MAX_BLOCKS + " blocks";
81
+ }
82
+ return null;
83
+ }
84
+
85
+ private static boolean isWhole(double d) {
86
+ return !Double.isNaN(d) && !Double.isInfinite(d) && Math.floor(d) == d && Math.abs(d) <= 9_007_199_254_740_991d;
87
+ }
88
+
89
+ /** A blob URL with a SAS token: a non-empty {@code sig} parameter, and no {@code comp}. */
90
+ static boolean isSasUrl(String url) {
91
+ if (url == null) return false;
92
+ int hash = url.indexOf('#');
93
+ String u = hash >= 0 ? url.substring(0, hash) : url;
94
+ int q = u.indexOf('?');
95
+ if (q < 0) return false;
96
+ boolean sig = false;
97
+ for (String p : u.substring(q + 1).split("&")) {
98
+ String name = p.contains("=") ? p.substring(0, p.indexOf('=')) : p;
99
+ if (name.equals("comp")) return false;
100
+ if (name.equals("sig") && p.length() > "sig=".length()) sig = true;
101
+ }
102
+ return sig;
103
+ }
104
+ }