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.
- package/CapacitorBackgroundTransfer.podspec +19 -0
- package/LICENSE +21 -0
- package/Package.swift +31 -0
- package/README.md +552 -2
- package/android/build.gradle +71 -0
- package/android/src/main/AndroidManifest.xml +20 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/AzureBlockUploader.java +148 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/BackgroundTransferPlugin.java +279 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Downloader.java +244 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Http.java +238 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/JobRuns.java +40 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Notifications.java +54 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Parts.java +25 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/PartsXml.java +199 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Pause.java +28 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Progress.java +13 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/PutUploader.java +47 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Runner.java +369 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/S3MultipartUploader.java +143 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Scheduler.java +144 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferException.java +65 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferJobService.java +115 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferPaths.java +129 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferRecord.java +163 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferStore.java +121 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferWorker.java +85 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadAdapter.java +11 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadAdapters.java +89 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadOptionsCheck.java +104 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Uploader.java +225 -0
- package/android/src/main/res/.gitkeep +0 -0
- package/dist/docs.json +527 -0
- package/dist/esm/definitions.d.ts +277 -0
- package/dist/esm/definitions.js +24 -0
- package/dist/esm/definitions.js.map +1 -0
- package/dist/esm/index.d.ts +10 -0
- package/dist/esm/index.js +26 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/validate.d.ts +18 -0
- package/dist/esm/validate.js +113 -0
- package/dist/esm/validate.js.map +1 -0
- package/dist/esm/web.d.ts +17 -0
- package/dist/esm/web.js +27 -0
- package/dist/esm/web.js.map +1 -0
- package/dist/plugin.cjs.js +200 -0
- package/dist/plugin.cjs.js.map +1 -0
- package/dist/plugin.js +203 -0
- package/dist/plugin.js.map +1 -0
- package/ios/Sources/BackgroundTransferCore/Files.swift +166 -0
- package/ios/Sources/BackgroundTransferCore/PartsUpload.swift +327 -0
- package/ios/Sources/BackgroundTransferCore/PartsXML.swift +137 -0
- package/ios/Sources/BackgroundTransferCore/TransferPaths.swift +103 -0
- package/ios/Sources/BackgroundTransferCore/TransferRecord.swift +141 -0
- package/ios/Sources/BackgroundTransferCore/TransferStore.swift +69 -0
- package/ios/Sources/BackgroundTransferCore/UploadOptionsCheck.swift +90 -0
- package/ios/Sources/BackgroundTransferCore/UploadOutcome.swift +96 -0
- package/ios/Sources/BackgroundTransferCore/UploadProtocol.swift +30 -0
- package/ios/Sources/BackgroundTransferPlugin/BackgroundTransferPlugin.swift +168 -0
- package/ios/Sources/BackgroundTransferPlugin/TransferManager.swift +1074 -0
- package/package.json +97 -4
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// One transfer, as stored and as reported to JavaScript (`TransferRecord` in definitions.ts).
|
|
4
|
+
public struct TransferRecord: Codable, Equatable {
|
|
5
|
+
public enum Direction: String, Codable { case upload, download }
|
|
6
|
+
public enum State: String, Codable { case queued, running, interrupted, finished, failed, cancelled }
|
|
7
|
+
|
|
8
|
+
public var id: String
|
|
9
|
+
public var direction: Direction
|
|
10
|
+
public var state: State
|
|
11
|
+
public var url: String
|
|
12
|
+
public var path: String
|
|
13
|
+
/// Uploads: the protocol the session speaks (`UploadProtocol`); nil for a download.
|
|
14
|
+
public var `protocol`: String?
|
|
15
|
+
public var bytes: Int64 = 0
|
|
16
|
+
public var total: Int64 = -1
|
|
17
|
+
public var reason: String?
|
|
18
|
+
public var message: String?
|
|
19
|
+
public var httpStatus: Int?
|
|
20
|
+
public var updatedAt: Double = 0
|
|
21
|
+
public var queuedAt: Double = 0
|
|
22
|
+
public var headers: [String: String] = [:]
|
|
23
|
+
/// Upload: the server's offset when this task was made; the task sends the bytes after it.
|
|
24
|
+
public var startOffset: Int64 = 0
|
|
25
|
+
/// Upload: the temporary copy of the bytes after `startOffset`, when there is one.
|
|
26
|
+
public var remainderPath: String?
|
|
27
|
+
/// The URLSession task carrying it, when there is one.
|
|
28
|
+
public var taskIdentifier: Int?
|
|
29
|
+
/// Upload: the HTTP status of a refusal still being checked against the session. Kept so a
|
|
30
|
+
/// launch that finds no answer yet checks again instead of guessing.
|
|
31
|
+
public var refusedStatus: Int?
|
|
32
|
+
/// `s3-multipart`: the presigned part URLs, part 1 first.
|
|
33
|
+
public var partUrls: [String]?
|
|
34
|
+
/// `s3-multipart`: bytes per part; nil for the default.
|
|
35
|
+
public var partSize: Int64?
|
|
36
|
+
/// `s3-multipart`: the presigned ListParts URL.
|
|
37
|
+
public var listPartsUrl: String?
|
|
38
|
+
/// `azure-blocks`: bytes per block; nil for the default.
|
|
39
|
+
public var blockSize: Int64?
|
|
40
|
+
/// Upload in parts: the parts or blocks the server holds, by number ("1", "2", …): the S3 `ETag`
|
|
41
|
+
/// or the Azure block id.
|
|
42
|
+
public var parts: [String: String]?
|
|
43
|
+
/// Upload in parts: the commit (S3 completion, Azure block list) has been handed over. A lost
|
|
44
|
+
/// answer isn't taken as success.
|
|
45
|
+
public var committing: Bool?
|
|
46
|
+
/// Upload in parts: 0 while the commit's task runs (its body file is `remainderPath`).
|
|
47
|
+
public var currentPart: Int?
|
|
48
|
+
/// Upload in parts (iOS): the tasks carrying parts or blocks, by task identifier, each with its
|
|
49
|
+
/// part number and the temporary copy it sends. One while the app is on screen; every remaining
|
|
50
|
+
/// part once the app has left it.
|
|
51
|
+
public var partTasks: [String: PartTask]?
|
|
52
|
+
|
|
53
|
+
public init(id: String, direction: Direction, url: String, path: String) {
|
|
54
|
+
self.id = id
|
|
55
|
+
self.direction = direction
|
|
56
|
+
self.state = .queued
|
|
57
|
+
self.url = url
|
|
58
|
+
self.path = path
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
public var key: String { TransferRecord.key(direction, id) }
|
|
62
|
+
|
|
63
|
+
public static func key(_ direction: Direction, _ id: String) -> String { "\(direction.rawValue):\(id)" }
|
|
64
|
+
|
|
65
|
+
/// Still to run or running: not to be forgotten or started twice.
|
|
66
|
+
public var isActive: Bool { state == .queued || state == .running }
|
|
67
|
+
|
|
68
|
+
/// The shape JavaScript sees.
|
|
69
|
+
public var js: [String: Any] {
|
|
70
|
+
var o: [String: Any] = [
|
|
71
|
+
"id": id, "direction": direction.rawValue, "state": state.rawValue, "url": url, "path": path,
|
|
72
|
+
"bytes": bytes, "total": total, "updatedAt": updatedAt,
|
|
73
|
+
]
|
|
74
|
+
if let p = `protocol` { o["protocol"] = p }
|
|
75
|
+
if let reason = reason { o["reason"] = reason }
|
|
76
|
+
if let message = message { o["message"] = message }
|
|
77
|
+
if let httpStatus = httpStatus { o["httpStatus"] = httpStatus }
|
|
78
|
+
return o
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/// A background task carrying one part or block, and the temporary copy of its range.
|
|
83
|
+
public struct PartTask: Codable, Equatable {
|
|
84
|
+
public var part: Int
|
|
85
|
+
public var copy: String
|
|
86
|
+
|
|
87
|
+
public init(part: Int, copy: String) {
|
|
88
|
+
self.part = part
|
|
89
|
+
self.copy = copy
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/// The `TransferFailureReason` values.
|
|
94
|
+
public enum Reason {
|
|
95
|
+
public static let fileMissing = "file-missing"
|
|
96
|
+
public static let diskFull = "disk-full"
|
|
97
|
+
public static let sessionRefused = "session-refused"
|
|
98
|
+
public static let sessionExpired = "session-expired"
|
|
99
|
+
/// The session was already closed when the upload started: whether the object was accepted
|
|
100
|
+
/// only its metadata can say (the Firebase Storage emulator closes a session whose finalize its security rules refused).
|
|
101
|
+
public static let sessionClosed = "session-closed"
|
|
102
|
+
public static let sizeMismatch = "size-mismatch"
|
|
103
|
+
public static let network = "network"
|
|
104
|
+
public static let stoppedBySystem = "stopped-by-system"
|
|
105
|
+
public static let cancelled = "cancelled"
|
|
106
|
+
public static let serverError = "server-error"
|
|
107
|
+
public static let unknown = "unknown"
|
|
108
|
+
|
|
109
|
+
/// The reason for an HTTP status that isn't a success, and whether trying again later can help.
|
|
110
|
+
public static func forStatus(_ status: Int) -> (reason: String, resumable: Bool) {
|
|
111
|
+
switch status {
|
|
112
|
+
case 404, 410: return (sessionExpired, false)
|
|
113
|
+
case 408, 429, 500...599: return (serverError, true)
|
|
114
|
+
default: return (sessionRefused, false)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/// The reason for a URLSession error. `cancelledByUs` is whether the app asked for the cancel.
|
|
119
|
+
public static func forError(_ error: NSError, cancelledByUs: Bool) -> (reason: String, resumable: Bool) {
|
|
120
|
+
if error.domain == NSURLErrorDomain {
|
|
121
|
+
if error.code == NSURLErrorCancelled {
|
|
122
|
+
if cancelledByUs { return (cancelled, false) }
|
|
123
|
+
// Swiped away by the user, or ended by the system: resumable from where it stopped.
|
|
124
|
+
return (stoppedBySystem, true)
|
|
125
|
+
}
|
|
126
|
+
if error.code == NSURLErrorCannotWriteToFile { return (diskFull, false) }
|
|
127
|
+
if error.code == NSURLErrorFileDoesNotExist || error.code == NSURLErrorCannotOpenFile { return (fileMissing, false) }
|
|
128
|
+
return (network, true)
|
|
129
|
+
}
|
|
130
|
+
if isDiskFull(error) { return (diskFull, false) }
|
|
131
|
+
if error.domain == NSPOSIXErrorDomain { return (network, true) }
|
|
132
|
+
return (unknown, false)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
public static func isDiskFull(_ error: NSError) -> Bool {
|
|
136
|
+
if error.domain == NSCocoaErrorDomain && error.code == NSFileWriteOutOfSpaceError { return true }
|
|
137
|
+
if error.domain == NSPOSIXErrorDomain && error.code == Int(ENOSPC) { return true }
|
|
138
|
+
if let underlying = error.userInfo[NSUnderlyingErrorKey] as? NSError { return isDiskFull(underlying) }
|
|
139
|
+
return false
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Every transfer's record, in one small JSON file, so state survives the app's process:
|
|
4
|
+
/// the system finishes background transfers with the app closed and relaunches it to report.
|
|
5
|
+
/// Thread-safe.
|
|
6
|
+
public final class TransferStore {
|
|
7
|
+
private let file: URL
|
|
8
|
+
private let lock = NSLock()
|
|
9
|
+
private var records: [String: TransferRecord] = [:]
|
|
10
|
+
private var lastQueuedAt: Double = 0
|
|
11
|
+
|
|
12
|
+
public init(file: URL) {
|
|
13
|
+
self.file = file
|
|
14
|
+
if let data = try? Data(contentsOf: file), let list = try? JSONDecoder().decode([TransferRecord].self, from: data) {
|
|
15
|
+
for r in list { records[r.key] = r }
|
|
16
|
+
lastQueuedAt = list.map(\.queuedAt).max() ?? 0
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
public func get(_ direction: TransferRecord.Direction, _ id: String) -> TransferRecord? {
|
|
21
|
+
lock.lock(); defer { lock.unlock() }
|
|
22
|
+
return records[TransferRecord.key(direction, id)]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
public func get(key: String) -> TransferRecord? {
|
|
26
|
+
lock.lock(); defer { lock.unlock() }
|
|
27
|
+
return records[key]
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// Oldest first.
|
|
31
|
+
public func all() -> [TransferRecord] {
|
|
32
|
+
lock.lock(); defer { lock.unlock() }
|
|
33
|
+
return records.values.sorted { $0.queuedAt < $1.queuedAt }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/// Stores `r`, stamping `updatedAt`. Returns what was stored. A record that has stopped
|
|
37
|
+
/// (finished, interrupted, failed or cancelled) is kept without its headers: a restart brings its
|
|
38
|
+
/// own, and a token has no business on the disk after the request it was for.
|
|
39
|
+
@discardableResult
|
|
40
|
+
public func put(_ r: TransferRecord, save: Bool = true) -> TransferRecord {
|
|
41
|
+
lock.lock(); defer { lock.unlock() }
|
|
42
|
+
var r = r
|
|
43
|
+
r.updatedAt = (Date().timeIntervalSince1970 * 1000).rounded()
|
|
44
|
+
if !r.isActive { r.headers = [:] }
|
|
45
|
+
records[r.key] = r
|
|
46
|
+
if save { write() }
|
|
47
|
+
return r
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
public func remove(key: String) {
|
|
51
|
+
lock.lock(); defer { lock.unlock() }
|
|
52
|
+
if records.removeValue(forKey: key) != nil { write() }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/// A strictly increasing time for first-in, first-out.
|
|
56
|
+
public func nextQueuedAt() -> Double {
|
|
57
|
+
lock.lock(); defer { lock.unlock() }
|
|
58
|
+
lastQueuedAt = max((Date().timeIntervalSince1970 * 1000).rounded(), lastQueuedAt + 1)
|
|
59
|
+
return lastQueuedAt
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private func write() {
|
|
63
|
+
let list = Array(records.values)
|
|
64
|
+
guard let data = try? JSONEncoder().encode(list) else { return }
|
|
65
|
+
try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
66
|
+
// Readable by the system's transfer daemon while the phone is locked after its first unlock.
|
|
67
|
+
try? data.write(to: file, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Checks an upload's protocol options the way `checkUploadOptions` in validate.ts does, with the
|
|
4
|
+
/// same words, and the part count against the file's size, which only the native side can read.
|
|
5
|
+
public enum UploadOptionsCheck {
|
|
6
|
+
public static let mib: Int64 = 1024 * 1024
|
|
7
|
+
public static let defaultPartSize: Int64 = 8 * mib
|
|
8
|
+
public static let s3MinPartSize: Int64 = 5 * mib
|
|
9
|
+
public static let s3MaxPartSize: Int64 = 5 * 1024 * mib
|
|
10
|
+
public static let s3MaxParts = 10_000
|
|
11
|
+
public static let azureMaxBlockSize: Int64 = 4000 * mib
|
|
12
|
+
public static let azureMaxBlocks = 50_000
|
|
13
|
+
|
|
14
|
+
/// What is wrong with the options, or nil. `partUrls` holds whatever JavaScript sent;
|
|
15
|
+
/// `partSize` and `blockSize` are nil when not given.
|
|
16
|
+
public static func check(protocol p: UploadProtocol, url: String, partUrls: [Any]?, partSize: Double?,
|
|
17
|
+
listPartsUrl: Any?, blockSize: Double?) -> String? {
|
|
18
|
+
if p != .s3Multipart && (partUrls != nil || partSize != nil || listPartsUrl != nil) {
|
|
19
|
+
return "partUrls, partSize and listPartsUrl are only for s3-multipart"
|
|
20
|
+
}
|
|
21
|
+
if p != .azureBlocks && blockSize != nil { return "blockSize is only for azure-blocks" }
|
|
22
|
+
if p == .s3Multipart {
|
|
23
|
+
guard let urls = partUrls, !urls.isEmpty else { return "partUrls is required for s3-multipart" }
|
|
24
|
+
if urls.count > s3MaxParts { return "partUrls holds more than \(s3MaxParts) parts" }
|
|
25
|
+
if !urls.allSatisfy({ ($0 as? String).map(isHttpUrl) ?? false }) { return "partUrls must be http or https URLs" }
|
|
26
|
+
let size = partSize ?? Double(defaultPartSize)
|
|
27
|
+
if !isWhole(size) || size < 1 || size > Double(s3MaxPartSize) { return "partSize must be a whole number of bytes up to 5 GiB" }
|
|
28
|
+
if urls.count > 1 && size < Double(s3MinPartSize) { return "partSize must be at least 5 MiB when there is more than one part" }
|
|
29
|
+
if let list = listPartsUrl, !((list as? String).map(isHttpUrl) ?? false) { return "listPartsUrl must be an http or https URL" }
|
|
30
|
+
}
|
|
31
|
+
if p == .azureBlocks {
|
|
32
|
+
if !isSasUrl(url) { return "url must be a blob SAS URL (with a sig parameter)" }
|
|
33
|
+
let size = blockSize ?? Double(defaultPartSize)
|
|
34
|
+
if !isWhole(size) || size < 1 || size > Double(azureMaxBlockSize) { return "blockSize must be a whole number of bytes up to 4000 MiB" }
|
|
35
|
+
}
|
|
36
|
+
return nil
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// What is wrong with the part or block count for a `fileSize`-byte file, or nil.
|
|
40
|
+
public static func checkSize(protocol p: UploadProtocol, partUrlCount: Int, partSize: Int64, blockSize: Int64, fileSize: Int64) -> String? {
|
|
41
|
+
if p == .s3Multipart {
|
|
42
|
+
let needed = PartPlan.count(size: fileSize, partSize: partSize, atLeastOne: true)
|
|
43
|
+
if needed > s3MaxParts { return "a \(fileSize)-byte file in \(partSize)-byte parts needs more than \(s3MaxParts) parts" }
|
|
44
|
+
if needed != partUrlCount {
|
|
45
|
+
return "partUrls holds \(partUrlCount) parts but a \(fileSize)-byte file in \(partSize)-byte parts needs \(needed)"
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if p == .azureBlocks && PartPlan.count(size: fileSize, partSize: blockSize, atLeastOne: false) > azureMaxBlocks {
|
|
49
|
+
return "a \(fileSize)-byte file in \(blockSize)-byte blocks needs more than \(azureMaxBlocks) blocks"
|
|
50
|
+
}
|
|
51
|
+
return nil
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
static func isHttpUrl(_ s: String) -> Bool {
|
|
55
|
+
s.range(of: "^https?://[^/]+", options: [.regularExpression, .caseInsensitive]) != nil
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
private static func isWhole(_ d: Double) -> Bool {
|
|
59
|
+
d.isFinite && d.rounded(.down) == d && abs(d) <= 9_007_199_254_740_991
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/// A blob URL with a SAS token: a non-empty `sig` parameter, and no `comp`.
|
|
63
|
+
public static func isSasUrl(_ url: String) -> Bool {
|
|
64
|
+
let base = url.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? url
|
|
65
|
+
guard let q = base.firstIndex(of: "?") else { return false }
|
|
66
|
+
var sig = false
|
|
67
|
+
for p in base[base.index(after: q)...].split(separator: "&", omittingEmptySubsequences: false) {
|
|
68
|
+
let name = p.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? ""
|
|
69
|
+
if name == "comp" { return false }
|
|
70
|
+
if name == "sig" && p.count > "sig=".count { sig = true }
|
|
71
|
+
}
|
|
72
|
+
return sig
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// How a file divides into parts (S3) or blocks (Azure), numbered from 1.
|
|
77
|
+
public enum PartPlan {
|
|
78
|
+
/// An empty file is one (empty) part when `atLeastOne` (S3 needs a part to complete), none otherwise.
|
|
79
|
+
public static func count(size: Int64, partSize: Int64, atLeastOne: Bool) -> Int {
|
|
80
|
+
if size <= 0 { return atLeastOne ? 1 : 0 }
|
|
81
|
+
let n = (size + partSize - 1) / partSize
|
|
82
|
+
return n > Int64(Int.max) ? Int.max : Int(n)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
public static func offset(_ n: Int, partSize: Int64) -> Int64 { Int64(n - 1) * partSize }
|
|
86
|
+
|
|
87
|
+
public static func length(_ n: Int, size: Int64, partSize: Int64) -> Int64 {
|
|
88
|
+
max(0, min(partSize, size - offset(n, partSize: partSize)))
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// What an ended background upload task means. The task's request carried the session's offset
|
|
4
|
+
/// from when it was made; if the system resent it by itself after a network cut, the server may
|
|
5
|
+
/// already hold part of it, so anything but a clean finalize of exactly the file's size is checked
|
|
6
|
+
/// against the session before it is believed.
|
|
7
|
+
public enum UploadOutcome: Equatable {
|
|
8
|
+
case finished
|
|
9
|
+
case interrupted(reason: String, message: String)
|
|
10
|
+
case failed(reason: String, message: String)
|
|
11
|
+
/// Ask the session (`X-Goog-Upload-Command: query`) and decide with `afterQuery`.
|
|
12
|
+
case query
|
|
13
|
+
|
|
14
|
+
/// After the task got an HTTP response.
|
|
15
|
+
/// - Parameters:
|
|
16
|
+
/// - uploadStatus: `X-Goog-Upload-Status`, if sent.
|
|
17
|
+
/// - received: `X-Goog-Upload-Size-Received`, if sent.
|
|
18
|
+
/// - body: the response body (the finalized object's metadata on success), if any.
|
|
19
|
+
public static func afterResponse(status: Int, uploadStatus: String?, received: Int64?, body: Data?, total: Int64) -> UploadOutcome {
|
|
20
|
+
switch status {
|
|
21
|
+
case 200:
|
|
22
|
+
if let s = uploadStatus?.lowercased(), s != "final" {
|
|
23
|
+
return .failed(reason: Reason.sizeMismatch, message: "finalize left the session \(s)")
|
|
24
|
+
}
|
|
25
|
+
if let received = received, received != total {
|
|
26
|
+
return .failed(reason: Reason.sizeMismatch, message: "the server holds \(received) of \(total) bytes")
|
|
27
|
+
}
|
|
28
|
+
if let size = objectSize(body), size != total {
|
|
29
|
+
return .failed(reason: Reason.sizeMismatch, message: "the object is \(size) bytes, the file \(total)")
|
|
30
|
+
}
|
|
31
|
+
return .finished
|
|
32
|
+
case 404, 410:
|
|
33
|
+
return .failed(reason: Reason.sessionExpired, message: "upload HTTP \(status)")
|
|
34
|
+
default:
|
|
35
|
+
return .query
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// After asking the session what it holds, following a response that wasn't a clean finalize
|
|
40
|
+
/// (`originalStatus`). `queryStatus` is nil when the query itself got no response.
|
|
41
|
+
public static func afterQuery(originalStatus: Int, queryStatus: Int?, received: Int64?, uploadStatus: String?, total: Int64) -> UploadOutcome {
|
|
42
|
+
guard let queryStatus = queryStatus else {
|
|
43
|
+
return .interrupted(reason: Reason.network, message: "upload HTTP \(originalStatus); the session couldn't be asked")
|
|
44
|
+
}
|
|
45
|
+
switch queryStatus {
|
|
46
|
+
case 200:
|
|
47
|
+
let isFinal = uploadStatus?.lowercased() == "final"
|
|
48
|
+
guard let received = received else {
|
|
49
|
+
return .failed(reason: Reason.unknown, message: "upload HTTP \(originalStatus); query answered without a size")
|
|
50
|
+
}
|
|
51
|
+
if isFinal {
|
|
52
|
+
// The server answered the finalize with a refusal: a closed session doesn't mean the
|
|
53
|
+
// object was accepted (security rules may have refused it), so this is never finished.
|
|
54
|
+
let reason = received == total ? Reason.forStatus(originalStatus).reason : Reason.sizeMismatch
|
|
55
|
+
return .failed(reason: reason, message: "upload HTTP \(originalStatus); the session is closed at \(received) of \(total) bytes")
|
|
56
|
+
}
|
|
57
|
+
if received <= total {
|
|
58
|
+
// Still open: the rest can be sent from the server's offset.
|
|
59
|
+
return .interrupted(reason: Reason.network, message: "upload HTTP \(originalStatus); the session holds \(received) of \(total) bytes")
|
|
60
|
+
}
|
|
61
|
+
return .failed(reason: Reason.sizeMismatch, message: "the session holds \(received) of a \(total)-byte file")
|
|
62
|
+
case 404, 410:
|
|
63
|
+
return .failed(reason: Reason.sessionExpired, message: "upload HTTP \(originalStatus); query HTTP \(queryStatus)")
|
|
64
|
+
default:
|
|
65
|
+
let (reason, resumable) = Reason.forStatus(queryStatus)
|
|
66
|
+
let message = "upload HTTP \(originalStatus); query HTTP \(queryStatus)"
|
|
67
|
+
return resumable ? .interrupted(reason: reason, message: message) : .failed(reason: reason, message: message)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/// How long a session check (`query`) may take. A relaunched app gets about 30 seconds of
|
|
72
|
+
/// background time, and the system's completion handler is held until the check answers, so
|
|
73
|
+
/// the check has to give up well inside that or the app is suspended with the handler unsent.
|
|
74
|
+
public static let checkTimeout: TimeInterval = 20
|
|
75
|
+
|
|
76
|
+
/// Before a run sends anything: what the session's answer to `query` rules out. Nil means send
|
|
77
|
+
/// the bytes after `received`. A closed session is never taken as an accepted object.
|
|
78
|
+
public static func beforeSending(received: Int64, uploadStatus: String?, total: Int64) -> UploadOutcome? {
|
|
79
|
+
if uploadStatus?.lowercased() == "final" {
|
|
80
|
+
return .failed(reason: Reason.sessionClosed, message: "the session was already closed at \(received) of \(total) bytes")
|
|
81
|
+
}
|
|
82
|
+
if received > total {
|
|
83
|
+
return .failed(reason: Reason.sizeMismatch, message: "server holds \(received) of a \(total)-byte file")
|
|
84
|
+
}
|
|
85
|
+
return nil
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/// `size` from a finalized object's metadata (Storage sends it as a string).
|
|
89
|
+
public static func objectSize(_ body: Data?) -> Int64? {
|
|
90
|
+
guard let body = body, !body.isEmpty,
|
|
91
|
+
let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any] else { return nil }
|
|
92
|
+
if let s = json["size"] as? String { return Int64(s) }
|
|
93
|
+
if let n = json["size"] as? NSNumber { return n.int64Value }
|
|
94
|
+
return nil
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The upload protocols this version speaks, by the name the JavaScript side passes in `protocol`.
|
|
4
|
+
/// Another protocol plugs in as a new case here and a branch where `TransferManager` starts an upload.
|
|
5
|
+
public enum UploadProtocol: String, CaseIterable, Codable {
|
|
6
|
+
/// A Firebase Storage resumable upload: the `X-Goog-Upload-*` protocol.
|
|
7
|
+
case firebaseResumable = "firebase-resumable"
|
|
8
|
+
/// The whole file in one `PUT`.
|
|
9
|
+
case put
|
|
10
|
+
/// An S3 multipart upload with every URL presigned up front.
|
|
11
|
+
case s3Multipart = "s3-multipart"
|
|
12
|
+
/// An Azure block blob through one SAS URL.
|
|
13
|
+
case azureBlocks = "azure-blocks"
|
|
14
|
+
|
|
15
|
+
/// Sent in parts or blocks, each a background task of its own, then committed.
|
|
16
|
+
public var inParts: Bool { self == .s3Multipart || self == .azureBlocks }
|
|
17
|
+
|
|
18
|
+
public static let defaultProtocol: UploadProtocol = .firebaseResumable
|
|
19
|
+
|
|
20
|
+
/// The protocol for `name`: the default when nil, or nil when unknown.
|
|
21
|
+
public static func resolve(_ name: String?) -> UploadProtocol? {
|
|
22
|
+
guard let name = name else { return defaultProtocol }
|
|
23
|
+
return UploadProtocol(rawValue: name)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// What the plugin says when it refuses an unknown protocol.
|
|
27
|
+
public static var refusal: String {
|
|
28
|
+
"protocol must be one of " + allCases.map(\.rawValue).joined(separator: ", ")
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import Capacitor
|
|
3
|
+
#if canImport(BackgroundTransferCore)
|
|
4
|
+
import BackgroundTransferCore
|
|
5
|
+
#endif
|
|
6
|
+
|
|
7
|
+
/// The JavaScript side's handle on background transfers (definitions.ts). The work is done by
|
|
8
|
+
/// `TransferManager` in background `URLSession`s.
|
|
9
|
+
///
|
|
10
|
+
/// The app's delegate must hand the system's background session events over, or transfers that
|
|
11
|
+
/// finish while the app is closed aren't recorded until it is next opened:
|
|
12
|
+
///
|
|
13
|
+
/// ```swift
|
|
14
|
+
/// func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String,
|
|
15
|
+
/// completionHandler: @escaping () -> Void) {
|
|
16
|
+
/// if BackgroundTransferPlugin.handleEvents(forBackgroundURLSession: identifier, completionHandler: completionHandler) { return }
|
|
17
|
+
/// completionHandler()
|
|
18
|
+
/// }
|
|
19
|
+
/// ```
|
|
20
|
+
@objc(BackgroundTransferPlugin)
|
|
21
|
+
public class BackgroundTransferPlugin: CAPPlugin, CAPBridgedPlugin, TransferListener {
|
|
22
|
+
public let identifier = "BackgroundTransferPlugin"
|
|
23
|
+
public let jsName = "BackgroundTransfer"
|
|
24
|
+
public let pluginMethods: [CAPPluginMethod] = [
|
|
25
|
+
CAPPluginMethod(name: "isAvailable", returnType: CAPPluginReturnPromise),
|
|
26
|
+
CAPPluginMethod(name: "upload", returnType: CAPPluginReturnPromise),
|
|
27
|
+
CAPPluginMethod(name: "download", returnType: CAPPluginReturnPromise),
|
|
28
|
+
CAPPluginMethod(name: "cancel", returnType: CAPPluginReturnPromise),
|
|
29
|
+
CAPPluginMethod(name: "list", returnType: CAPPluginReturnPromise),
|
|
30
|
+
CAPPluginMethod(name: "forget", returnType: CAPPluginReturnPromise)
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
/// Hands a background session's events to the plugin. Returns false if `identifier` isn't
|
|
34
|
+
/// one of the plugin's sessions (call `completionHandler` yourself then).
|
|
35
|
+
@objc public static func handleEvents(forBackgroundURLSession identifier: String,
|
|
36
|
+
completionHandler: @escaping () -> Void) -> Bool {
|
|
37
|
+
TransferManager.shared.handleEvents(identifier: identifier, completionHandler: completionHandler)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
override public func load() {
|
|
41
|
+
TransferManager.shared.listener = self
|
|
42
|
+
TransferManager.shared.start()
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
func transferChanged(_ record: TransferRecord, event: String) {
|
|
46
|
+
notifyListeners(event, data: ["transfer": record.js])
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
@objc func isAvailable(_ call: CAPPluginCall) {
|
|
50
|
+
call.resolve(["available": true, "mechanism": "urlsession"])
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
@objc func upload(_ call: CAPPluginCall) {
|
|
54
|
+
start(call, .upload)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
@objc func download(_ call: CAPPluginCall) {
|
|
58
|
+
start(call, .download)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
private func start(_ call: CAPPluginCall, _ direction: TransferRecord.Direction) {
|
|
62
|
+
guard let id = call.getString("id"), !id.isEmpty, let url = call.getString("url"),
|
|
63
|
+
let path = call.getString("path"), path.hasPrefix("/") else {
|
|
64
|
+
call.reject("id, url and an absolute path are required")
|
|
65
|
+
return
|
|
66
|
+
}
|
|
67
|
+
// The wrapper's checks, repeated here: a script can call the plugin without it.
|
|
68
|
+
if let refused = TransferPaths.checkUrl(url) {
|
|
69
|
+
call.reject(refused)
|
|
70
|
+
return
|
|
71
|
+
}
|
|
72
|
+
if let refused = TransferPaths.confine(path, roots: allowedRoots(), refused: TransferManager.shared.directory,
|
|
73
|
+
download: direction == .download) {
|
|
74
|
+
call.reject(refused)
|
|
75
|
+
return
|
|
76
|
+
}
|
|
77
|
+
var record = TransferRecord(id: id, direction: direction, url: url, path: path)
|
|
78
|
+
if direction == .upload {
|
|
79
|
+
guard let chosen = UploadProtocol.resolve(call.getString("protocol")) else {
|
|
80
|
+
call.reject(UploadProtocol.refusal)
|
|
81
|
+
return
|
|
82
|
+
}
|
|
83
|
+
record.protocol = chosen.rawValue
|
|
84
|
+
if let refused = readProtocolOptions(call, chosen, &record) {
|
|
85
|
+
call.reject(refused)
|
|
86
|
+
return
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if let headers = call.getObject("headers") {
|
|
90
|
+
for (name, value) in headers {
|
|
91
|
+
if let value = value as? String { record.headers[name] = value }
|
|
92
|
+
}
|
|
93
|
+
if let refused = TransferPaths.checkHeaders(record.headers) {
|
|
94
|
+
call.reject(refused)
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
TransferManager.shared.enqueue(record) { stored in
|
|
99
|
+
call.resolve(["transfer": stored.js])
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/// Where a transfer's file may be: the app's own Documents, Library (Application Support and
|
|
104
|
+
/// Caches included) and tmp, plus any absolute paths the app lists under `allowedRoots` in the
|
|
105
|
+
/// plugin's configuration (never from JavaScript).
|
|
106
|
+
private func allowedRoots() -> [URL] {
|
|
107
|
+
let fm = FileManager.default
|
|
108
|
+
var roots = fm.urls(for: .documentDirectory, in: .userDomainMask) + fm.urls(for: .libraryDirectory, in: .userDomainMask)
|
|
109
|
+
roots.append(fm.temporaryDirectory)
|
|
110
|
+
if let configured = getConfig().getArray("allowedRoots") {
|
|
111
|
+
roots += configured.compactMap { $0 as? String }.filter { $0.hasPrefix("/") }.map { URL(fileURLWithPath: $0) }
|
|
112
|
+
}
|
|
113
|
+
return roots
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/// Reads `partUrls`, `partSize`, `listPartsUrl` and `blockSize` into `record`, and returns what is
|
|
117
|
+
/// wrong with them (as the JavaScript side words it), or nil.
|
|
118
|
+
private func readProtocolOptions(_ call: CAPPluginCall, _ chosen: UploadProtocol, _ record: inout TransferRecord) -> String? {
|
|
119
|
+
let options = call.options ?? [:]
|
|
120
|
+
func number(_ name: String) -> Double? {
|
|
121
|
+
guard let v = options[name], !(v is NSNull) else { return nil }
|
|
122
|
+
if let n = v as? NSNumber, CFGetTypeID(n) != CFBooleanGetTypeID() { return n.doubleValue }
|
|
123
|
+
return .nan
|
|
124
|
+
}
|
|
125
|
+
var partUrls: [Any]?
|
|
126
|
+
if let v = options["partUrls"], !(v is NSNull) { partUrls = (v as? [Any]) ?? [] }
|
|
127
|
+
let listPartsUrl = options["listPartsUrl"].flatMap { $0 is NSNull ? nil : $0 }
|
|
128
|
+
let partSize = number("partSize"), blockSize = number("blockSize")
|
|
129
|
+
if let refused = UploadOptionsCheck.check(protocol: chosen, url: record.url, partUrls: partUrls, partSize: partSize,
|
|
130
|
+
listPartsUrl: listPartsUrl, blockSize: blockSize) {
|
|
131
|
+
return refused
|
|
132
|
+
}
|
|
133
|
+
record.partUrls = partUrls?.compactMap { $0 as? String }
|
|
134
|
+
record.partSize = partSize.map { Int64($0) }
|
|
135
|
+
record.listPartsUrl = listPartsUrl as? String
|
|
136
|
+
record.blockSize = blockSize.map { Int64($0) }
|
|
137
|
+
// A missing file is reported when the upload runs (file-missing), as for every protocol.
|
|
138
|
+
guard let size = try? Files.fileSize(URL(fileURLWithPath: record.path)) else { return nil }
|
|
139
|
+
return UploadOptionsCheck.checkSize(protocol: chosen, partUrlCount: record.partUrls?.count ?? 0,
|
|
140
|
+
partSize: record.partSize ?? UploadOptionsCheck.defaultPartSize,
|
|
141
|
+
blockSize: record.blockSize ?? UploadOptionsCheck.defaultPartSize, fileSize: size)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
@objc func cancel(_ call: CAPPluginCall) {
|
|
145
|
+
guard let id = call.getString("id"), let direction = call.getString("direction").flatMap(TransferRecord.Direction.init) else {
|
|
146
|
+
call.reject("id and direction are required")
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
TransferManager.shared.cancel(key: TransferRecord.key(direction, id))
|
|
150
|
+
call.resolve()
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
@objc func list(_ call: CAPPluginCall) {
|
|
154
|
+
call.resolve(["transfers": TransferManager.shared.list().map(\.js)])
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
@objc func forget(_ call: CAPPluginCall) {
|
|
158
|
+
var keys: Set<String>?
|
|
159
|
+
if let ids = call.getArray("ids", JSObject.self) {
|
|
160
|
+
keys = Set(ids.compactMap { o in
|
|
161
|
+
guard let id = o["id"] as? String, let d = (o["direction"] as? String).flatMap(TransferRecord.Direction.init) else { return nil }
|
|
162
|
+
return TransferRecord.key(d, id)
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
TransferManager.shared.forget(keys: keys)
|
|
166
|
+
call.resolve()
|
|
167
|
+
}
|
|
168
|
+
}
|