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,1074 @@
1
+ import Foundation
2
+ import UIKit
3
+ #if canImport(BackgroundTransferCore)
4
+ import BackgroundTransferCore
5
+ #endif
6
+
7
+ /// Runs transfers in two background `URLSession`s, one per direction, so they carry on in the
8
+ /// system's transfer daemon with the app suspended or killed, and records every change in the
9
+ /// `TransferStore`. Each session allows one connection per host, so transfers in a direction go
10
+ /// one at a time.
11
+ ///
12
+ /// Everything here runs on `queue`, which is also the sessions' delegate queue.
13
+ final class TransferManager: NSObject {
14
+ static let shared = TransferManager()
15
+
16
+ /// The app's events, while it is open.
17
+ weak var listener: TransferListener?
18
+
19
+ let queue = DispatchQueue(label: "io.github.sandman92.backgroundtransfer")
20
+ private let delegateQueue = OperationQueue()
21
+ private let store: TransferStore
22
+ /// The plugin's own storage: the records, remainder copies and resume data. No transfer may
23
+ /// read or write here.
24
+ let directory: URL
25
+ private var completionHandlers: [String: () -> Void] = [:]
26
+ /// Keys of transfers the app asked to cancel, so the task's cancellation reads as theirs.
27
+ private var cancelling = Set<String>()
28
+ private var lastSaved: [String: Date] = [:]
29
+ private var lastProgress: [String: Date] = [:]
30
+ /// Upload responses' bodies (the finalized object's metadata), kept to check its size.
31
+ private var uploadBodies: [Int: Data] = [:]
32
+ /// Session checks still waiting for an answer, and parts being made ready for their task; the
33
+ /// system's completion handler is held until none are.
34
+ private var checks = 0
35
+ private var heldHandlers: [() -> Void] = []
36
+ /// Calls that arrive before `start()` has reconciled the records wait here.
37
+ private var started = false
38
+ private var waiting: [() -> Void] = []
39
+ /// Download tasks' outcome, decided when the file arrives and applied when the task completes.
40
+ private var downloadOutcome: [String: (state: TransferRecord.State, reason: String?, message: String?, status: Int?)] = [:]
41
+
42
+ static var bundlePrefix: String { Bundle.main.bundleIdentifier ?? "io.github.sandman92.backgroundtransfer" }
43
+ static var uploadSessionId: String { "\(bundlePrefix).background-transfer.upload" }
44
+ static var downloadSessionId: String { "\(bundlePrefix).background-transfer.download" }
45
+
46
+ private lazy var uploadSession: URLSession = makeSession(TransferManager.uploadSessionId)
47
+ private lazy var downloadSession: URLSession = makeSession(TransferManager.downloadSessionId)
48
+
49
+ /// Whether the app is on screen. Parts and blocks go one at a time then; once it leaves the
50
+ /// screen every remaining one is handed to the session at once, because the system holds back
51
+ /// each background wake that would start the next part, doubling the wait every time.
52
+ private var onScreen: Bool
53
+ /// Uploads whose part copies are being made, so a second hand-over doesn't copy them again.
54
+ private var preparing = Set<String>()
55
+
56
+ private override init() {
57
+ let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
58
+ directory = support.appendingPathComponent("BackgroundTransfer", isDirectory: true)
59
+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
60
+ // Headers, tokens and resume data: never in a backup, never restored onto another device.
61
+ try? Files.excludeFromBackup(directory)
62
+ store = TransferStore(file: directory.appendingPathComponent("transfers.json"))
63
+ // Made on the main thread (the plugin's load, or the system's background session events).
64
+ onScreen = Thread.isMainThread ? UIApplication.shared.applicationState != .background : false
65
+ super.init()
66
+ delegateQueue.maxConcurrentOperationCount = 1
67
+ delegateQueue.underlyingQueue = queue
68
+ let center = NotificationCenter.default
69
+ center.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { [weak self] _ in
70
+ guard let self = self else { return }
71
+ // Background time so the copies are made and handed over before the app is suspended.
72
+ let time = BackgroundTime("BackgroundTransfer hand-over")
73
+ self.queue.async {
74
+ defer { time.end() }
75
+ self.onScreen = false
76
+ self.handOverEverything()
77
+ }
78
+ }
79
+ center.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { [weak self] _ in
80
+ self?.queue.async { self?.onScreen = true }
81
+ }
82
+ }
83
+
84
+ private func makeSession(_ identifier: String) -> URLSession {
85
+ let config = URLSessionConfiguration.background(withIdentifier: identifier)
86
+ config.isDiscretionary = false
87
+ config.sessionSendsLaunchEvents = true
88
+ config.httpMaximumConnectionsPerHost = 1
89
+ config.requestCachePolicy = .reloadIgnoringLocalCacheData
90
+ return URLSession(configuration: config, delegate: self, delegateQueue: delegateQueue)
91
+ }
92
+
93
+ // MARK: Launch
94
+
95
+ /// Reconnects both sessions (their finished work is then delivered), and reports a record left
96
+ /// queued or running with no task behind it as interrupted.
97
+ func start() {
98
+ queue.async {
99
+ let sessions = [self.uploadSession, self.downloadSession]
100
+ let group = DispatchGroup()
101
+ var live = Set<String>()
102
+ for session in sessions {
103
+ group.enter()
104
+ session.getAllTasks { tasks in
105
+ self.queue.async {
106
+ for t in tasks where t.state == .running || t.state == .suspended {
107
+ if let key = t.taskDescription { live.insert(key) }
108
+ }
109
+ group.leave()
110
+ }
111
+ }
112
+ }
113
+ group.notify(queue: self.queue) {
114
+ for var r in self.store.all() where r.isActive && !live.contains(r.key) {
115
+ if r.direction == .upload, let refused = r.refusedStatus {
116
+ // A refusal was being checked when the process ended: check it again.
117
+ self.checkSession(r, refusedWith: refused)
118
+ continue
119
+ }
120
+ // No task behind it: the app was killed while preparing it. (A task that ended
121
+ // while the app was away is reported by the session and overrides this.)
122
+ r.state = .interrupted
123
+ r.reason = Reason.stoppedBySystem
124
+ r.message = "no transfer was running for this when the app opened"
125
+ r.taskIdentifier = nil
126
+ if r.partTasks == nil {
127
+ r.currentPart = nil
128
+ self.removeRemainder(&r)
129
+ }
130
+ // Parts handed over stay recorded with their copies: tasks that ended while the
131
+ // app was away are reported after this, find their parts, and carry the upload on.
132
+ self.save(r, event: "stateChange")
133
+ }
134
+ // Copies no record names: left by a process that ended mid-copy.
135
+ let named = Set(self.store.all().flatMap { PartsUpload.copies($0) })
136
+ Files.removeOrphans(in: self.directory.appendingPathComponent("remainders"), keeping: named)
137
+ self.started = true
138
+ let calls = self.waiting
139
+ self.waiting = []
140
+ calls.forEach { $0() }
141
+ }
142
+ }
143
+ }
144
+
145
+ /// Runs `work` on `queue` once `start()` has reconciled the records, so a new transfer is
146
+ /// never mistaken for one the last process left behind.
147
+ private func whenStarted(_ work: @escaping () -> Void) {
148
+ queue.async {
149
+ if self.started { work() } else { self.waiting.append(work) }
150
+ }
151
+ }
152
+
153
+ func handleEvents(identifier: String, completionHandler: @escaping () -> Void) -> Bool {
154
+ guard identifier == TransferManager.uploadSessionId || identifier == TransferManager.downloadSessionId else { return false }
155
+ NSLog("BackgroundTransfer: woken for %@", identifier)
156
+ let background = UIApplication.shared.applicationState == .background
157
+ queue.async {
158
+ if background { self.onScreen = false }
159
+ self.completionHandlers[identifier] = completionHandler
160
+ _ = identifier == TransferManager.uploadSessionId ? self.uploadSession : self.downloadSession
161
+ }
162
+ return true
163
+ }
164
+
165
+ // MARK: Calls from JavaScript
166
+
167
+ func list() -> [TransferRecord] { store.all() }
168
+
169
+ func forget(keys: Set<String>?) {
170
+ queue.async {
171
+ for r in self.store.all() where !r.isActive && r.state != .interrupted {
172
+ if let keys = keys, !keys.contains(r.key) { continue }
173
+ self.store.remove(key: r.key)
174
+ }
175
+ }
176
+ }
177
+
178
+ /// Queues a transfer and calls back with its record. One that is queued or running is left alone.
179
+ func enqueue(_ wanted: TransferRecord, done: @escaping (TransferRecord) -> Void) {
180
+ whenStarted {
181
+ if let existing = self.store.get(key: wanted.key), existing.isActive {
182
+ done(existing)
183
+ return
184
+ }
185
+ if var old = self.store.get(key: wanted.key), old.partTasks != nil {
186
+ // Parts an earlier run handed over: stopped, and their copies removed.
187
+ self.dropParts(&old)
188
+ self.store.put(old)
189
+ }
190
+ var r = wanted
191
+ r.state = .queued
192
+ r.queuedAt = self.store.nextQueuedAt()
193
+ r.reason = nil
194
+ r.message = nil
195
+ r.httpStatus = nil
196
+ r.taskIdentifier = nil
197
+ r.refusedStatus = nil
198
+ r.currentPart = nil
199
+ if r.direction == .download {
200
+ r.bytes = (try? Files.fileSize(Files.partURL(for: URL(fileURLWithPath: r.path)))) ?? 0
201
+ } else if UploadProtocol.resolve(r.protocol)?.inParts == true, let existing = self.store.get(key: wanted.key),
202
+ PartsUpload.carriesOver(existing, r, fileSize: (try? Files.fileSize(URL(fileURLWithPath: r.path))) ?? -2) {
203
+ // The same upload: what it sent, and whether its commit went, carry over.
204
+ r.parts = existing.parts
205
+ r.committing = existing.committing
206
+ r.bytes = existing.bytes
207
+ }
208
+ r = self.save(r, event: "stateChange")
209
+ done(r)
210
+ if r.direction == .upload { self.startUpload(r) } else { self.startDownload(r) }
211
+ }
212
+ }
213
+
214
+ func cancel(key: String) {
215
+ whenStarted {
216
+ guard var r = self.store.get(key: key) else { return }
217
+ if r.isActive, r.taskIdentifier != nil || r.partTasks != nil {
218
+ self.cancelling.insert(key)
219
+ let session = r.direction == .upload ? self.uploadSession : self.downloadSession
220
+ session.getAllTasks { tasks in
221
+ self.queue.async {
222
+ guard var now = self.store.get(key: key), now.isActive else { return }
223
+ // Every task of the transfer: an upload in parts may have several handed over.
224
+ let mine = tasks.filter { $0.taskDescription == key }
225
+ let unfinished = mine.filter { $0.state != .completed }
226
+ let commitOut = UploadProtocol.resolve(now.protocol)?.inParts == true && now.currentPart == 0
227
+ switch PartsUpload.cancelPlan(commitOut: commitOut, unfinishedTasks: unfinished.count,
228
+ endedTasks: mine.count - unfinished.count) {
229
+ case .cancelTasks:
230
+ unfinished.forEach { $0.cancel() }
231
+ case .awaitCommit, .awaitEnd:
232
+ break // That task's end decides, with the cancel noted.
233
+ case .markCancelled:
234
+ self.markCancelled(&now)
235
+ }
236
+ }
237
+ }
238
+ return
239
+ }
240
+ if r.isActive || r.state == .interrupted { self.markCancelled(&r) }
241
+ }
242
+ }
243
+
244
+ private func markCancelled(_ r: inout TransferRecord) {
245
+ cleanUp(&r)
246
+ r.state = .cancelled
247
+ r.reason = Reason.cancelled
248
+ r.message = "cancelled"
249
+ r.taskIdentifier = nil
250
+ save(r, event: "stateChange")
251
+ }
252
+
253
+ // MARK: Upload
254
+
255
+ private func startUpload(_ record: TransferRecord) {
256
+ var r = record
257
+ guard let chosen = UploadProtocol.resolve(r.protocol) else {
258
+ fail(&r, Reason.unknown, "unknown upload protocol \(r.protocol ?? "")")
259
+ return
260
+ }
261
+ let file = URL(fileURLWithPath: r.path)
262
+ let size: Int64
263
+ do {
264
+ size = try Files.fileSize(file)
265
+ } catch {
266
+ fail(&r, Reason.fileMissing, "no file at \(r.path)")
267
+ return
268
+ }
269
+ r.total = size
270
+ guard let url = URL(string: r.url) else {
271
+ fail(&r, Reason.sessionRefused, "not a URL")
272
+ return
273
+ }
274
+ // Each protocol's adapter plugs in here.
275
+ switch chosen {
276
+ case .firebaseResumable:
277
+ break
278
+ case .put:
279
+ sendWhole(r, from: file)
280
+ return
281
+ case .s3Multipart, .azureBlocks:
282
+ startParts(r)
283
+ return
284
+ }
285
+ // Ask the session what it holds. A plain (foreground) request: the app is on screen now.
286
+ querySession(url, headers: r.headers) { response, error in
287
+ self.afterQuery(r, file: file, size: size, response: response, error: error)
288
+ }
289
+ }
290
+
291
+ /// `X-Goog-Upload-Command: query` on a plain ephemeral session; calls back on `queue`.
292
+ private func querySession(_ url: URL, headers: [String: String], done: @escaping (URLResponse?, Error?) -> Void) {
293
+ var query = URLRequest(url: url)
294
+ query.httpMethod = "POST"
295
+ query.setValue("query", forHTTPHeaderField: "X-Goog-Upload-Command")
296
+ for (k, v) in headers { query.setValue(v, forHTTPHeaderField: k) }
297
+ query.httpBody = Data()
298
+ // Inside the ~30 s a relaunched app gets: the completion handler waits for this answer.
299
+ query.timeoutInterval = UploadOutcome.checkTimeout
300
+ let probe = URLSession(configuration: .ephemeral, delegate: SameOriginRedirects(), delegateQueue: nil)
301
+ probe.dataTask(with: query) { _, response, error in
302
+ probe.finishTasksAndInvalidate()
303
+ self.queue.async { done(response, error) }
304
+ }.resume()
305
+ }
306
+
307
+ private func afterQuery(_ record: TransferRecord, file: URL, size: Int64, response: URLResponse?, error: Error?) {
308
+ guard var r = store.get(key: record.key), r.state == .queued else { return } // cancelled meanwhile
309
+ r.total = size
310
+ if let error = error as NSError? {
311
+ let (reason, resumable) = Reason.forError(error, cancelledByUs: false)
312
+ if resumable { interrupt(&r, reason, "query: \(error.localizedDescription)") } else { fail(&r, reason, "query: \(error.localizedDescription)") }
313
+ return
314
+ }
315
+ guard let http = response as? HTTPURLResponse else {
316
+ interrupt(&r, Reason.network, "query: no response")
317
+ return
318
+ }
319
+ guard http.statusCode == 200 else {
320
+ let (reason, resumable) = Reason.forStatus(http.statusCode)
321
+ r.httpStatus = http.statusCode
322
+ if resumable { interrupt(&r, reason, "query HTTP \(http.statusCode)") } else { fail(&r, reason, "query HTTP \(http.statusCode)") }
323
+ return
324
+ }
325
+ guard let received = (http.value(forHTTPHeaderField: "X-Goog-Upload-Size-Received")).flatMap({ Int64($0) }) else {
326
+ fail(&r, Reason.unknown, "query answered without X-Goog-Upload-Size-Received")
327
+ return
328
+ }
329
+ if let stop = UploadOutcome.beforeSending(received: received, uploadStatus: http.value(forHTTPHeaderField: "X-Goog-Upload-Status"),
330
+ total: size) {
331
+ apply(stop, to: &r, httpStatus: 0)
332
+ return
333
+ }
334
+ guard received > 0 else {
335
+ sendUpload(r, from: file, offset: 0)
336
+ return
337
+ }
338
+ // A background upload sends a whole file, so resuming part-way sends a copy of the rest.
339
+ let remainder = directory.appendingPathComponent("remainders/\(UUID().uuidString)")
340
+ // Named before it is written, so a process that ends mid-copy leaves a file the next launch removes.
341
+ r.remainderPath = remainder.path
342
+ r = store.put(r)
343
+ // Off the serial queue, so a copy of gigabytes doesn't hold up every call and callback, and
344
+ // with background time, so leaving the app doesn't end it half-way.
345
+ let time = BackgroundTime("BackgroundTransfer remainder copy")
346
+ DispatchQueue.global(qos: .utility).async {
347
+ var copyError: NSError?
348
+ do {
349
+ try Files.writeRemainder(of: file, from: received, to: remainder)
350
+ } catch {
351
+ copyError = error as NSError
352
+ }
353
+ self.queue.async {
354
+ defer { time.end() }
355
+ guard var now = self.store.get(key: r.key), now.state == .queued, now.remainderPath == remainder.path else {
356
+ // Cancelled (or started again) while copying.
357
+ try? FileManager.default.removeItem(at: remainder)
358
+ return
359
+ }
360
+ if let ns = copyError {
361
+ self.fail(&now, Reason.isDiskFull(ns) ? Reason.diskFull : Reason.fileMissing, "remainder copy: \(ns.localizedDescription)")
362
+ return
363
+ }
364
+ self.sendUpload(now, from: remainder, offset: received)
365
+ }
366
+ }
367
+ }
368
+
369
+ /// Hands the upload to the background session: `source` holds the bytes from `offset` to the end.
370
+ private func sendUpload(_ record: TransferRecord, from source: URL, offset: Int64) {
371
+ var r = record
372
+ guard let url = URL(string: r.url) else { return }
373
+ var request = URLRequest(url: url)
374
+ request.httpMethod = "POST"
375
+ for (k, v) in r.headers { request.setValue(v, forHTTPHeaderField: k) }
376
+ request.setValue("upload, finalize", forHTTPHeaderField: "X-Goog-Upload-Command")
377
+ request.setValue(String(offset), forHTTPHeaderField: "X-Goog-Upload-Offset")
378
+ // A body sent without one goes as a form.
379
+ request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
380
+ let task = uploadSession.uploadTask(with: request, fromFile: source)
381
+ task.taskDescription = r.key
382
+ r.startOffset = offset
383
+ r.bytes = offset
384
+ r.taskIdentifier = task.taskIdentifier
385
+ save(r, event: "progress")
386
+ task.resume()
387
+ }
388
+
389
+ // MARK: put, and uploads in parts
390
+
391
+ /// `put`: the whole file in one background task, sent in place (no copy).
392
+ private func sendWhole(_ record: TransferRecord, from file: URL) {
393
+ var r = record
394
+ guard let request = PartsUpload.putRequest(r) else { return fail(&r, Reason.sessionRefused, "not a URL") }
395
+ let task = uploadSession.uploadTask(with: request, fromFile: file)
396
+ task.taskDescription = r.key
397
+ r.startOffset = 0
398
+ r.bytes = 0
399
+ r.taskIdentifier = task.taskIdentifier
400
+ save(r, event: "progress")
401
+ task.resume()
402
+ }
403
+
404
+ /// `s3-multipart` and `azure-blocks`: asks the server what it holds (ListParts or Get Block List,
405
+ /// on a plain session: the app is on screen), then hands the parts to the background session
406
+ /// one at a time.
407
+ private func startParts(_ record: TransferRecord) {
408
+ var r = record
409
+ if let stop = PartsUpload.beforeStart(r, size: r.total) {
410
+ apply(stop, to: &r, httpStatus: 0)
411
+ return
412
+ }
413
+ guard var probe = PartsUpload.probe(r) else {
414
+ sendNextPart(r)
415
+ return
416
+ }
417
+ probe.timeoutInterval = UploadOutcome.checkTimeout
418
+ let session = URLSession(configuration: .ephemeral, delegate: SameOriginRedirects(), delegateQueue: nil)
419
+ session.dataTask(with: probe) { body, response, error in
420
+ session.finishTasksAndInvalidate()
421
+ self.queue.async {
422
+ guard var now = self.store.get(key: r.key), now.state == .queued else { return } // cancelled meanwhile
423
+ now.total = r.total
424
+ let status = error == nil ? (response as? HTTPURLResponse)?.statusCode : nil
425
+ if let stop = PartsUpload.afterProbe(&now, status: status, body: body, size: now.total) {
426
+ self.apply(stop, to: &now, httpStatus: status ?? 0)
427
+ return
428
+ }
429
+ now.bytes = min(PartsUpload.storedBytes(now, size: now.total), max(now.total - 1, 0))
430
+ self.sendNextPart(self.store.put(now))
431
+ }
432
+ }.resume()
433
+ }
434
+
435
+ /// Hands the next part or block to the background session (one, while the app is on screen;
436
+ /// every remaining one, once it has left it), or the commit once every part is stored. Runs after
437
+ /// each part's answer too, with the app perhaps woken in the background for it: the system's
438
+ /// completion handler is held until the tasks are handed over, so the app isn't suspended half-way.
439
+ private func sendNextPart(_ record: TransferRecord) {
440
+ var r = record
441
+ guard !cancelling.contains(r.key) else { return } // Nothing more goes once the app has asked to cancel.
442
+ let size = r.total
443
+ r.taskIdentifier = nil
444
+ guard let step = PartsUpload.next(r, size: size) else {
445
+ store.put(r) // The last parts are still in tasks' hands.
446
+ return
447
+ }
448
+ switch step {
449
+ case .part:
450
+ if onScreen {
451
+ handOver(r, [step])
452
+ } else {
453
+ handOverRemaining(r)
454
+ }
455
+ case .commit:
456
+ guard let (request, body) = PartsUpload.commitRequest(r, size: size) else {
457
+ return fail(&r, Reason.sessionRefused, "not a URL")
458
+ }
459
+ let copy = directory.appendingPathComponent("remainders/\(UUID().uuidString)")
460
+ do {
461
+ try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true)
462
+ try body.write(to: copy, options: [.completeFileProtectionUntilFirstUserAuthentication])
463
+ } catch {
464
+ let ns = error as NSError
465
+ return fail(&r, Reason.isDiskFull(ns) ? Reason.diskFull : Reason.unknown, "commit body: \(ns.localizedDescription)")
466
+ }
467
+ let task = uploadSession.uploadTask(with: request, fromFile: copy)
468
+ task.taskDescription = r.key
469
+ r.remainderPath = copy.path
470
+ r.currentPart = 0
471
+ // From here a lost answer can't be told from a committed object.
472
+ r.committing = true
473
+ r.startOffset = size
474
+ r.taskIdentifier = task.taskIdentifier
475
+ save(r, event: "progress")
476
+ task.resume()
477
+ }
478
+ }
479
+
480
+ /// The app has left the screen: every upload in parts that is running hands all its remaining
481
+ /// parts over now.
482
+ private func handOverEverything() {
483
+ for r in store.all() where r.direction == .upload && r.isActive && r.total >= 0
484
+ && UploadProtocol.resolve(r.protocol)?.inParts == true && r.currentPart != 0 && r.committing != true {
485
+ if !PartsUpload.pending(r, size: r.total).isEmpty { handOverRemaining(r) }
486
+ }
487
+ }
488
+
489
+ /// Hands every part neither stored nor in a task's hands to the session, if their copies fit on
490
+ /// the disk with room to spare; otherwise the next one only, saying so.
491
+ private func handOverRemaining(_ record: TransferRecord) {
492
+ var r = record
493
+ let pending = PartsUpload.pending(r, size: r.total)
494
+ guard let first = pending.first else { return }
495
+ let bytes = PartsUpload.pendingBytes(r, size: r.total)
496
+ let free = (try? directory.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]))?
497
+ .volumeAvailableCapacityForImportantUsage ?? 0
498
+ if PartsUpload.handOverFits(bytes: bytes, free: free) {
499
+ handOver(r, pending)
500
+ } else {
501
+ let message = "not enough free disk to hand over the \(bytes) bytes left (\(free) free): sending one part at a time"
502
+ NSLog("BackgroundTransfer: %@: %@", r.id, message)
503
+ r.message = message
504
+ handOver(store.put(r), [first])
505
+ }
506
+ }
507
+
508
+ /// Copies each part's range to a temporary file (off the serial queue, with background time),
509
+ /// then hands them to the session, recording which part each task carries. Each copy is removed
510
+ /// when its task ends, and by the launch sweep after a process that ended mid-copy.
511
+ private func handOver(_ record: TransferRecord, _ steps: [PartsUpload.Step]) {
512
+ let r = record
513
+ guard !preparing.contains(r.key) else { return }
514
+ let parts: [(n: Int, offset: Int64, length: Int64, copy: URL)] = steps.compactMap { step in
515
+ guard case .part(let n, let offset, let length) = step else { return nil }
516
+ return (n, offset, length, directory.appendingPathComponent("remainders/\(UUID().uuidString)"))
517
+ }
518
+ guard !parts.isEmpty else { return }
519
+ // The file's size and what is stored so far, for the answers that read the record back.
520
+ store.put(r)
521
+ preparing.insert(r.key)
522
+ hold()
523
+ let time = BackgroundTime("BackgroundTransfer part copy")
524
+ DispatchQueue.global(qos: .utility).async {
525
+ var copyError: NSError?
526
+ var made: [URL] = []
527
+ for p in parts {
528
+ do {
529
+ try Files.writeRange(of: URL(fileURLWithPath: r.path), from: p.offset, length: p.length, to: p.copy)
530
+ made.append(p.copy)
531
+ } catch {
532
+ copyError = error as NSError
533
+ break
534
+ }
535
+ }
536
+ self.queue.async {
537
+ defer {
538
+ time.end()
539
+ self.release()
540
+ }
541
+ self.preparing.remove(r.key)
542
+ let removeCopies = { for p in parts { try? FileManager.default.removeItem(at: p.copy) } }
543
+ guard var now = self.store.get(key: r.key), now.isActive, now.queuedAt == r.queuedAt, now.currentPart != 0,
544
+ !self.cancelling.contains(r.key) else {
545
+ // Cancelled, stopped or started again while copying.
546
+ removeCopies()
547
+ return
548
+ }
549
+ if let ns = copyError {
550
+ removeCopies()
551
+ if Reason.isDiskFull(ns) && parts.count > 1 {
552
+ // The disk filled up after all: one part at a time instead.
553
+ now.message = "the disk filled up handing every part over: sending one part at a time"
554
+ NSLog("BackgroundTransfer: %@: %@", now.id, now.message ?? "")
555
+ self.handOver(self.store.put(now), [.part(n: parts[0].n, offset: parts[0].offset, length: parts[0].length)])
556
+ return
557
+ }
558
+ let missing = !FileManager.default.fileExists(atPath: now.path)
559
+ self.fail(&now, Reason.isDiskFull(ns) ? Reason.diskFull : (missing ? Reason.fileMissing : Reason.sizeMismatch),
560
+ "part \(parts[0].n) copy: \(ns.localizedDescription)")
561
+ return
562
+ }
563
+ var tasks: [URLSessionUploadTask] = []
564
+ for p in parts {
565
+ guard let request = PartsUpload.partRequest(now, n: p.n, size: now.total) else {
566
+ removeCopies()
567
+ tasks.forEach { $0.cancel() }
568
+ self.fail(&now, Reason.sessionRefused, "part \(p.n) has no URL")
569
+ return
570
+ }
571
+ let task = self.uploadSession.uploadTask(with: request, fromFile: p.copy)
572
+ task.taskDescription = now.key
573
+ PartsUpload.assign(&now, task: task.taskIdentifier, part: p.n, copy: p.copy.path)
574
+ tasks.append(task)
575
+ }
576
+ now.taskIdentifier = nil
577
+ now.startOffset = PartsUpload.storedBytes(now, size: now.total)
578
+ // Recorded before any task can end, so every answer finds its part.
579
+ self.save(now, event: "progress")
580
+ tasks.forEach { $0.resume() }
581
+ // The app left the screen while this one part was being copied: the rest go too.
582
+ if !self.onScreen && !PartsUpload.pending(now, size: now.total).isEmpty { self.handOverRemaining(now) }
583
+ }
584
+ }
585
+ }
586
+
587
+ /// Cancels every task the upload's record has handed over and removes their copies.
588
+ private func dropParts(_ r: inout TransferRecord) {
589
+ guard let tasks = r.partTasks else { return }
590
+ for t in tasks.values { try? FileManager.default.removeItem(atPath: t.copy) }
591
+ r.partTasks = nil
592
+ let key = r.key
593
+ let ids = Set(tasks.keys.compactMap(Int.init))
594
+ uploadSession.getAllTasks { all in
595
+ for task in all where task.taskDescription == key && ids.contains(task.taskIdentifier) { task.cancel() }
596
+ }
597
+ }
598
+
599
+ /// The answer to a `put`'s task or to a part's or the commit's.
600
+ private func answered(_ record: TransferRecord, part n: Int, status: Int, etag: String?, body: Data?) {
601
+ var r = record
602
+ guard UploadProtocol.resolve(r.protocol)?.inParts == true else {
603
+ apply(PartsUpload.afterPut(status: status), to: &r, httpStatus: status)
604
+ return
605
+ }
606
+ if n == 0 {
607
+ r.currentPart = nil
608
+ if cancelling.contains(r.key) {
609
+ // Cancelled while the commit was out: only the server's confirmation outranks the cancel.
610
+ let outcome = PartsUpload.afterCommit(&r, status: status, body: body)
611
+ if outcome == .finished { apply(outcome, to: &r, httpStatus: status); return }
612
+ // An answer that leaves it open whether the commit was applied (S3's 404 to a resent
613
+ // completion) keeps `committing`, so a restart reports session-closed.
614
+ if case .failed(let reason, _) = outcome, reason == Reason.sessionClosed { r.committing = true }
615
+ markCancelled(&r)
616
+ return
617
+ }
618
+ let outcome = PartsUpload.afterCommit(&r, status: status, body: body)
619
+ apply(outcome, to: &r, httpStatus: status)
620
+ return
621
+ }
622
+ guard n > 0 else {
623
+ apply(.failed(reason: Reason.unknown, message: "an answer came for no part"), to: &r, httpStatus: status)
624
+ return
625
+ }
626
+ if let stop = PartsUpload.afterPart(&r, n: n, status: status, etag: etag, size: r.total) {
627
+ apply(stop, to: &r, httpStatus: status)
628
+ return
629
+ }
630
+ // Stored: on to the next one, or the commit once the others in tasks' hands are in too.
631
+ r.state = .running
632
+ r.reason = nil
633
+ r.message = nil
634
+ r.httpStatus = nil
635
+ // Never the whole object before the commit is confirmed.
636
+ r.bytes = min(PartsUpload.storedBytes(r, size: r.total), max(r.total - 1, 0))
637
+ r = store.put(r)
638
+ listener?.transferChanged(r, event: "progress")
639
+ sendNextPart(r)
640
+ }
641
+
642
+ /// Keeps the system's completion handler while work the app must finish is under way.
643
+ private func hold() { checks += 1 }
644
+
645
+ private func release() {
646
+ checks -= 1
647
+ if checks == 0 {
648
+ let handlers = heldHandlers
649
+ heldHandlers = []
650
+ handlers.forEach { DispatchQueue.main.async(execute: $0) }
651
+ }
652
+ }
653
+
654
+ // MARK: Download
655
+
656
+ private func startDownload(_ record: TransferRecord) {
657
+ var r = record
658
+ guard let url = URL(string: r.url) else {
659
+ fail(&r, Reason.sessionRefused, "not a URL")
660
+ return
661
+ }
662
+ let dest = URL(fileURLWithPath: r.path)
663
+ try? FileManager.default.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true)
664
+ let part = Files.partURL(for: dest)
665
+ if TransferPaths.isSymbolicLink(dest) || TransferPaths.isSymbolicLink(part) {
666
+ fail(&r, Reason.unknown, "refusing to write through a symbolic link at \(r.path)")
667
+ return
668
+ }
669
+ let have = (try? Files.fileSize(part)) ?? 0
670
+ let task: URLSessionDownloadTask
671
+ if let data = try? Data(contentsOf: resumeDataURL(r.key)) {
672
+ // The system kept the bytes of an earlier attempt; it resumes those itself.
673
+ try? FileManager.default.removeItem(at: resumeDataURL(r.key))
674
+ task = downloadSession.downloadTask(withResumeData: data)
675
+ } else {
676
+ var request = URLRequest(url: url)
677
+ for (k, v) in r.headers { request.setValue(v, forHTTPHeaderField: k) }
678
+ request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
679
+ if have > 0 { request.setValue("bytes=\(have)-", forHTTPHeaderField: "Range") }
680
+ task = downloadSession.downloadTask(with: request)
681
+ }
682
+ task.taskDescription = r.key
683
+ r.bytes = have
684
+ r.startOffset = have
685
+ r.taskIdentifier = task.taskIdentifier
686
+ save(r, event: "progress")
687
+ task.resume()
688
+ }
689
+
690
+ private func resumeDataURL(_ key: String) -> URL {
691
+ let safe = key.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? key
692
+ return directory.appendingPathComponent("resume/\(safe).data")
693
+ }
694
+
695
+ /// Called on `queue` with the finished file in the system's temporary location, which is gone
696
+ /// once this returns.
697
+ private func downloadArrived(_ task: URLSessionDownloadTask, at location: URL) {
698
+ guard let key = task.taskDescription, var r = store.get(key: key) else { return }
699
+ let dest = URL(fileURLWithPath: r.path)
700
+ let part = Files.partURL(for: dest)
701
+ let http = task.response as? HTTPURLResponse
702
+ let status = http?.statusCode ?? 0
703
+ if let crossed = redirectedElsewhere(task) {
704
+ downloadOutcome[key] = (.failed, Reason.sessionRefused, crossed, status)
705
+ return
706
+ }
707
+ if TransferPaths.isSymbolicLink(dest) || TransferPaths.isSymbolicLink(part) {
708
+ downloadOutcome[key] = (.failed, Reason.unknown, "refusing to write through a symbolic link at \(r.path)", status)
709
+ return
710
+ }
711
+ do {
712
+ // What the delivered file holds: from the start this task asked for (its Range, or 0) to the
713
+ // end. The system may resume a dropped download by itself and answer 206 to a request that
714
+ // had no Range; the file it hands over is still whole from that start.
715
+ let asked = ContentRange.requestedStart(task.originalRequest?.value(forHTTPHeaderField: "Range"))
716
+ switch status {
717
+ case 200, 206:
718
+ let range = ContentRange.parse(http?.value(forHTTPHeaderField: "Content-Range"))
719
+ let total: Int64
720
+ if status == 200 || asked == 0 {
721
+ // The whole object: it replaces whatever was in the part file.
722
+ if FileManager.default.fileExists(atPath: part.path) { try FileManager.default.removeItem(at: part) }
723
+ try FileManager.default.moveItem(at: location, to: part)
724
+ let expected = status == 206 ? (range?.total ?? -1) : (http?.expectedContentLength ?? -1)
725
+ total = expected >= 0 ? expected : (try Files.fileSize(part))
726
+ } else {
727
+ // The rest after the part file's bytes.
728
+ let have = (try? Files.fileSize(part)) ?? 0
729
+ guard have == asked else {
730
+ try? FileManager.default.removeItem(at: part)
731
+ downloadOutcome[key] = (.interrupted, Reason.sizeMismatch, "the part file changed while downloading; starting again", status)
732
+ return
733
+ }
734
+ try Files.append(location, to: part)
735
+ total = range?.total ?? -1
736
+ }
737
+ try Files.finish(part: part, at: dest, size: total)
738
+ r.total = try Files.fileSize(dest)
739
+ case 416:
740
+ let range = ContentRange.parse(http?.value(forHTTPHeaderField: "Content-Range"))
741
+ let have = (try? Files.fileSize(part)) ?? 0
742
+ if let range = range, range.total == have, have > 0 {
743
+ try Files.finish(part: part, at: dest, size: have)
744
+ r.total = have
745
+ } else {
746
+ try? FileManager.default.removeItem(at: part)
747
+ downloadOutcome[key] = (.interrupted, Reason.sizeMismatch, "the part file didn't fit the object; starting again", status)
748
+ return
749
+ }
750
+ default:
751
+ let (reason, resumable) = Reason.forStatus(status)
752
+ downloadOutcome[key] = (resumable ? .interrupted : .failed, reason, "download HTTP \(status)", status)
753
+ return
754
+ }
755
+ downloadOutcome[key] = (.finished, nil, nil, status)
756
+ r.bytes = r.total
757
+ store.put(r, save: false)
758
+ } catch {
759
+ let ns = error as NSError
760
+ let full = Reason.isDiskFull(ns)
761
+ if full { try? FileManager.default.removeItem(at: part) }
762
+ downloadOutcome[key] = (.failed, full ? Reason.diskFull : Reason.sizeMismatch, ns.localizedDescription, status)
763
+ if !full { try? FileManager.default.removeItem(at: part) }
764
+ }
765
+ }
766
+
767
+ // MARK: Outcomes
768
+
769
+ private func completed(_ task: URLSessionTask, error: Error?) {
770
+ let body = uploadBodies.removeValue(forKey: task.taskIdentifier)
771
+ guard let key = task.taskDescription, var r = store.get(key: key) else { return }
772
+ // Once finished, failed or cancelled, a transfer has said its last word: one final state each.
773
+ if r.state == .finished || r.state == .failed || r.state == .cancelled { return }
774
+ // An upload in parts: which part the task carried (none: cancelled with the others, or older).
775
+ var part = -1
776
+ if r.direction == .upload, UploadProtocol.resolve(r.protocol)?.inParts == true {
777
+ if let t = PartsUpload.release(&r, task: task.taskIdentifier) {
778
+ try? FileManager.default.removeItem(atPath: t.copy)
779
+ part = t.part
780
+ } else if r.currentPart == 0 && (r.taskIdentifier == task.taskIdentifier || r.taskIdentifier == nil) {
781
+ part = 0
782
+ } else {
783
+ return
784
+ }
785
+ } else {
786
+ guard r.taskIdentifier == task.taskIdentifier || r.taskIdentifier == nil else { return } // an older task
787
+ }
788
+ let byUs = cancelling.contains(key)
789
+ r.taskIdentifier = nil
790
+ if r.direction == .upload {
791
+ if part <= 0 { removeRemainder(&r) }
792
+ let ns = error as NSError?
793
+ let cancelledError = ns?.domain == NSURLErrorDomain && ns?.code == NSURLErrorCancelled
794
+ switch PartsUpload.afterCancel(requested: byUs, inParts: UploadProtocol.resolve(r.protocol)?.inParts == true,
795
+ isCommit: part == 0, cancelledError: cancelledError,
796
+ otherError: ns != nil && !cancelledError, othersInFlight: r.partTasks != nil) {
797
+ case .cancelled:
798
+ // `committing` stays as it was: a commit cut off may have been applied.
799
+ markCancelled(&r)
800
+ return
801
+ case .ignore:
802
+ store.put(r) // A part landed after the cancel: nothing more goes; the others' ends report it.
803
+ return
804
+ case .asUsual, .confirmOrCancel:
805
+ break // An answered commit is decided in `answered`: finished only if confirmed.
806
+ }
807
+ if let error = ns {
808
+ let (reason, resumable) = Reason.forError(error, cancelledByUs: byUs)
809
+ if reason == Reason.cancelled { markCancelled(&r); return }
810
+ if resumable { interrupt(&r, reason, error.localizedDescription) } else { fail(&r, reason, error.localizedDescription) }
811
+ return
812
+ }
813
+ let http = task.response as? HTTPURLResponse
814
+ let status = http?.statusCode ?? 0
815
+ if let crossed = redirectedElsewhere(task) {
816
+ fail(&r, Reason.sessionRefused, crossed)
817
+ return
818
+ }
819
+ if UploadProtocol.resolve(r.protocol) != .firebaseResumable {
820
+ answered(r, part: part, status: status, etag: http?.value(forHTTPHeaderField: "ETag"), body: body)
821
+ return
822
+ }
823
+ let received = http?.value(forHTTPHeaderField: "X-Goog-Upload-Size-Received").flatMap { Int64($0) }
824
+ let outcome = UploadOutcome.afterResponse(status: status, uploadStatus: http?.value(forHTTPHeaderField: "X-Goog-Upload-Status"),
825
+ received: received, body: body, total: r.total)
826
+ if outcome == .query {
827
+ checkSession(r, refusedWith: status)
828
+ return
829
+ }
830
+ apply(outcome, to: &r, httpStatus: status)
831
+ return
832
+ }
833
+ // Download
834
+ if let outcome = downloadOutcome.removeValue(forKey: key) {
835
+ r = store.get(key: key) ?? r
836
+ r.taskIdentifier = nil
837
+ r.httpStatus = outcome.state == .finished ? nil : outcome.status
838
+ switch outcome.state {
839
+ case .finished:
840
+ r.state = .finished
841
+ r.reason = nil
842
+ r.message = nil
843
+ save(r, event: "stateChange")
844
+ case .interrupted:
845
+ interrupt(&r, outcome.reason ?? Reason.unknown, outcome.message ?? "")
846
+ default:
847
+ fail(&r, outcome.reason ?? Reason.unknown, outcome.message ?? "")
848
+ }
849
+ return
850
+ }
851
+ let ns = (error as NSError?) ?? NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown)
852
+ let (reason, resumable) = Reason.forError(ns, cancelledByUs: byUs)
853
+ if reason == Reason.cancelled { markCancelled(&r); return }
854
+ if let data = ns.userInfo[NSURLSessionDownloadTaskResumeData] as? Data {
855
+ try? FileManager.default.createDirectory(at: resumeDataURL(key).deletingLastPathComponent(), withIntermediateDirectories: true)
856
+ try? data.write(to: resumeDataURL(key))
857
+ }
858
+ if resumable { interrupt(&r, reason, ns.localizedDescription) } else { fail(&r, reason, ns.localizedDescription) }
859
+ }
860
+
861
+ /// A background session follows redirects by itself and tells nobody, so a task whose answer
862
+ /// came from another origin than the URL the app named is refused once it ends: the message, or
863
+ /// nil when it stayed where it was sent.
864
+ private func redirectedElsewhere(_ task: URLSessionTask) -> String? {
865
+ let original = task.originalRequest?.url
866
+ let final = task.response?.url ?? task.currentRequest?.url
867
+ guard Redirects.crossedOrigin(original: original, final: final) else { return nil }
868
+ return "redirected to \(final?.host ?? "another host"): the request left the host the URL named, so its answer isn't accepted"
869
+ }
870
+
871
+ /// The answer wasn't a clean finalize: the system may have resent the request by itself, with the
872
+ /// offset from when it was made, after the server had kept part of it. Ask the session before
873
+ /// believing the answer. The refusal is recorded first, so a process that ends before the answer
874
+ /// comes asks again at the next launch; the system's completion handler is held until it is in.
875
+ private func checkSession(_ record: TransferRecord, refusedWith status: Int) {
876
+ var r = record
877
+ r.state = .running
878
+ r.taskIdentifier = nil
879
+ r.refusedStatus = status
880
+ r = store.put(r)
881
+ guard let url = URL(string: r.url) else {
882
+ apply(.failed(reason: Reason.sessionRefused, message: "not a URL"), to: &r, httpStatus: status)
883
+ return
884
+ }
885
+ hold()
886
+ let time = BackgroundTime("BackgroundTransfer session check")
887
+ querySession(url, headers: r.headers) { response, error in
888
+ defer {
889
+ time.end()
890
+ self.release()
891
+ }
892
+ guard var now = self.store.get(key: r.key), now.isActive, now.taskIdentifier == nil, now.refusedStatus == status else { return }
893
+ let q = response as? HTTPURLResponse
894
+ let received = q?.value(forHTTPHeaderField: "X-Goog-Upload-Size-Received").flatMap { Int64($0) }
895
+ let after = UploadOutcome.afterQuery(originalStatus: status, queryStatus: error == nil ? q?.statusCode : nil, received: received,
896
+ uploadStatus: q?.value(forHTTPHeaderField: "X-Goog-Upload-Status"), total: now.total)
897
+ if let received = received { now.bytes = received }
898
+ self.apply(after, to: &now, httpStatus: status)
899
+ }
900
+ }
901
+
902
+ private func apply(_ outcome: UploadOutcome, to r: inout TransferRecord, httpStatus: Int) {
903
+ r.refusedStatus = nil
904
+ switch outcome {
905
+ case .finished:
906
+ r.httpStatus = nil
907
+ r.reason = nil
908
+ r.message = nil
909
+ r.bytes = r.total
910
+ r.state = .finished
911
+ save(r, event: "stateChange")
912
+ case .interrupted(let reason, let message):
913
+ r.httpStatus = httpStatus == 0 ? nil : httpStatus
914
+ interrupt(&r, reason, message)
915
+ case .failed(let reason, let message):
916
+ r.httpStatus = httpStatus == 0 ? nil : httpStatus
917
+ fail(&r, reason, message)
918
+ case .query:
919
+ r.httpStatus = httpStatus
920
+ interrupt(&r, Reason.unknown, "upload HTTP \(httpStatus)")
921
+ }
922
+ }
923
+
924
+ private func interrupt(_ r: inout TransferRecord, _ reason: String, _ message: String) {
925
+ // The other parts handed over stop too: starting the upload again asks the server what it holds.
926
+ dropParts(&r)
927
+ r.currentPart = nil
928
+ r.state = .interrupted
929
+ r.reason = reason
930
+ r.message = message
931
+ r.taskIdentifier = nil
932
+ save(r, event: "stateChange")
933
+ }
934
+
935
+ private func fail(_ r: inout TransferRecord, _ reason: String, _ message: String) {
936
+ cleanUp(&r)
937
+ r.state = .failed
938
+ r.reason = reason
939
+ r.message = message
940
+ r.taskIdentifier = nil
941
+ save(r, event: "stateChange")
942
+ }
943
+
944
+ /// Removes a transfer's temporary files: an upload's remainder copy, a download's part file and resume data.
945
+ private func cleanUp(_ r: inout TransferRecord) {
946
+ removeRemainder(&r)
947
+ dropParts(&r)
948
+ if r.direction == .download {
949
+ try? FileManager.default.removeItem(at: Files.partURL(for: URL(fileURLWithPath: r.path)))
950
+ try? FileManager.default.removeItem(at: resumeDataURL(r.key))
951
+ r.bytes = 0
952
+ }
953
+ }
954
+
955
+ private func removeRemainder(_ r: inout TransferRecord) {
956
+ if let path = r.remainderPath {
957
+ try? FileManager.default.removeItem(atPath: path)
958
+ r.remainderPath = nil
959
+ }
960
+ }
961
+
962
+ @discardableResult
963
+ private func save(_ r: TransferRecord, event: String) -> TransferRecord {
964
+ let stored = store.put(r)
965
+ if !stored.isActive { cancelling.remove(stored.key) }
966
+ lastSaved[r.key] = Date()
967
+ listener?.transferChanged(stored, event: event)
968
+ return stored
969
+ }
970
+
971
+ /// Progress: told to the app at most four times a second, written to disk every two seconds.
972
+ private func progressed(_ task: URLSessionTask, bytes: Int64, total: Int64) {
973
+ guard let key = task.taskDescription, var r = store.get(key: key),
974
+ r.taskIdentifier == task.taskIdentifier || r.partTasks?[String(task.taskIdentifier)] != nil else { return }
975
+ let wasQueued = r.state == .queued
976
+ r.state = .running
977
+ r.bytes = bytes
978
+ if total >= 0 { r.total = total }
979
+ let now = Date()
980
+ let persist = wasQueued || now.timeIntervalSince(lastSaved[key] ?? .distantPast) >= 2
981
+ let stored = store.put(r, save: persist)
982
+ if persist { lastSaved[key] = now }
983
+ if wasQueued { listener?.transferChanged(stored, event: "stateChange") }
984
+ if wasQueued || now.timeIntervalSince(lastProgress[key] ?? .distantPast) >= 0.25 {
985
+ lastProgress[key] = now
986
+ listener?.transferChanged(stored, event: "progress")
987
+ }
988
+ }
989
+ }
990
+
991
+ protocol TransferListener: AnyObject {
992
+ func transferChanged(_ record: TransferRecord, event: String)
993
+ }
994
+
995
+ extension TransferManager: URLSessionDataDelegate, URLSessionDownloadDelegate {
996
+ func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64,
997
+ totalBytesExpectedToSend: Int64) {
998
+ guard let key = task.taskDescription, let r = store.get(key: key) else { return }
999
+ var bytes = r.startOffset + totalBytesSent
1000
+ if r.partTasks?[String(task.taskIdentifier)] != nil {
1001
+ // One of the parts handed over: the session sends them one by one.
1002
+ bytes = PartsUpload.storedBytes(r, size: r.total) + totalBytesSent
1003
+ }
1004
+ if UploadProtocol.resolve(r.protocol) != .firebaseResumable {
1005
+ // Never the whole object before the server has confirmed it (a commit's body isn't file bytes).
1006
+ bytes = min(r.currentPart == 0 ? r.total : bytes, max(r.total - 1, 0))
1007
+ }
1008
+ progressed(task, bytes: bytes, total: r.total)
1009
+ }
1010
+
1011
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
1012
+ // An upload's response: the finalized object's metadata. Small; capped all the same.
1013
+ var body = uploadBodies[dataTask.taskIdentifier] ?? Data()
1014
+ if body.count + data.count <= 64 * 1024 { body.append(data) }
1015
+ uploadBodies[dataTask.taskIdentifier] = body
1016
+ }
1017
+
1018
+ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
1019
+ totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
1020
+ guard let key = downloadTask.taskDescription, let r = store.get(key: key) else { return }
1021
+ let total = totalBytesExpectedToWrite >= 0 ? r.startOffset + totalBytesExpectedToWrite : -1
1022
+ progressed(downloadTask, bytes: r.startOffset + totalBytesWritten, total: total)
1023
+ }
1024
+
1025
+ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
1026
+ downloadArrived(downloadTask, at: location)
1027
+ }
1028
+
1029
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
1030
+ completed(task, error: error)
1031
+ }
1032
+
1033
+ func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
1034
+ guard let id = session.configuration.identifier, let handler = completionHandlers.removeValue(forKey: id) else { return }
1035
+ // Not while a session check is out: the app would be suspended before its answer.
1036
+ if checks > 0 { heldHandlers.append(handler) } else { DispatchQueue.main.async(execute: handler) }
1037
+ }
1038
+ }
1039
+
1040
+ /// The plain sessions' redirect policy: followed on the same origin only, so the app's headers
1041
+ /// never reach a host it didn't name. (Background sessions take no such delegate; their tasks are
1042
+ /// checked when they end.)
1043
+ final class SameOriginRedirects: NSObject, URLSessionTaskDelegate {
1044
+ func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
1045
+ newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
1046
+ guard let from = task.originalRequest?.url, let to = request.url, Redirects.sameOrigin(from, to) else {
1047
+ completionHandler(nil) // The 3xx answer stands, and reads as a refusal.
1048
+ return
1049
+ }
1050
+ completionHandler(request)
1051
+ }
1052
+ }
1053
+
1054
+ /// Background execution time for work that must not be cut short when the app leaves the screen.
1055
+ final class BackgroundTime {
1056
+ private let lock = NSLock()
1057
+ private var id = UIBackgroundTaskIdentifier.invalid
1058
+
1059
+ init(_ name: String) {
1060
+ // Safe from any thread.
1061
+ let id = UIApplication.shared.beginBackgroundTask(withName: name) { [weak self] in self?.end() }
1062
+ lock.lock()
1063
+ self.id = id
1064
+ lock.unlock()
1065
+ }
1066
+
1067
+ func end() {
1068
+ lock.lock()
1069
+ let current = id
1070
+ id = .invalid
1071
+ lock.unlock()
1072
+ if current != .invalid { UIApplication.shared.endBackgroundTask(current) }
1073
+ }
1074
+ }