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,244 @@
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.io.InputStream;
7
+ import java.net.HttpURLConnection;
8
+ import java.net.URL;
9
+ import java.nio.file.Files;
10
+ import java.util.Map;
11
+ import java.util.regex.Matcher;
12
+ import java.util.regex.Pattern;
13
+
14
+ /**
15
+ * Fetches a URL into {@code <dest>.part}, resuming from that file's size with
16
+ * a {@code Range} request, and renames it to {@code dest} only once every
17
+ * byte has landed. A half-finished file never sits at {@code dest}.
18
+ *
19
+ * Plain Java (no Android types), so it runs under JUnit against a local
20
+ * server.
21
+ */
22
+ public final class Downloader {
23
+
24
+ private static final int BUFFER = 256 * 1024;
25
+ private static final Pattern CONTENT_RANGE = Pattern.compile("bytes\\s+(?:(\\d+)-(\\d+)|\\*)/(\\d+|\\*)");
26
+
27
+ private final int retries;
28
+ private final long backoffMillis;
29
+
30
+ public Downloader() {
31
+ this(3, 2000);
32
+ }
33
+
34
+ /** For tests: quicker retries. */
35
+ public Downloader(int retries, long backoffMillis) {
36
+ this.retries = retries;
37
+ this.backoffMillis = backoffMillis;
38
+ }
39
+
40
+ /** A parsed {@code Content-Range}: {@code start} is -1 for {@code bytes *}, {@code total} -1 for {@code /*}. */
41
+ public static final class Range {
42
+
43
+ public final long start;
44
+ public final long end;
45
+ public final long total;
46
+
47
+ Range(long start, long end, long total) {
48
+ this.start = start;
49
+ this.end = end;
50
+ this.total = total;
51
+ }
52
+ }
53
+
54
+ /** Parses {@code bytes 100-199/1000} or {@code bytes *}{@code /1000}; null when it isn't one. */
55
+ public static Range parseContentRange(String header) {
56
+ if (header == null) return null;
57
+ Matcher m = CONTENT_RANGE.matcher(header.trim());
58
+ if (!m.matches()) return null;
59
+ long start = m.group(1) == null ? -1 : Long.parseLong(m.group(1));
60
+ long end = m.group(2) == null ? -1 : Long.parseLong(m.group(2));
61
+ long total = "*".equals(m.group(3)) ? -1 : Long.parseLong(m.group(3));
62
+ return new Range(start, end, total);
63
+ }
64
+
65
+ /** Where the bytes go until they have all landed. */
66
+ public static File partFile(File dest) {
67
+ return new File(dest.getPath() + ".part");
68
+ }
69
+
70
+ /** Downloads {@code url} to {@code dest}; returns its size. */
71
+ public long run(String url, File dest, Map<String, String> headers, Progress progress) throws TransferException {
72
+ int attempt = 0;
73
+ while (true) {
74
+ try {
75
+ return attempt(url, dest, headers, progress, true);
76
+ } catch (TransferException e) {
77
+ if (!TransferException.Reason.NETWORK.equals(e.reason) || attempt >= retries) throw e;
78
+ attempt++;
79
+ Pause.sleep(backoffMillis << (attempt - 1), progress);
80
+ }
81
+ }
82
+ }
83
+
84
+ private long attempt(String url, File dest, Map<String, String> headers, Progress progress, boolean mayRestart)
85
+ throws TransferException {
86
+ File part = partFile(dest);
87
+ File dir = dest.getAbsoluteFile().getParentFile();
88
+ if (dir != null && !dir.isDirectory() && !dir.mkdirs()) {
89
+ throw new TransferException(TransferException.Reason.UNKNOWN, "can't make " + dir);
90
+ }
91
+ long have = part.isFile() ? part.length() : 0;
92
+ if (Files.isSymbolicLink(part.toPath()) || Files.isSymbolicLink(dest.toPath())) {
93
+ throw new TransferException(TransferException.Reason.UNKNOWN, "refusing to write through a symbolic link at " + dest);
94
+ }
95
+ Pause.check(progress);
96
+ HttpURLConnection c = null;
97
+ try {
98
+ URL target = new URL(url);
99
+ int code;
100
+ int hops = 0;
101
+ while (true) {
102
+ c = (HttpURLConnection) target.openConnection();
103
+ c.setInstanceFollowRedirects(false);
104
+ c.setUseCaches(false);
105
+ c.setConnectTimeout(30_000);
106
+ c.setReadTimeout(120_000);
107
+ // The byte count must be the file's, not a compressed stream's.
108
+ c.setRequestProperty("Accept-Encoding", "identity");
109
+ if (headers != null) {
110
+ for (Map.Entry<String, String> h : headers.entrySet()) c.setRequestProperty(h.getKey(), h.getValue());
111
+ }
112
+ if (have > 0) c.setRequestProperty("Range", "bytes=" + have + "-");
113
+ code = c.getResponseCode();
114
+ if (!Http.isRedirect(code)) break;
115
+ // Followed on the same origin only, so the headers never reach a host the app didn't name.
116
+ String location = c.getHeaderField("Location");
117
+ URL next = location == null ? null : new URL(target, location);
118
+ c.disconnect();
119
+ c = null;
120
+ if (next == null || !Http.sameOrigin(target, next)) {
121
+ throw new TransferException(
122
+ TransferException.Reason.SESSION_REFUSED,
123
+ "download HTTP " + code + ": redirected to " + (next == null ? "nowhere" : next.getHost()) + ", not followed",
124
+ code,
125
+ null
126
+ );
127
+ }
128
+ if (++hops > TransferPaths.MAX_REDIRECTS) {
129
+ throw new TransferException(TransferException.Reason.SESSION_REFUSED, "download: too many redirects", code, null);
130
+ }
131
+ target = next;
132
+ }
133
+ long total;
134
+ boolean append;
135
+ if (code == 206) {
136
+ Range r = parseContentRange(c.getHeaderField("Content-Range"));
137
+ if (r == null || r.start != have) {
138
+ // Not the range we asked for: start again from nothing.
139
+ deleteQuietly(part);
140
+ if (mayRestart) {
141
+ c.disconnect();
142
+ return attempt(url, dest, headers, progress, false);
143
+ }
144
+ throw new TransferException(
145
+ TransferException.Reason.SIZE_MISMATCH,
146
+ "server sent range " + c.getHeaderField("Content-Range")
147
+ );
148
+ }
149
+ total = r.total;
150
+ append = true;
151
+ } else if (code == 200) {
152
+ total = c.getContentLengthLong();
153
+ have = 0;
154
+ append = false;
155
+ } else if (code == 416 && have > 0) {
156
+ Range r = parseContentRange(c.getHeaderField("Content-Range"));
157
+ if (r != null && r.total == have) {
158
+ progress.onBytes(have, have);
159
+ return finish(part, dest, have);
160
+ }
161
+ deleteQuietly(part);
162
+ if (mayRestart) {
163
+ c.disconnect();
164
+ return attempt(url, dest, headers, progress, false);
165
+ }
166
+ throw TransferException.forStatus(code, "download");
167
+ } else {
168
+ throw TransferException.forStatus(code, "download");
169
+ }
170
+ progress.onBytes(have, total);
171
+ long got = copy(c, part, append, have, total, progress);
172
+ if (total >= 0 && got != total) {
173
+ if (got < total) throw new TransferException(
174
+ TransferException.Reason.NETWORK,
175
+ "connection closed at " + got + " of " + total
176
+ );
177
+ deleteQuietly(part);
178
+ throw new TransferException(TransferException.Reason.SIZE_MISMATCH, "got " + got + " bytes, expected " + total);
179
+ }
180
+ return finish(part, dest, got);
181
+ } catch (IOException e) {
182
+ throw new TransferException(TransferException.Reason.NETWORK, "download: " + e, 0, e);
183
+ } finally {
184
+ if (c != null) c.disconnect();
185
+ }
186
+ }
187
+
188
+ /** Copies the body into {@code part}; returns the part file's size. Network and disk errors are told apart. */
189
+ private static long copy(HttpURLConnection c, File part, boolean append, long have, long total, Progress progress)
190
+ throws TransferException, IOException {
191
+ byte[] buffer = new byte[BUFFER];
192
+ long size = have;
193
+ FileOutputStream out;
194
+ try {
195
+ out = new FileOutputStream(part, append);
196
+ } catch (IOException e) {
197
+ throw TransferException.forDisk(e);
198
+ }
199
+ try (InputStream in = c.getInputStream()) {
200
+ while (true) {
201
+ Pause.check(progress);
202
+ int n = in.read(buffer); // IOException here is the network
203
+ if (n < 0) break;
204
+ try {
205
+ out.write(buffer, 0, n);
206
+ } catch (IOException e) {
207
+ throw TransferException.forDisk(e);
208
+ }
209
+ size += n;
210
+ progress.onBytes(size, total);
211
+ }
212
+ } finally {
213
+ try {
214
+ out.getFD().sync();
215
+ } catch (IOException ignored) {
216
+ // Best effort: the size check below still guards the rename.
217
+ }
218
+ try {
219
+ out.close();
220
+ } catch (IOException e) {
221
+ throw TransferException.forDisk(e);
222
+ }
223
+ }
224
+ return part.length();
225
+ }
226
+
227
+ private static long finish(File part, File dest, long size) throws TransferException {
228
+ if (part.length() != size) {
229
+ throw new TransferException(TransferException.Reason.SIZE_MISMATCH, "part file is " + part.length() + ", expected " + size);
230
+ }
231
+ if (Files.isSymbolicLink(dest.toPath())) {
232
+ throw new TransferException(TransferException.Reason.UNKNOWN, "refusing to replace a symbolic link at " + dest);
233
+ }
234
+ if (dest.exists() && !dest.delete()) {
235
+ throw new TransferException(TransferException.Reason.UNKNOWN, "can't replace " + dest);
236
+ }
237
+ if (!part.renameTo(dest)) throw new TransferException(TransferException.Reason.UNKNOWN, "can't rename " + part + " to " + dest);
238
+ return size;
239
+ }
240
+
241
+ static void deleteQuietly(File f) {
242
+ if (f.exists() && !f.delete()) f.deleteOnExit();
243
+ }
244
+ }
@@ -0,0 +1,238 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.io.ByteArrayOutputStream;
4
+ import java.io.File;
5
+ import java.io.IOException;
6
+ import java.io.InputStream;
7
+ import java.io.OutputStream;
8
+ import java.io.RandomAccessFile;
9
+ import java.net.HttpURLConnection;
10
+ import java.net.URL;
11
+ import java.nio.charset.StandardCharsets;
12
+ import java.util.Map;
13
+
14
+ /** One request of an upload in parts, with its body read from the file in place or from memory. */
15
+ final class Http {
16
+
17
+ /** Bytes written per piece, between progress reports and stop checks. */
18
+ static final int PIECE = 64 * 1024;
19
+ private static final int MAX_BODY = 64 * 1024;
20
+ /**
21
+ * A body write that makes no headway this long ends the request (as a dropped connection).
22
+ * Headway is seen per 64 KiB piece, so only links slower than about 1 KiB/s are taken as stalled.
23
+ */
24
+ static final long STALL_MILLIS = 60_000;
25
+ private static final java.util.concurrent.ScheduledExecutorService WATCHDOG =
26
+ java.util.concurrent.Executors.newSingleThreadScheduledExecutor((r) -> {
27
+ Thread t = new Thread(r, "BackgroundTransfer write watchdog");
28
+ t.setDaemon(true);
29
+ return t;
30
+ });
31
+ private static final boolean ON_ANDROID = String.valueOf(System.getProperty("java.vm.vendor")).contains("Android");
32
+
33
+ private Http() {}
34
+
35
+ /** The answer: status, the headers asked for, and up to 64 KiB of body. */
36
+ static final class Answer {
37
+
38
+ final int status;
39
+ final String etag;
40
+ final String body;
41
+
42
+ Answer(int status, String etag, String body) {
43
+ this.status = status;
44
+ this.etag = etag;
45
+ this.body = body;
46
+ }
47
+ }
48
+
49
+ /** Told after the connection is open and before the body is written (the commit marks itself sent). */
50
+ interface Sending {
51
+ void now() throws TransferException;
52
+ }
53
+
54
+ /** Reports body bytes written as they go: {@code written} of this request. */
55
+ interface Written {
56
+ void bytes(long written);
57
+ }
58
+
59
+ /**
60
+ * Sends {@code method url} with {@code length} bytes of {@code file} from {@code offset} (or
61
+ * {@code body} when it isn't null), checking {@code progress} for a stop between pieces. An I/O
62
+ * error is {@code network}, with {@code what} in the message.
63
+ */
64
+ static Answer send(
65
+ String method,
66
+ String url,
67
+ Map<String, String> headers,
68
+ String contentType,
69
+ File file,
70
+ long offset,
71
+ long length,
72
+ byte[] body,
73
+ Progress progress,
74
+ Written written,
75
+ Sending sending,
76
+ String what
77
+ ) throws TransferException {
78
+ HttpURLConnection c = null;
79
+ try {
80
+ c = (HttpURLConnection) new URL(url).openConnection();
81
+ c.setRequestMethod(method);
82
+ c.setInstanceFollowRedirects(false);
83
+ c.setUseCaches(false);
84
+ c.setConnectTimeout(30_000);
85
+ c.setReadTimeout(120_000);
86
+ boolean hasType = false;
87
+ if (headers != null) {
88
+ for (Map.Entry<String, String> h : headers.entrySet()) {
89
+ c.setRequestProperty(h.getKey(), h.getValue());
90
+ if (h.getKey().equalsIgnoreCase("Content-Type")) hasType = true;
91
+ }
92
+ }
93
+ long size = body != null ? body.length : length;
94
+ boolean sendsBody = body != null || file != null;
95
+ if (sendsBody) {
96
+ c.setDoOutput(true);
97
+ if (!hasType && contentType != null) c.setRequestProperty("Content-Type", contentType);
98
+ c.setFixedLengthStreamingMode(size);
99
+ // A server that will refuse the request (an expired URL) says so before the body goes.
100
+ // The JDK's client needs this to read such an answer; Android's reads it anyway (earlyAnswer).
101
+ if (file != null && length > 0 && !ON_ANDROID) c.setRequestProperty("Expect", "100-continue");
102
+ }
103
+ c.connect();
104
+ if (sending != null) sending.now();
105
+ if (sendsBody) {
106
+ // A write has no timeout of its own: one that makes no headway is ended from outside.
107
+ final HttpURLConnection conn = c;
108
+ final long[] lastWrite = { System.currentTimeMillis() };
109
+ java.util.concurrent.ScheduledFuture<?> watch = WATCHDOG.scheduleWithFixedDelay(
110
+ () -> {
111
+ if (System.currentTimeMillis() - lastWrite[0] > STALL_MILLIS) conn.disconnect();
112
+ },
113
+ 5,
114
+ 5,
115
+ java.util.concurrent.TimeUnit.SECONDS
116
+ );
117
+ Written seen = (w) -> {
118
+ lastWrite[0] = System.currentTimeMillis();
119
+ if (written != null) written.bytes(w);
120
+ };
121
+ try (OutputStream out = c.getOutputStream()) {
122
+ if (body != null) {
123
+ out.write(body);
124
+ } else {
125
+ writeRange(file, offset, length, out, progress, seen);
126
+ }
127
+ } catch (IOException e) {
128
+ // A server that refuses a request (an expired URL, a bad signature) may answer
129
+ // before the body is in and close the connection: read that answer if it came.
130
+ Answer early = earlyAnswer(c);
131
+ if (early != null) return early;
132
+ throw e;
133
+ } finally {
134
+ watch.cancel(false);
135
+ }
136
+ }
137
+ int status = c.getResponseCode();
138
+ return new Answer(status, c.getHeaderField("ETag"), readBody(c, status));
139
+ } catch (IOException e) {
140
+ throw new TransferException(TransferException.Reason.NETWORK, what + ": " + e, 0, e);
141
+ } finally {
142
+ if (c != null) c.disconnect();
143
+ }
144
+ }
145
+
146
+ private static void writeRange(File file, long offset, long length, OutputStream out, Progress progress, Written written)
147
+ throws IOException, TransferException {
148
+ byte[] buffer = new byte[(int) Math.min(PIECE, Math.max(length, 1))];
149
+ RandomAccessFile in;
150
+ try {
151
+ in = new RandomAccessFile(file, "r");
152
+ } catch (IOException e) {
153
+ throw new TransferException(TransferException.Reason.FILE_MISSING, "opening the file: " + e.getMessage(), 0, e);
154
+ }
155
+ try {
156
+ in.seek(offset);
157
+ long sent = 0;
158
+ while (sent < length) {
159
+ Pause.check(progress);
160
+ int n = (int) Math.min(buffer.length, length - sent);
161
+ try {
162
+ in.readFully(buffer, 0, n);
163
+ } catch (IOException e) {
164
+ throw new TransferException(
165
+ file.isFile() ? TransferException.Reason.UNKNOWN : TransferException.Reason.FILE_MISSING,
166
+ "reading the file: " + e.getMessage(),
167
+ 0,
168
+ e
169
+ );
170
+ }
171
+ out.write(buffer, 0, n);
172
+ sent += n;
173
+ if (written != null) written.bytes(sent);
174
+ }
175
+ } finally {
176
+ try {
177
+ in.close();
178
+ } catch (IOException ignored) {
179
+ // Read only.
180
+ }
181
+ }
182
+ }
183
+
184
+ /** A refusal (4xx) the server sent while the body was still going, or null. */
185
+ private static Answer earlyAnswer(HttpURLConnection c) {
186
+ try {
187
+ int status = c.getResponseCode();
188
+ if (status < 400 || status >= 500) return null;
189
+ String body;
190
+ try {
191
+ body = readBody(c, status);
192
+ } catch (IOException e) {
193
+ body = "";
194
+ }
195
+ return new Answer(status, null, body);
196
+ } catch (IOException | RuntimeException e) {
197
+ return null;
198
+ }
199
+ }
200
+
201
+ /** The body; an answer cut off part-way is an I/O error, as a lost answer. */
202
+ private static String readBody(HttpURLConnection c, int status) throws IOException {
203
+ try (InputStream in = status >= 400 ? c.getErrorStream() : c.getInputStream()) {
204
+ if (in == null) return "";
205
+ ByteArrayOutputStream b = new ByteArrayOutputStream();
206
+ byte[] buf = new byte[8192];
207
+ int n;
208
+ while ((n = in.read(buf)) > 0) {
209
+ if (b.size() < MAX_BODY) b.write(buf, 0, n);
210
+ }
211
+ return new String(b.toByteArray(), StandardCharsets.UTF_8);
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Whether {@code next} has the same origin as {@code from}: scheme, host and port. A redirect
217
+ * elsewhere isn't followed, so the caller's headers only ever reach the host it named.
218
+ */
219
+ static boolean sameOrigin(URL from, URL next) {
220
+ if (!from.getProtocol().equalsIgnoreCase(next.getProtocol())) return false;
221
+ if (from.getHost() == null || !from.getHost().equalsIgnoreCase(next.getHost())) return false;
222
+ int a = from.getPort() == -1 ? from.getDefaultPort() : from.getPort();
223
+ int b = next.getPort() == -1 ? next.getDefaultPort() : next.getPort();
224
+ return a == b;
225
+ }
226
+
227
+ /** Whether {@code status} is a redirect with a {@code Location} to follow. */
228
+ static boolean isRedirect(int status) {
229
+ return status == 301 || status == 302 || status == 303 || status == 307 || status == 308;
230
+ }
231
+
232
+ /** {@code url} with {@code extra} added to its query. */
233
+ static String withQuery(String url, String extra) {
234
+ int hash = url.indexOf('#');
235
+ String base = hash >= 0 ? url.substring(0, hash) : url;
236
+ return base + (base.contains("?") ? "&" : "?") + extra;
237
+ }
238
+ }
@@ -0,0 +1,40 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.util.Map;
4
+ import java.util.concurrent.ConcurrentHashMap;
5
+
6
+ /**
7
+ * Each job's current run, by job id. The system hands onStopJob a JobParameters instance of its
8
+ * own, not the one onStartJob got (and they don't compare equal), so the id is the only key both
9
+ * share. A run that ends removes only itself, never a newer run of the same job.
10
+ */
11
+ final class JobRuns {
12
+
13
+ /** What the system told one run. */
14
+ static final class Run {
15
+
16
+ volatile String stopReason;
17
+ volatile boolean byUser;
18
+ }
19
+
20
+ private final Map<Integer, Run> runs = new ConcurrentHashMap<>();
21
+
22
+ Run start(int jobId) {
23
+ Run run = new Run();
24
+ runs.put(jobId, run);
25
+ return run;
26
+ }
27
+
28
+ /** Tells the job's current run to stop; returns false if no run of it is known. */
29
+ boolean stop(int jobId, boolean byUser) {
30
+ Run run = runs.get(jobId);
31
+ if (run == null) return false;
32
+ run.byUser = byUser;
33
+ run.stopReason = TransferException.Reason.STOPPED_BY_SYSTEM;
34
+ return true;
35
+ }
36
+
37
+ void end(int jobId, Run run) {
38
+ runs.remove(jobId, run);
39
+ }
40
+ }
@@ -0,0 +1,54 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import android.app.Notification;
4
+ import android.app.NotificationChannel;
5
+ import android.app.NotificationManager;
6
+ import android.content.Context;
7
+ import android.os.Build;
8
+ import androidx.core.app.NotificationCompat;
9
+
10
+ /**
11
+ * The notification the job or the worker must show while it runs, which is
12
+ * also its progress. Channel, title and text come from the transfer
13
+ * ({@code notification} in its options), with plain defaults. With the
14
+ * notification permission refused it isn't shown, and the transfer still runs.
15
+ */
16
+ final class Notifications {
17
+
18
+ static final String DEFAULT_CHANNEL = "background-transfer";
19
+ static final String DEFAULT_CHANNEL_NAME = "Transfers";
20
+
21
+ private Notifications() {}
22
+
23
+ static int idFor(String direction) {
24
+ return TransferRecord.UPLOAD.equals(direction) ? 0x0B7A0101 : 0x0B7A0102;
25
+ }
26
+
27
+ /** For {@code r}, or a placeholder in {@code direction} before the first transfer starts. */
28
+ static Notification build(Context context, String direction, TransferRecord r) {
29
+ String channelId = r != null && r.channelId != null ? r.channelId : DEFAULT_CHANNEL;
30
+ String channelName = r != null && r.channelName != null ? r.channelName : DEFAULT_CHANNEL_NAME;
31
+ if (Build.VERSION.SDK_INT >= 26) {
32
+ NotificationManager manager = context.getSystemService(NotificationManager.class);
33
+ if (manager != null && manager.getNotificationChannel(channelId) == null) {
34
+ manager.createNotificationChannel(new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW));
35
+ }
36
+ }
37
+ boolean upload = TransferRecord.UPLOAD.equals(direction);
38
+ String title = r != null && r.title != null ? r.title : upload ? "Uploading" : "Downloading";
39
+ NotificationCompat.Builder b = new NotificationCompat.Builder(context, channelId)
40
+ .setSmallIcon(upload ? android.R.drawable.stat_sys_upload : android.R.drawable.stat_sys_download)
41
+ .setContentTitle(title)
42
+ .setOngoing(true)
43
+ .setOnlyAlertOnce(true)
44
+ .setSilent(true)
45
+ .setCategory(NotificationCompat.CATEGORY_PROGRESS);
46
+ if (r != null && r.text != null) b.setContentText(r.text);
47
+ if (r != null && r.total > 0) {
48
+ b.setProgress(1000, (int) Math.min(1000, (r.bytes * 1000) / r.total), false);
49
+ } else {
50
+ b.setProgress(0, 0, true);
51
+ }
52
+ return b.build();
53
+ }
54
+ }
@@ -0,0 +1,25 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ /** How a file divides into parts (S3) or blocks (Azure), numbered from 1. */
4
+ final class Parts {
5
+
6
+ private Parts() {}
7
+
8
+ /**
9
+ * How many {@code partSize}-byte parts a {@code size}-byte file takes. An empty file is one
10
+ * (empty) part when {@code atLeastOne} (S3 needs a part to complete), and none otherwise.
11
+ */
12
+ static int count(long size, long partSize, boolean atLeastOne) {
13
+ if (size <= 0) return atLeastOne ? 1 : 0;
14
+ long n = (size + partSize - 1) / partSize;
15
+ return n > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) n;
16
+ }
17
+
18
+ static long offset(int n, long partSize) {
19
+ return (n - 1) * partSize;
20
+ }
21
+
22
+ static long length(int n, long size, long partSize) {
23
+ return Math.max(0, Math.min(partSize, size - offset(n, partSize)));
24
+ }
25
+ }