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,71 @@
1
+ ext {
2
+ junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'
3
+ androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.7.1'
4
+ androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.3.0'
5
+ androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.7.0'
6
+ // Follows the app's own workManagerVersion (variables.gradle) when it sets one.
7
+ workManagerVersion = project.hasProperty('workManagerVersion') ? rootProject.ext.workManagerVersion : '2.10.0'
8
+ }
9
+
10
+ buildscript {
11
+ repositories {
12
+ google()
13
+ mavenCentral()
14
+ }
15
+ dependencies {
16
+ classpath 'com.android.tools.build:gradle:8.13.0'
17
+ }
18
+ }
19
+
20
+ apply plugin: 'com.android.library'
21
+
22
+ android {
23
+ namespace "io.github.sandman92.backgroundtransfer"
24
+ compileSdk project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36
25
+ defaultConfig {
26
+ minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 23
27
+ targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 36
28
+ versionCode 1
29
+ versionName "1.0"
30
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
31
+ }
32
+ buildTypes {
33
+ release {
34
+ minifyEnabled false
35
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
36
+ }
37
+ }
38
+ lintOptions {
39
+ abortOnError false
40
+ }
41
+ testOptions {
42
+ unitTests.returnDefaultValues = true
43
+ unitTests.all {
44
+ // The tests against the local storage servers run only with BT_HARNESS set: a run with
45
+ // it isn't the same as one without, so Gradle mustn't reuse that one's results.
46
+ inputs.property('btHarness', System.getenv('BT_HARNESS') ?: '')
47
+ }
48
+ }
49
+ compileOptions {
50
+ sourceCompatibility JavaVersion.VERSION_21
51
+ targetCompatibility JavaVersion.VERSION_21
52
+ }
53
+ }
54
+
55
+ repositories {
56
+ google()
57
+ mavenCentral()
58
+ }
59
+
60
+
61
+ dependencies {
62
+ implementation fileTree(dir: 'libs', include: ['*.jar'])
63
+ implementation project(':capacitor-android')
64
+ implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
65
+ implementation "androidx.work:work-runtime:$workManagerVersion"
66
+ testImplementation "junit:junit:$junitVersion"
67
+ // Android's org.json is a stub under plain JUnit; the real one for the store's tests.
68
+ testImplementation "org.json:json:20240303"
69
+ // A local server for the uploader and downloader tests (the JDK one is not on the Android test classpath).
70
+ testImplementation "com.squareup.okhttp3:mockwebserver:4.12.0"
71
+ }
@@ -0,0 +1,20 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+
3
+ <uses-permission android:name="android.permission.INTERNET" />
4
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
5
+ <!-- Android 14+: the user-initiated data transfer job. Install-time. -->
6
+ <uses-permission android:name="android.permission.RUN_USER_INITIATED_JOBS" />
7
+ <!-- The job is persisted, so it carries on after a restart. -->
8
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
9
+ <!-- Below Android 14: the worker runs as a dataSync foreground service. -->
10
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
11
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
12
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
13
+
14
+ <application>
15
+ <service
16
+ android:name="io.github.sandman92.backgroundtransfer.TransferJobService"
17
+ android:exported="false"
18
+ android:permission="android.permission.BIND_JOB_SERVICE" />
19
+ </application>
20
+ </manifest>
@@ -0,0 +1,148 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.io.File;
4
+ import java.io.UnsupportedEncodingException;
5
+ import java.net.URLEncoder;
6
+ import java.util.List;
7
+ import java.util.Map;
8
+ import java.util.TreeMap;
9
+
10
+ /**
11
+ * An Azure block blob through one SAS URL: sends the blocks one at a time from the file in place
12
+ * with stable ids ({@code Put Block}), skips the ones in the blob's uncommitted block list when it
13
+ * resumes (or, when the SAS can't read the list, the ones its record holds), then commits them
14
+ * ({@code Put Block List}). Finished only when Azure answers the commit with 201.
15
+ */
16
+ final class AzureBlockUploader implements UploadAdapter {
17
+
18
+ private final int retries;
19
+ private final long backoffMillis;
20
+
21
+ AzureBlockUploader(int retries, long backoffMillis) {
22
+ this.retries = retries;
23
+ this.backoffMillis = backoffMillis;
24
+ }
25
+
26
+ @Override
27
+ public long run(TransferRecord r, Progress progress) throws TransferException {
28
+ return UploadAdapters.withRetries(retries, backoffMillis, progress, () -> attempt(r, progress));
29
+ }
30
+
31
+ private static long attempt(TransferRecord r, Progress progress) throws TransferException {
32
+ File file = UploadAdapters.fileOf(r);
33
+ long total = file.length();
34
+ if (r.committing) throw UploadAdapters.commitUnconfirmed("the block list");
35
+ long blockSize = r.blockSize > 0 ? r.blockSize : UploadOptionsCheck.DEFAULT_PART_SIZE;
36
+ String bad = UploadOptionsCheck.checkSize(UploadAdapters.AZURE_BLOCKS, 0, 0, blockSize, total);
37
+ if (bad != null) throw new TransferException(TransferException.Reason.SIZE_MISMATCH, bad);
38
+ int count = Parts.count(total, blockSize, false);
39
+ List<String> ids = PartsXml.blockIds(r.id, total, blockSize, count);
40
+ Http.Answer list = Http.send(
41
+ "GET",
42
+ Http.withQuery(r.url, "comp=blocklist&blocklisttype=uncommitted"),
43
+ r.headers,
44
+ null,
45
+ null,
46
+ 0,
47
+ 0,
48
+ null,
49
+ progress,
50
+ null,
51
+ null,
52
+ "Get Block List"
53
+ );
54
+ if (list.status == 200) {
55
+ Map<String, Long> held = PartsXml.uncommittedBlocks(list.body);
56
+ Map<Integer, String> kept = new TreeMap<>();
57
+ for (int n = 1; n <= count; n++) {
58
+ Long size = held.get(ids.get(n - 1));
59
+ if (size != null && size == Parts.length(n, total, blockSize)) kept.put(n, ids.get(n - 1));
60
+ }
61
+ r.parts = kept;
62
+ } else if (list.status == 404) {
63
+ // No blob and no blocks yet (or they expired): everything goes.
64
+ r.parts = new TreeMap<>();
65
+ } else if (list.status != 403) {
66
+ // 403: the SAS can't read the list (no `r`); trust the record. An expired SAS fails on the first block.
67
+ throw TransferException.forStatus(list.status, "Get Block List");
68
+ }
69
+ r.parts.keySet().removeIf((n) -> n > count || !ids.get(n - 1).equals(r.parts.get(n)));
70
+ progress.saveState();
71
+ long stored = 0;
72
+ for (int n : r.parts.keySet()) stored += Parts.length(n, total, blockSize);
73
+ progress.onBytes(UploadAdapters.pending(stored, total), total);
74
+ for (int n = 1; n <= count; n++) {
75
+ if (r.parts.containsKey(n)) continue;
76
+ Pause.check(progress);
77
+ final long base = stored;
78
+ long length = Parts.length(n, total, blockSize);
79
+ String what = "block " + n + " of " + count;
80
+ Http.Answer a = Http.send(
81
+ "PUT",
82
+ Http.withQuery(r.url, "comp=block&blockid=" + encode(ids.get(n - 1))),
83
+ blockHeaders(r.headers),
84
+ "application/octet-stream",
85
+ file,
86
+ Parts.offset(n, blockSize),
87
+ length,
88
+ null,
89
+ progress,
90
+ (w) -> progress.onBytes(UploadAdapters.pending(base + w, total), total),
91
+ null,
92
+ what
93
+ );
94
+ if (a.status != 201) throw TransferException.forStatus(a.status, what);
95
+ r.parts.put(n, ids.get(n - 1));
96
+ stored += length;
97
+ progress.saveState();
98
+ progress.onBytes(UploadAdapters.pending(stored, total), total);
99
+ }
100
+ Pause.check(progress);
101
+ byte[] body = PartsXml.blockListBody(ids).getBytes(java.nio.charset.StandardCharsets.UTF_8);
102
+ Http.Answer a = Http.send(
103
+ "PUT",
104
+ Http.withQuery(r.url, "comp=blocklist"),
105
+ r.headers,
106
+ "application/xml",
107
+ null,
108
+ 0,
109
+ 0,
110
+ body,
111
+ progress,
112
+ null,
113
+ () -> {
114
+ r.committing = true;
115
+ progress.saveState();
116
+ },
117
+ "commit (Put Block List)"
118
+ );
119
+ if (a.status == 201) {
120
+ progress.onBytes(total, total);
121
+ return total;
122
+ }
123
+ r.committing = false;
124
+ progress.saveState();
125
+ throw TransferException.forStatus(a.status, "commit (Put Block List)");
126
+ }
127
+
128
+ /**
129
+ * The headers for a block: all but the blob's properties ({@code x-ms-blob-content-type} and
130
+ * the other {@code x-ms-blob-*} ones), which belong to the commit that creates the blob.
131
+ */
132
+ static Map<String, String> blockHeaders(Map<String, String> headers) {
133
+ Map<String, String> out = new java.util.LinkedHashMap<>();
134
+ if (headers == null) return out;
135
+ for (Map.Entry<String, String> h : headers.entrySet()) {
136
+ if (!h.getKey().toLowerCase(java.util.Locale.ROOT).startsWith("x-ms-blob-")) out.put(h.getKey(), h.getValue());
137
+ }
138
+ return out;
139
+ }
140
+
141
+ private static String encode(String id) {
142
+ try {
143
+ return URLEncoder.encode(id, "UTF-8");
144
+ } catch (UnsupportedEncodingException e) {
145
+ throw new IllegalStateException(e);
146
+ }
147
+ }
148
+ }
@@ -0,0 +1,279 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import com.getcapacitor.JSArray;
4
+ import com.getcapacitor.JSObject;
5
+ import com.getcapacitor.Plugin;
6
+ import com.getcapacitor.PluginCall;
7
+ import com.getcapacitor.PluginMethod;
8
+ import com.getcapacitor.annotation.CapacitorPlugin;
9
+ import java.io.File;
10
+ import java.util.ArrayList;
11
+ import java.util.HashSet;
12
+ import java.util.Iterator;
13
+ import java.util.List;
14
+ import java.util.Set;
15
+ import org.json.JSONArray;
16
+ import org.json.JSONException;
17
+ import org.json.JSONObject;
18
+
19
+ /**
20
+ * The JavaScript side's handle on background transfers: queue an upload or a
21
+ * download, cancel one, list what ran while the app was away, and hear
22
+ * progress and state changes while it is open. The work itself is done by
23
+ * {@link TransferJobService} (Android 14+) or {@link TransferWorker} (below),
24
+ * through {@link Runner}.
25
+ */
26
+ @CapacitorPlugin(name = "BackgroundTransfer")
27
+ public class BackgroundTransferPlugin extends Plugin implements Runner.Events {
28
+
29
+ private TransferStore store;
30
+
31
+ @Override
32
+ public void load() {
33
+ store = Scheduler.store(getContext());
34
+ Runner.setEvents(this);
35
+ // The app has just opened, so it is visible and a host may be scheduled.
36
+ getBridge().execute(() -> {
37
+ for (String direction : new String[] { TransferRecord.UPLOAD, TransferRecord.DOWNLOAD }) {
38
+ try {
39
+ if (Runner.reconcile(store, direction, Scheduler.hostScheduled(getContext(), direction))) {
40
+ Scheduler.schedule(getContext(), direction);
41
+ }
42
+ } catch (RuntimeException e) {
43
+ android.util.Log.w("BackgroundTransfer", "could not resume the " + direction + " queue: " + e);
44
+ }
45
+ }
46
+ });
47
+ }
48
+
49
+ @Override
50
+ protected void handleOnDestroy() {
51
+ if (Runner.events() == this) Runner.setEvents(null);
52
+ }
53
+
54
+ @Override
55
+ public void onEvent(String name, TransferRecord r) {
56
+ try {
57
+ notifyListeners(name, event(r));
58
+ } catch (JSONException ignored) {
59
+ // A record always serialises; nothing to tell.
60
+ }
61
+ }
62
+
63
+ private static JSObject event(TransferRecord r) throws JSONException {
64
+ JSObject o = new JSObject();
65
+ o.put("transfer", r.toJson(true));
66
+ return o;
67
+ }
68
+
69
+ @PluginMethod
70
+ public void isAvailable(PluginCall call) {
71
+ JSObject o = new JSObject();
72
+ o.put("available", true);
73
+ o.put("mechanism", Scheduler.usesJob() ? "job" : "worker");
74
+ String problem = Scheduler.foregroundServiceProblem(getContext());
75
+ if (problem != null) o.put("warning", problem);
76
+ call.resolve(o);
77
+ }
78
+
79
+ @PluginMethod
80
+ public void upload(PluginCall call) {
81
+ start(call, TransferRecord.UPLOAD);
82
+ }
83
+
84
+ @PluginMethod
85
+ public void download(PluginCall call) {
86
+ start(call, TransferRecord.DOWNLOAD);
87
+ }
88
+
89
+ private void start(PluginCall call, String direction) {
90
+ String id = call.getString("id");
91
+ String url = call.getString("url");
92
+ String path = call.getString("path");
93
+ if (id == null || id.isEmpty() || url == null || path == null || !path.startsWith("/")) {
94
+ call.reject("id, url and an absolute path are required");
95
+ return;
96
+ }
97
+ // The wrapper's checks, repeated here: a script can call the plugin without it.
98
+ String refusedUrl = TransferPaths.checkUrl(url);
99
+ if (refusedUrl != null) {
100
+ call.reject(refusedUrl);
101
+ return;
102
+ }
103
+ String refusedPath = TransferPaths.confine(
104
+ path,
105
+ allowedRoots(),
106
+ Scheduler.storeDir(getContext()),
107
+ TransferRecord.DOWNLOAD.equals(direction)
108
+ );
109
+ if (refusedPath != null) {
110
+ call.reject(refusedPath);
111
+ return;
112
+ }
113
+ TransferRecord r = new TransferRecord();
114
+ r.id = id;
115
+ r.direction = direction;
116
+ r.url = url;
117
+ r.path = path;
118
+ if (TransferRecord.UPLOAD.equals(direction)) {
119
+ String protocol = UploadAdapters.resolve(call.getString("protocol"));
120
+ if (protocol == null) {
121
+ call.reject(UploadAdapters.refusal());
122
+ return;
123
+ }
124
+ r.protocol = protocol;
125
+ String refused = readProtocolOptions(call, r, path);
126
+ if (refused != null) {
127
+ call.reject(refused);
128
+ return;
129
+ }
130
+ }
131
+ JSObject headers = call.getObject("headers");
132
+ if (headers != null) {
133
+ Iterator<String> names = headers.keys();
134
+ while (names.hasNext()) {
135
+ String name = names.next();
136
+ String value = headers.getString(name);
137
+ if (value != null) r.headers.put(name, value);
138
+ }
139
+ String refusedHeader = TransferPaths.checkHeaders(r.headers);
140
+ if (refusedHeader != null) {
141
+ call.reject(refusedHeader);
142
+ return;
143
+ }
144
+ }
145
+ JSObject n = call.getObject("notification");
146
+ if (n != null) {
147
+ r.channelId = n.getString("channelId");
148
+ r.channelName = n.getString("channelName");
149
+ r.title = n.getString("title");
150
+ r.text = n.getString("text");
151
+ }
152
+ getBridge().execute(() -> {
153
+ try {
154
+ Runner.Enqueued queued = Runner.enqueue(store, r);
155
+ // No run in this process: schedule afresh, replacing any job the system is holding back
156
+ // (after a quota or other system stop it can wait minutes). The app is visible now.
157
+ if (queued.needsHost) Scheduler.schedule(getContext(), direction);
158
+ call.resolve(event(queued.record));
159
+ } catch (Exception e) {
160
+ call.reject("could not start the " + direction + ": " + e.getMessage(), e);
161
+ }
162
+ });
163
+ }
164
+
165
+ /**
166
+ * Where a transfer's file may be: the app's own directories (internal and external files and
167
+ * cache, and the no-backup files), plus any absolute paths the app lists under
168
+ * {@code allowedRoots} in the plugin's configuration (never from JavaScript).
169
+ */
170
+ private List<File> allowedRoots() {
171
+ android.content.Context context = getContext().getApplicationContext();
172
+ List<File> roots = new ArrayList<>();
173
+ roots.add(context.getFilesDir());
174
+ roots.add(context.getNoBackupFilesDir());
175
+ roots.add(context.getCacheDir());
176
+ File[] external = context.getExternalFilesDirs(null);
177
+ if (external != null) roots.addAll(java.util.Arrays.asList(external));
178
+ File[] externalCache = context.getExternalCacheDirs();
179
+ if (externalCache != null) roots.addAll(java.util.Arrays.asList(externalCache));
180
+ String[] configured = getConfig().getArray("allowedRoots");
181
+ if (configured != null) for (String p : configured) if (p != null && p.startsWith("/")) roots.add(new File(p));
182
+ return roots;
183
+ }
184
+
185
+ /**
186
+ * Reads {@code partUrls}, {@code partSize}, {@code listPartsUrl} and {@code blockSize} into
187
+ * {@code r}, and returns what is wrong with them (as the JavaScript side words it), or null.
188
+ */
189
+ static String readProtocolOptions(PluginCall call, TransferRecord r, String path) {
190
+ JSONObject data = call.getData();
191
+ List<Object> partUrls = null;
192
+ JSONArray urls = data.optJSONArray("partUrls");
193
+ if (urls != null) {
194
+ partUrls = new ArrayList<>();
195
+ for (int i = 0; i < urls.length(); i++) partUrls.add(urls.opt(i));
196
+ } else if (data.has("partUrls") && !data.isNull("partUrls")) {
197
+ partUrls = new ArrayList<>(); // Not an array: refused as missing.
198
+ }
199
+ Double partSize = number(data, "partSize");
200
+ Double blockSize = number(data, "blockSize");
201
+ Object listPartsUrl = data.isNull("listPartsUrl") ? null : data.opt("listPartsUrl");
202
+ if (data.has("partSize") && !data.isNull("partSize") && partSize == null) partSize = Double.NaN;
203
+ if (data.has("blockSize") && !data.isNull("blockSize") && blockSize == null) blockSize = Double.NaN;
204
+ String refused = UploadOptionsCheck.check(r.protocol, r.url, partUrls, partSize, listPartsUrl, blockSize);
205
+ if (refused != null) return refused;
206
+ if (partUrls != null) for (Object u : partUrls) r.partUrls.add((String) u);
207
+ r.partSize = partSize != null ? partSize.longValue() : 0;
208
+ r.listPartsUrl = (String) listPartsUrl;
209
+ r.blockSize = blockSize != null ? blockSize.longValue() : 0;
210
+ File file = new File(path);
211
+ if (file.isFile()) {
212
+ // A missing file is reported when the upload runs (file-missing), as for every protocol.
213
+ return UploadOptionsCheck.checkSize(
214
+ r.protocol,
215
+ r.partUrls.size(),
216
+ r.partSize > 0 ? r.partSize : UploadOptionsCheck.DEFAULT_PART_SIZE,
217
+ r.blockSize > 0 ? r.blockSize : UploadOptionsCheck.DEFAULT_PART_SIZE,
218
+ file.length()
219
+ );
220
+ }
221
+ return null;
222
+ }
223
+
224
+ private static Double number(JSONObject data, String name) {
225
+ Object v = data.opt(name);
226
+ return v instanceof Number ? ((Number) v).doubleValue() : null;
227
+ }
228
+
229
+ @PluginMethod
230
+ public void cancel(PluginCall call) {
231
+ String id = call.getString("id");
232
+ String direction = call.getString("direction");
233
+ if (id == null || !(TransferRecord.UPLOAD.equals(direction) || TransferRecord.DOWNLOAD.equals(direction))) {
234
+ call.reject("id and direction are required");
235
+ return;
236
+ }
237
+ getBridge().execute(() -> {
238
+ Runner.cancel(store, direction, id);
239
+ call.resolve();
240
+ });
241
+ }
242
+
243
+ @PluginMethod
244
+ public void list(PluginCall call) {
245
+ getBridge().execute(() -> {
246
+ try {
247
+ JSArray list = new JSArray();
248
+ for (TransferRecord r : store.all()) list.put(r.toJson(true));
249
+ JSObject o = new JSObject();
250
+ o.put("transfers", list);
251
+ call.resolve(o);
252
+ } catch (JSONException e) {
253
+ call.reject("could not list transfers", e);
254
+ }
255
+ });
256
+ }
257
+
258
+ @PluginMethod
259
+ public void forget(PluginCall call) {
260
+ JSArray ids = call.getArray("ids");
261
+ getBridge().execute(() -> {
262
+ Set<String> only = null;
263
+ if (ids != null) {
264
+ only = new HashSet<>();
265
+ JSONArray list = ids;
266
+ for (int i = 0; i < list.length(); i++) {
267
+ JSONObject o = list.optJSONObject(i);
268
+ if (o != null) only.add(TransferRecord.keyOf(o.optString("direction"), o.optString("id")));
269
+ }
270
+ }
271
+ for (TransferRecord r : store.all()) {
272
+ if (r.isActive() || TransferRecord.INTERRUPTED.equals(r.state)) continue;
273
+ if (only != null && !only.contains(r.key())) continue;
274
+ store.remove(r.direction, r.id);
275
+ }
276
+ call.resolve();
277
+ });
278
+ }
279
+ }