capacitor-background-transfer 0.0.0-stage → 0.1.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 +542 -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 +96 -4
@@ -0,0 +1,199 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.io.ByteArrayInputStream;
4
+ import java.nio.charset.StandardCharsets;
5
+ import java.security.MessageDigest;
6
+ import java.util.ArrayList;
7
+ import java.util.LinkedHashMap;
8
+ import java.util.List;
9
+ import java.util.Map;
10
+ import javax.xml.parsers.DocumentBuilderFactory;
11
+ import org.w3c.dom.Document;
12
+ import org.w3c.dom.Element;
13
+ import org.w3c.dom.Node;
14
+ import org.w3c.dom.NodeList;
15
+
16
+ /** The XML that S3 multipart uploads and Azure block blobs speak, and Azure's block ids. */
17
+ final class PartsXml {
18
+
19
+ private PartsXml() {}
20
+
21
+ /** A part or block the server holds. */
22
+ static final class Held {
23
+
24
+ final String tag;
25
+ final long size;
26
+
27
+ Held(String tag, long size) {
28
+ this.tag = tag;
29
+ this.size = size;
30
+ }
31
+ }
32
+
33
+ /** What {@code ListParts} answered: part number → ETag and size, and whether more pages follow. */
34
+ static final class Listed {
35
+
36
+ final Map<Integer, Held> parts = new LinkedHashMap<>();
37
+ boolean truncated;
38
+ int highest;
39
+ }
40
+
41
+ static Listed listParts(String xml) throws TransferException {
42
+ Element root = parse(xml, "ListParts");
43
+ Listed out = new Listed();
44
+ out.truncated = "true".equalsIgnoreCase(text(root, "IsTruncated"));
45
+ for (Element part : children(root, "Part")) {
46
+ try {
47
+ int n = Integer.parseInt(text(part, "PartNumber").trim());
48
+ out.parts.put(n, new Held(text(part, "ETag"), Long.parseLong(text(part, "Size").trim())));
49
+ out.highest = Math.max(out.highest, n);
50
+ } catch (NumberFormatException e) {
51
+ throw new TransferException(TransferException.Reason.UNKNOWN, "ListParts answered with a part that has no number or size");
52
+ }
53
+ }
54
+ return out;
55
+ }
56
+
57
+ /** The {@code CompleteMultipartUpload} body listing every part. */
58
+ static String completeBody(Map<Integer, String> etags, int count) {
59
+ StringBuilder b = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><CompleteMultipartUpload>");
60
+ for (int n = 1; n <= count; n++) {
61
+ b.append("<Part><PartNumber>")
62
+ .append(n)
63
+ .append("</PartNumber><ETag>")
64
+ .append(escape(etags.get(n)))
65
+ .append("</ETag></Part>");
66
+ }
67
+ return b.append("</CompleteMultipartUpload>").toString();
68
+ }
69
+
70
+ /**
71
+ * The error code in an S3 answer, or null when it isn't an {@code <Error>}. S3 can answer
72
+ * {@code CompleteMultipartUpload} with 200 and an error in the body.
73
+ */
74
+ static String errorCode(String xml) {
75
+ if (xml == null || !xml.contains("<Error")) return null;
76
+ try {
77
+ Element root = parse(xml, "answer");
78
+ if (!"Error".equals(root.getTagName())) return null;
79
+ String code = text(root, "Code");
80
+ return code.isEmpty() ? "Error" : code;
81
+ } catch (TransferException e) {
82
+ return "Error";
83
+ }
84
+ }
85
+
86
+ /** Whether a 200 answer to {@code CompleteMultipartUpload} is the completed object. */
87
+ static boolean isCompleteResult(String xml) {
88
+ return xml != null && xml.contains("CompleteMultipartUploadResult") && errorCode(xml) == null;
89
+ }
90
+
91
+ /** Azure's {@code Get Block List}: block id → size, for the uncommitted blocks. */
92
+ static Map<String, Long> uncommittedBlocks(String xml) throws TransferException {
93
+ Element root = parse(xml, "Get Block List");
94
+ Map<String, Long> out = new LinkedHashMap<>();
95
+ for (Element section : children(root, "UncommittedBlocks")) {
96
+ for (Element block : children(section, "Block")) {
97
+ try {
98
+ out.put(text(block, "Name"), Long.parseLong(text(block, "Size").trim()));
99
+ } catch (NumberFormatException e) {
100
+ throw new TransferException(TransferException.Reason.UNKNOWN, "Get Block List answered with a block that has no size");
101
+ }
102
+ }
103
+ }
104
+ return out;
105
+ }
106
+
107
+ /** The {@code Put Block List} body committing {@code ids} in order. */
108
+ static String blockListBody(List<String> ids) {
109
+ StringBuilder b = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?><BlockList>");
110
+ for (String id : ids) b.append("<Latest>").append(escape(id)).append("</Latest>");
111
+ return b.append("</BlockList>").toString();
112
+ }
113
+
114
+ /**
115
+ * Block {@code n}'s id: the same for the same transfer, file size and block size, so a resumed
116
+ * upload finds its blocks, and different for a different file. Every id of a blob has the same
117
+ * length, as Azure requires. iOS makes the same ids.
118
+ */
119
+ static String blockId(String transferId, long size, long blockSize, int n) {
120
+ String prefix;
121
+ try {
122
+ byte[] hash = MessageDigest.getInstance("SHA-256").digest(
123
+ (transferId + "|" + size + "|" + blockSize).getBytes(StandardCharsets.UTF_8)
124
+ );
125
+ StringBuilder hex = new StringBuilder();
126
+ for (int i = 0; i < 8; i++) hex.append(String.format("%02x", hash[i]));
127
+ prefix = hex.toString();
128
+ } catch (java.security.NoSuchAlgorithmException e) {
129
+ throw new IllegalStateException(e);
130
+ }
131
+ String raw = prefix + "-" + String.format(java.util.Locale.ROOT, "%06d", n);
132
+ return base64(raw.getBytes(StandardCharsets.US_ASCII));
133
+ }
134
+
135
+ private static final char[] B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
136
+
137
+ /** Standard Base64 with padding (java.util.Base64 needs Android 8). */
138
+ static String base64(byte[] in) {
139
+ StringBuilder b = new StringBuilder();
140
+ for (int i = 0; i < in.length; i += 3) {
141
+ int n = (in[i] & 0xff) << 16;
142
+ if (i + 1 < in.length) n |= (in[i + 1] & 0xff) << 8;
143
+ if (i + 2 < in.length) n |= in[i + 2] & 0xff;
144
+ b.append(B64[(n >> 18) & 63]).append(B64[(n >> 12) & 63]);
145
+ b.append(i + 1 < in.length ? B64[(n >> 6) & 63] : '=');
146
+ b.append(i + 2 < in.length ? B64[n & 63] : '=');
147
+ }
148
+ return b.toString();
149
+ }
150
+
151
+ static List<String> blockIds(String transferId, long size, long blockSize, int count) {
152
+ List<String> ids = new ArrayList<>();
153
+ for (int n = 1; n <= count; n++) ids.add(blockId(transferId, size, blockSize, n));
154
+ return ids;
155
+ }
156
+
157
+ private static String escape(String s) {
158
+ if (s == null) return "";
159
+ return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
160
+ }
161
+
162
+ private static Element parse(String xml, String what) throws TransferException {
163
+ try {
164
+ DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
165
+ f.setNamespaceAware(false);
166
+ f.setExpandEntityReferences(false);
167
+ try {
168
+ f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
169
+ } catch (Exception ignored) {
170
+ // Not every parser knows the feature; the answers carry no DOCTYPE anyway.
171
+ }
172
+ Document d = f.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
173
+ return d.getDocumentElement();
174
+ } catch (Exception e) {
175
+ throw new TransferException(TransferException.Reason.UNKNOWN, what + " answered with XML that couldn't be read", 0, e);
176
+ }
177
+ }
178
+
179
+ private static List<Element> children(Element parent, String tag) {
180
+ List<Element> out = new ArrayList<>();
181
+ NodeList nodes = parent.getChildNodes();
182
+ for (int i = 0; i < nodes.getLength(); i++) {
183
+ Node n = nodes.item(i);
184
+ if (n instanceof Element && localName((Element) n).equals(tag)) out.add((Element) n);
185
+ }
186
+ return out;
187
+ }
188
+
189
+ private static String localName(Element e) {
190
+ String name = e.getTagName();
191
+ int colon = name.indexOf(':');
192
+ return colon >= 0 ? name.substring(colon + 1) : name;
193
+ }
194
+
195
+ private static String text(Element parent, String tag) {
196
+ List<Element> found = children(parent, tag);
197
+ return found.isEmpty() ? "" : found.get(0).getTextContent();
198
+ }
199
+ }
@@ -0,0 +1,28 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ /** Waiting between retries without missing a cancel. */
4
+ final class Pause {
5
+
6
+ private Pause() {}
7
+
8
+ /** Throws if the transfer has been told to stop. */
9
+ static void check(Progress progress) throws TransferException {
10
+ String reason = progress.stopReason();
11
+ if (reason != null) throw new TransferException(reason, "stopped: " + reason);
12
+ }
13
+
14
+ /** Sleeps up to {@code millis}, checking for a stop every quarter second. */
15
+ static void sleep(long millis, Progress progress) throws TransferException {
16
+ long until = System.currentTimeMillis() + millis;
17
+ while (System.currentTimeMillis() < until) {
18
+ check(progress);
19
+ try {
20
+ Thread.sleep(Math.min(250, Math.max(1, until - System.currentTimeMillis())));
21
+ } catch (InterruptedException e) {
22
+ Thread.currentThread().interrupt();
23
+ throw new TransferException(TransferException.Reason.STOPPED_BY_SYSTEM, "interrupted");
24
+ }
25
+ }
26
+ check(progress);
27
+ }
28
+ }
@@ -0,0 +1,13 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ /** What an {@link Uploader} or {@link Downloader} reports, and how it is told to stop. */
4
+ public interface Progress {
5
+ /** Bytes the server holds (upload) or that are on disk (download), and the total (-1 if unknown). */
6
+ void onBytes(long bytes, long total);
7
+
8
+ /** Checked between chunks and reads: non-null stops the transfer with that reason. */
9
+ String stopReason();
10
+
11
+ /** Saves the record now: an adapter has changed what it resumes from (a part sent, the commit sent). */
12
+ default void saveState() {}
13
+ }
@@ -0,0 +1,47 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.io.File;
4
+
5
+ /**
6
+ * Sends the whole file in one {@code PUT} (an S3 presigned URL, an Azure SAS URL with
7
+ * {@code x-ms-blob-type: BlockBlob}, or any server that takes one). Nothing to resume from: an
8
+ * interrupted upload sends the file again from the first byte. Finished only on a 2xx.
9
+ */
10
+ final class PutUploader implements UploadAdapter {
11
+
12
+ private final int retries;
13
+ private final long backoffMillis;
14
+
15
+ PutUploader(int retries, long backoffMillis) {
16
+ this.retries = retries;
17
+ this.backoffMillis = backoffMillis;
18
+ }
19
+
20
+ @Override
21
+ public long run(TransferRecord r, Progress progress) throws TransferException {
22
+ return UploadAdapters.withRetries(retries, backoffMillis, progress, () -> attempt(r, progress));
23
+ }
24
+
25
+ private static long attempt(TransferRecord r, Progress progress) throws TransferException {
26
+ File file = UploadAdapters.fileOf(r);
27
+ long total = file.length();
28
+ progress.onBytes(0, total);
29
+ Http.Answer a = Http.send(
30
+ "PUT",
31
+ r.url,
32
+ r.headers,
33
+ "application/octet-stream",
34
+ file,
35
+ 0,
36
+ total,
37
+ null,
38
+ progress,
39
+ (w) -> progress.onBytes(UploadAdapters.pending(w, total), total),
40
+ null,
41
+ "PUT"
42
+ );
43
+ if (a.status / 100 != 2) throw TransferException.forStatus(a.status, "PUT");
44
+ progress.onBytes(total, total);
45
+ return total;
46
+ }
47
+ }
@@ -0,0 +1,369 @@
1
+ package io.github.sandman92.backgroundtransfer;
2
+
3
+ import java.io.File;
4
+ import java.util.Map;
5
+ import java.util.concurrent.ConcurrentHashMap;
6
+
7
+ /**
8
+ * Works through one direction's queue, one transfer at a time, oldest first,
9
+ * for whichever host is running it: the user-initiated job (Android 14+) or
10
+ * the WorkManager worker (below 14). Keeps every record in the
11
+ * {@link TransferStore} and tells the plugin (if the app is open) what
12
+ * changed.
13
+ *
14
+ * Plain Java apart from what the {@link Host} does, so the queue rules run
15
+ * under JUnit.
16
+ */
17
+ public final class Runner {
18
+
19
+ /** What a drain ended with. */
20
+ public enum Outcome {
21
+ /** The queue is empty. */
22
+ DONE,
23
+ /** The host should be rescheduled by the system (the job, after the network went or the system stopped it). */
24
+ RESCHEDULE,
25
+ /** A transfer was interrupted and the host can't wait for the network (the worker): the rest waits for the next open. */
26
+ INTERRUPTED
27
+ }
28
+
29
+ /** The job or the worker. */
30
+ public interface Host {
31
+ /** Shows the transfer's progress (the notification, the job's byte counts). */
32
+ void onProgress(TransferRecord r);
33
+
34
+ /** Whether the system restarts this host when the network comes back (the job: yes). */
35
+ boolean waitsForNetwork();
36
+
37
+ /** Non-null once the system has told the host to stop. */
38
+ String systemStopReason();
39
+ }
40
+
41
+ /** The plugin, while the app is open. */
42
+ public interface Events {
43
+ void onEvent(String name, TransferRecord r);
44
+ }
45
+
46
+ /** A job that has failed this many runs in a row without moving a byte is reported as interrupted. */
47
+ static final int MAX_IDLE_RUNS = 8;
48
+
49
+ /** Retries within one run before a network error ends it; lowered by the tests. */
50
+ static int retries = 3;
51
+ static long backoffMillis = 2000;
52
+
53
+ private static final long PROGRESS_EVERY_MS = 250;
54
+ private static final long SAVE_EVERY_MS = 2000;
55
+ private static final long NOTIFY_EVERY_MS = 1000;
56
+
57
+ private static final Map<String, Object> locks = new ConcurrentHashMap<>();
58
+ private static final Map<String, Boolean> active = new ConcurrentHashMap<>();
59
+ private static final Map<String, String> current = new ConcurrentHashMap<>();
60
+ private static final Map<String, String> stopRequests = new ConcurrentHashMap<>();
61
+ private static volatile Events events;
62
+ private static long lastQueuedAt;
63
+
64
+ private Runner() {}
65
+
66
+ public static void setEvents(Events e) {
67
+ events = e;
68
+ }
69
+
70
+ public static Events events() {
71
+ return events;
72
+ }
73
+
74
+ static Object lock(String direction) {
75
+ return locks.computeIfAbsent(direction, (d) -> new Object());
76
+ }
77
+
78
+ /** Whether a host in this process is working through {@code direction}'s queue. */
79
+ public static boolean isActive(String direction) {
80
+ return Boolean.TRUE.equals(active.get(direction));
81
+ }
82
+
83
+ /** Claims the queue for a host; false if another host in this process already has it. */
84
+ public static boolean begin(String direction) {
85
+ synchronized (lock(direction)) {
86
+ if (isActive(direction)) return false;
87
+ active.put(direction, true);
88
+ return true;
89
+ }
90
+ }
91
+
92
+ /** Lets go of the queue (a host that stopped early). */
93
+ public static void end(String direction) {
94
+ synchronized (lock(direction)) {
95
+ active.put(direction, false);
96
+ }
97
+ }
98
+
99
+ private static synchronized long nextQueuedAt() {
100
+ lastQueuedAt = Math.max(System.currentTimeMillis(), lastQueuedAt + 1);
101
+ return lastQueuedAt;
102
+ }
103
+
104
+ /** The result of {@link #enqueue}. */
105
+ public static final class Enqueued {
106
+
107
+ public final TransferRecord record;
108
+ /** True when no host is working through the queue, so the caller must schedule one. */
109
+ public final boolean needsHost;
110
+
111
+ Enqueued(TransferRecord record, boolean needsHost) {
112
+ this.record = record;
113
+ this.needsHost = needsHost;
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Queues {@code wanted}. A transfer with the same id that is already
119
+ * queued or running is left alone and returned; one that is finished,
120
+ * interrupted, failed or cancelled is replaced and starts again (from the
121
+ * server's offset or the {@code .part} file).
122
+ */
123
+ public static Enqueued enqueue(TransferStore store, TransferRecord wanted) {
124
+ synchronized (lock(wanted.direction)) {
125
+ TransferRecord existing = store.get(wanted.direction, wanted.id);
126
+ if (existing != null && existing.isActive()) {
127
+ return new Enqueued(existing, !isActive(wanted.direction));
128
+ }
129
+ wanted.state = TransferRecord.QUEUED;
130
+ wanted.reason = null;
131
+ wanted.message = null;
132
+ wanted.httpStatus = 0;
133
+ wanted.idleRuns = 0;
134
+ wanted.queuedAt = nextQueuedAt();
135
+ if (TransferRecord.DOWNLOAD.equals(wanted.direction)) {
136
+ File part = Downloader.partFile(new File(wanted.path));
137
+ wanted.bytes = part.isFile() ? part.length() : 0;
138
+ } else if (UploadAdapters.PUT.equals(wanted.protocol)) {
139
+ // A PUT starts from the first byte every time.
140
+ wanted.bytes = 0;
141
+ } else if (carriesOver(existing, wanted, new File(wanted.path).length())) {
142
+ wanted.bytes = existing.bytes;
143
+ wanted.total = existing.total;
144
+ // The same upload: what it sent, and whether its commit went, carry over.
145
+ wanted.parts = existing.parts;
146
+ wanted.committing = existing.committing;
147
+ }
148
+ TransferRecord stored = store.put(wanted);
149
+ emit("stateChange", stored);
150
+ return new Enqueued(stored, !isActive(wanted.direction));
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Whether a restarted upload is the same one as {@code existing}, so what that one sent carries
156
+ * over: the same URL and protocol, and for one in parts the same part or block size and file
157
+ * size too (parts recorded for other ranges would otherwise be skipped as stored).
158
+ */
159
+ static boolean carriesOver(TransferRecord existing, TransferRecord wanted, long fileSize) {
160
+ if (existing == null || !existing.url.equals(wanted.url) || !existing.protocol.equals(wanted.protocol)) return false;
161
+ if (UploadAdapters.S3_MULTIPART.equals(wanted.protocol) || UploadAdapters.AZURE_BLOCKS.equals(wanted.protocol)) {
162
+ return existing.partSize == wanted.partSize && existing.blockSize == wanted.blockSize && existing.total == fileSize;
163
+ }
164
+ return true;
165
+ }
166
+
167
+ /**
168
+ * Cancels a transfer. A running one is stopped by its host, which then
169
+ * cleans up; any other active or interrupted one is cancelled here.
170
+ */
171
+ public static void cancel(TransferStore store, String direction, String id) {
172
+ synchronized (lock(direction)) {
173
+ TransferRecord r = store.get(direction, id);
174
+ if (r == null) return;
175
+ if (r.key().equals(current.get(direction))) {
176
+ stopRequests.put(r.key(), TransferException.Reason.CANCELLED);
177
+ return;
178
+ }
179
+ if (r.isActive() || TransferRecord.INTERRUPTED.equals(r.state)) {
180
+ cleanUp(r);
181
+ r.state = TransferRecord.CANCELLED;
182
+ r.reason = TransferException.Reason.CANCELLED;
183
+ r.message = "cancelled";
184
+ emit("stateChange", store.put(r));
185
+ }
186
+ }
187
+ }
188
+
189
+ /**
190
+ * After the app opens: a record left {@code running} by a process that
191
+ * died is queued again if a host is still scheduled for it, and otherwise
192
+ * reported as interrupted. Returns true if there is queued work and no host
193
+ * is running it in this process, so the caller should schedule one: a job
194
+ * the system still holds (after a quota or other system stop it may hold it
195
+ * for a long time) is replaced by a fresh one while the app is visible.
196
+ */
197
+ public static boolean reconcile(TransferStore store, String direction, boolean hostScheduled) {
198
+ synchronized (lock(direction)) {
199
+ if (isActive(direction)) return false;
200
+ boolean queued = false;
201
+ for (TransferRecord r : store.all()) {
202
+ if (!direction.equals(r.direction)) continue;
203
+ if (TransferRecord.RUNNING.equals(r.state)) {
204
+ if (hostScheduled) {
205
+ r.state = TransferRecord.QUEUED;
206
+ } else {
207
+ r.state = TransferRecord.INTERRUPTED;
208
+ r.reason = TransferException.Reason.STOPPED_BY_SYSTEM;
209
+ r.message = "the app was stopped while this was running";
210
+ }
211
+ emit("stateChange", store.put(r));
212
+ }
213
+ if (TransferRecord.QUEUED.equals(r.state)) queued = true;
214
+ }
215
+ return queued;
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Works through the queue until it is empty, the host is stopped, or a
221
+ * transfer is interrupted and the host can't wait for the network.
222
+ * The caller must have called {@link #begin}; this always lets go.
223
+ */
224
+ public static Outcome drain(TransferStore store, String direction, Host host) {
225
+ try {
226
+ synchronized (lock(direction)) {
227
+ // A record left running by a process that died (killed, or stopped mid-run) is this
228
+ // host's to carry on: nothing else in this process is running the queue.
229
+ for (TransferRecord r : store.all()) {
230
+ if (direction.equals(r.direction) && TransferRecord.RUNNING.equals(r.state)) {
231
+ r.state = TransferRecord.QUEUED;
232
+ store.put(r);
233
+ }
234
+ }
235
+ }
236
+ while (true) {
237
+ TransferRecord r;
238
+ synchronized (lock(direction)) {
239
+ if (host.systemStopReason() != null) return Outcome.RESCHEDULE;
240
+ r = store.nextQueued(direction);
241
+ if (r == null) {
242
+ active.put(direction, false);
243
+ return Outcome.DONE;
244
+ }
245
+ r.state = TransferRecord.RUNNING;
246
+ r.reason = null;
247
+ r.message = null;
248
+ r.httpStatus = 0;
249
+ // A cancel that landed after an earlier run of this id ended isn't for this run.
250
+ stopRequests.remove(r.key());
251
+ current.put(direction, r.key());
252
+ r = store.put(r);
253
+ }
254
+ emit("stateChange", r);
255
+ host.onProgress(r);
256
+ Outcome outcome = runOne(store, r, host);
257
+ if (outcome != null) return outcome;
258
+ }
259
+ } finally {
260
+ synchronized (lock(direction)) {
261
+ active.put(direction, false);
262
+ current.remove(direction);
263
+ }
264
+ }
265
+ }
266
+
267
+ /** Runs one transfer to its end; returns non-null if the drain should stop. */
268
+ private static Outcome runOne(TransferStore store, TransferRecord r, Host host) {
269
+ final long startBytes = r.bytes;
270
+ final long[] stamps = { 0, System.currentTimeMillis(), 0 }; // progress, save, notify
271
+ Progress progress = new Progress() {
272
+ @Override
273
+ public void onBytes(long bytes, long total) {
274
+ r.bytes = bytes;
275
+ r.total = total;
276
+ long now = System.currentTimeMillis();
277
+ boolean done = total >= 0 && bytes >= total;
278
+ if (done || now - stamps[0] >= PROGRESS_EVERY_MS) {
279
+ stamps[0] = now;
280
+ emit("progress", r);
281
+ }
282
+ if (done || now - stamps[1] >= SAVE_EVERY_MS) {
283
+ stamps[1] = now;
284
+ store.put(r);
285
+ }
286
+ if (done || now - stamps[2] >= NOTIFY_EVERY_MS) {
287
+ stamps[2] = now;
288
+ host.onProgress(r);
289
+ }
290
+ }
291
+
292
+ @Override
293
+ public String stopReason() {
294
+ String asked = stopRequests.get(r.key());
295
+ return asked != null ? asked : host.systemStopReason();
296
+ }
297
+
298
+ @Override
299
+ public void saveState() {
300
+ stamps[1] = System.currentTimeMillis();
301
+ store.put(r);
302
+ }
303
+ };
304
+ try {
305
+ long total = TransferRecord.UPLOAD.equals(r.direction)
306
+ ? UploadAdapters.forProtocol(r.protocol, retries, backoffMillis).run(r, progress)
307
+ : new Downloader(retries, backoffMillis).run(r.url, new File(r.path), r.headers, progress);
308
+ r.state = TransferRecord.FINISHED;
309
+ r.bytes = total;
310
+ r.total = total;
311
+ r.idleRuns = 0;
312
+ emit("stateChange", store.put(r));
313
+ return null;
314
+ } catch (TransferException e) {
315
+ return stopped(store, r, host, e, r.bytes > startBytes);
316
+ } catch (RuntimeException e) {
317
+ return stopped(store, r, host, new TransferException(TransferException.Reason.UNKNOWN, String.valueOf(e), 0, e), false);
318
+ } finally {
319
+ synchronized (lock(r.direction)) {
320
+ // No longer running: a cancel from here on finds the record's final state instead.
321
+ current.remove(r.direction);
322
+ stopRequests.remove(r.key());
323
+ }
324
+ }
325
+ }
326
+
327
+ private static Outcome stopped(TransferStore store, TransferRecord r, Host host, TransferException e, boolean moved) {
328
+ r.reason = e.reason;
329
+ r.message = e.getMessage();
330
+ r.httpStatus = e.httpStatus;
331
+ if (TransferException.Reason.CANCELLED.equals(e.reason)) {
332
+ cleanUp(r);
333
+ r.state = TransferRecord.CANCELLED;
334
+ emit("stateChange", store.put(r));
335
+ return null;
336
+ }
337
+ if (e.isResumable()) {
338
+ r.idleRuns = moved ? 0 : r.idleRuns + 1;
339
+ boolean systemStop = host.systemStopReason() != null;
340
+ if (host.waitsForNetwork() && (systemStop || r.idleRuns < MAX_IDLE_RUNS)) {
341
+ // The job: back in the queue, first in line; the system starts the job again when it can.
342
+ r.state = TransferRecord.QUEUED;
343
+ emit("stateChange", store.put(r));
344
+ return Outcome.RESCHEDULE;
345
+ }
346
+ r.state = TransferRecord.INTERRUPTED;
347
+ emit("stateChange", store.put(r));
348
+ // The worker can't come back by itself: leave the rest queued for the next open.
349
+ return host.waitsForNetwork() ? null : Outcome.INTERRUPTED;
350
+ }
351
+ cleanUp(r);
352
+ r.state = TransferRecord.FAILED;
353
+ emit("stateChange", store.put(r));
354
+ return null;
355
+ }
356
+
357
+ /** Removes a transfer's temporary files: a download's {@code .part}. An upload has none on Android (parts are read in place). */
358
+ static void cleanUp(TransferRecord r) {
359
+ if (TransferRecord.DOWNLOAD.equals(r.direction)) {
360
+ Downloader.deleteQuietly(Downloader.partFile(new File(r.path)));
361
+ r.bytes = 0;
362
+ }
363
+ }
364
+
365
+ private static void emit(String name, TransferRecord r) {
366
+ Events e = events;
367
+ if (e != null) e.onEvent(name, r);
368
+ }
369
+ }