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,19 @@
1
+ require 'json'
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = 'CapacitorBackgroundTransfer'
7
+ # The same module name as the Swift package's target, so `import BackgroundTransferPlugin` works with either.
8
+ s.module_name = 'BackgroundTransferPlugin'
9
+ s.version = package['version']
10
+ s.summary = package['description']
11
+ s.license = package['license']
12
+ s.homepage = package['repository']['url']
13
+ s.author = package['author']
14
+ s.source = { :git => package['repository']['url'], :tag => s.version.to_s }
15
+ s.source_files = 'ios/Sources/**/*.{swift,h,m,c,cc,mm,cpp}'
16
+ s.ios.deployment_target = '15.0'
17
+ s.dependency 'Capacitor'
18
+ s.swift_version = '5.1'
19
+ end
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sandman-92
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/Package.swift ADDED
@@ -0,0 +1,31 @@
1
+ // swift-tools-version: 5.9
2
+ import PackageDescription
3
+
4
+ let package = Package(
5
+ name: "CapacitorBackgroundTransfer",
6
+ platforms: [.iOS(.v15)],
7
+ products: [
8
+ .library(
9
+ name: "CapacitorBackgroundTransfer",
10
+ targets: ["BackgroundTransferPlugin"])
11
+ ],
12
+ dependencies: [
13
+ .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "7.0.0")
14
+ ],
15
+ targets: [
16
+ // Foundation only: records, the store, the remainder copy and the download's part file.
17
+ .target(
18
+ name: "BackgroundTransferCore",
19
+ path: "ios/Sources/BackgroundTransferCore"),
20
+ .target(
21
+ name: "BackgroundTransferPlugin",
22
+ dependencies: [
23
+ "BackgroundTransferCore",
24
+ .product(name: "Capacitor", package: "capacitor-swift-pm"),
25
+ .product(name: "Cordova", package: "capacitor-swift-pm")
26
+ ],
27
+ path: "ios/Sources/BackgroundTransferPlugin")
28
+ // The core's tests are in ios/CoreTests, a package of their own that builds on a Mac
29
+ // without Capacitor's iOS-only binaries: `npm run test:ios`.
30
+ ]
31
+ )
package/README.md CHANGED
@@ -1,3 +1,543 @@
1
- # Temporary Holding Version
1
+ # capacitor-background-transfer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Uploads and downloads that keep going when your Capacitor app doesn't.**
4
+
5
+ [![CI](https://github.com/sandman-92/capacitor-background-transfer/actions/workflows/ci.yml/badge.svg)](https://github.com/sandman-92/capacitor-background-transfer/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
+ ![Capacitor 7](https://img.shields.io/badge/Capacitor-7-119eff.svg)
8
+ ![Android 6+](https://img.shields.io/badge/Android-6.0%2B-3ddc84.svg)
9
+ ![iOS 15+](https://img.shields.io/badge/iOS-15%2B-lightgrey.svg)
10
+
11
+ [Install](#install) · [Quick start](#quick-start) · [Upload protocols](docs/upload-protocols.md) ·
12
+ [How it works](docs/how-it-works.md) · [API](#api) · [Changelog](CHANGELOG.md)
13
+
14
+ A phone suspends an app soon after it leaves the screen, and an upload made with `fetch` or XHR
15
+ from the web view is suspended with it. For a large file on a mobile network, the user has to keep
16
+ the app open and the screen on until the last byte arrives.
17
+
18
+ This plugin hands the transfer to the operating system instead: a user-initiated data transfer job
19
+ on Android 14 and later, a foreground service below that, and a background `URLSession` on iOS.
20
+ The user can lock the phone or switch apps, the app can be closed, the connection can drop, and
21
+ the file still arrives. After an interruption it picks up from where it stopped instead of
22
+ starting again.
23
+
24
+ ## Highlights
25
+
26
+ - **Keeps going in the background.** It carries on with the phone locked, the app in the
27
+ background or closed, and through Doze. On iOS the system's transfer daemon keeps it running
28
+ after the app's process has ended.
29
+ - **Resumes instead of restarting.** An upload asks the server how much it already holds and
30
+ sends the rest. A download resumes with a `Range` request.
31
+ - **Four upload protocols.** Firebase Storage resumable uploads, Amazon S3 multipart uploads
32
+ (and S3-compatible services), Azure Blob block blobs, and a plain `PUT` to any presigned or
33
+ SAS URL. Downloads work with any URL.
34
+ - **No cloud keys in the plugin.** Your app or server starts the upload and hands over its URL,
35
+ presigned where the protocol needs it. The plugin never signs a request.
36
+ - **Truthful outcomes.** A transfer is reported finished only once every byte is confirmed, and
37
+ a download appears at its path only when it is complete. Every stopped transfer has a `reason`.
38
+ After a relaunch, `list()` tells you what finished or failed while the app was closed.
39
+ - **A small API.** `upload`, `download`, `cancel`, `list`, `forget` and two events, fully typed.
40
+ On the web it reports itself unavailable, so your app can fall back to its own code there.
41
+
42
+ ## Status
43
+
44
+ Early but complete: version 0.x, so the API may still change before 1.0. The JVM and Swift tests
45
+ run in CI, including against local MinIO (S3) and Azurite (Azure) servers. The upload protocols
46
+ also run end to end on the Android emulator and the iOS simulator, with the app killed, the
47
+ network cut and URLs left to expire. Real AWS and Azure accounts, a locked iPhone and makers' own
48
+ battery managers haven't been tested yet (see [what's checked](docs/upload-protocols.md#checked-here-and-not)).
49
+ Reports from real apps are very welcome.
50
+
51
+ ## Install
52
+
53
+ ```bash
54
+ npm install capacitor-background-transfer
55
+ npx cap sync
56
+ ```
57
+
58
+ | Platform | Supported |
59
+ |---|---|
60
+ | Capacitor | 7 |
61
+ | Android | 6.0 (API 23) and later |
62
+ | iOS | 15 and later, with Swift Package Manager or CocoaPods |
63
+ | Web | No: `isAvailable()` returns `{ available: false }` |
64
+
65
+ Each platform needs one small change to your app:
66
+
67
+ ### Android: one manifest entry
68
+
69
+ The plugin's manifest adds the `INTERNET`, `ACCESS_NETWORK_STATE`, `RUN_USER_INITIATED_JOBS`,
70
+ `RECEIVE_BOOT_COMPLETED`, `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_DATA_SYNC` and
71
+ `POST_NOTIFICATIONS` permissions and its job service. **Your app declares WorkManager's
72
+ foreground service with the `dataSync` type** (the plugin doesn't, so it can't clash with an app
73
+ that declares the service with other types as well). In `android/app/src/main/AndroidManifest.xml`,
74
+ inside `<application>` (with `xmlns:tools` on `<manifest>`):
75
+
76
+ ```xml
77
+ <service
78
+ android:name="androidx.work.impl.foreground.SystemForegroundService"
79
+ android:foregroundServiceType="dataSync"
80
+ tools:node="merge" />
81
+ ```
82
+
83
+ Without it, transfers below Android 14 stop when the app leaves the screen, and `isAvailable()`
84
+ carries a `warning` saying so. Ask for the notification permission on Android 13+ if you want the
85
+ progress notification shown; transfers run without it. The WorkManager version follows
86
+ `workManagerVersion` in your `variables.gradle` (default 2.10.0).
87
+
88
+ ### iOS: one `AppDelegate` method
89
+
90
+ Hand the system's background session events to the plugin in `AppDelegate`, so transfers that
91
+ end while the app is closed are recorded straight away (otherwise on the next launch):
92
+
93
+ ```swift
94
+ import BackgroundTransferPlugin
95
+
96
+ func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String,
97
+ completionHandler: @escaping () -> Void) {
98
+ if BackgroundTransferPlugin.handleEvents(forBackgroundURLSession: identifier, completionHandler: completionHandler) { return }
99
+ completionHandler()
100
+ }
101
+ ```
102
+
103
+ The module is `BackgroundTransferPlugin` with both Swift Package Manager and CocoaPods. Files to
104
+ upload must be readable while the phone is locked: the default data protection (until the first
105
+ unlock after a restart) is; complete protection isn't.
106
+
107
+ ### Where files may be
108
+
109
+ A transfer's `path` must be inside the app's own storage, and the native side checks this after
110
+ resolving symbolic links, whatever called it: on Android the app's files, no-backup files and
111
+ cache directories, internal and external (`Directory.Data`, `Directory.Cache` and
112
+ `Directory.External` of the Filesystem plugin); on iOS Documents, Library and tmp (every
113
+ Filesystem directory). Paths with `..`, paths into the plugin's own storage, and a download onto a
114
+ symbolic link are refused. An app that keeps files elsewhere (an app group container, say) lists
115
+ the extra roots in the plugin's configuration, never from JavaScript:
116
+
117
+ ```ts
118
+ // capacitor.config.ts
119
+ plugins: {
120
+ BackgroundTransfer: {
121
+ allowedRoots: ['/private/var/mobile/Containers/Shared/AppGroup/…/Videos'],
122
+ },
123
+ },
124
+ ```
125
+
126
+ ## Quick start
127
+
128
+ ```ts
129
+ import { BackgroundTransfer } from 'capacitor-background-transfer';
130
+
131
+ const { available } = await BackgroundTransfer.isAvailable();
132
+
133
+ await BackgroundTransfer.addListener('progress', ({ transfer }) => {
134
+ console.log(`${transfer.id}: ${transfer.bytes} of ${transfer.total} bytes`);
135
+ });
136
+ await BackgroundTransfer.addListener('stateChange', ({ transfer }) => {
137
+ // queued, running, interrupted, finished, failed or cancelled
138
+ });
139
+
140
+ // Upload: your server (or the Firebase SDK) starts the upload, then the plugin sends the file.
141
+ await BackgroundTransfer.upload({
142
+ id: 'clip-42',
143
+ path: fileUri, // an absolute path or file:// URI, e.g. from Filesystem.getUri()
144
+ url: sessionUrl, // here, the X-Goog-Upload-URL of a Firebase Storage resumable upload
145
+ notification: { title: 'Uploading', text: 'clip-42.mp4' }, // Android only
146
+ });
147
+
148
+ // Download any URL to a file.
149
+ await BackgroundTransfer.download({ id: 'clip-42', url: downloadUrl, path: destinationUri });
150
+
151
+ // At launch: what happened while the app was closed.
152
+ const { transfers } = await BackgroundTransfer.list();
153
+ ```
154
+
155
+ Two rules to know:
156
+
157
+ - **Start transfers while the app is on screen.** Android only lets a user-initiated job be
158
+ scheduled then, and iOS may defer work started from the background.
159
+ - **The `id` is how you resume.** Calling `upload()` or `download()` again with the `id` of an
160
+ `interrupted`, `failed` or `cancelled` transfer carries on from where it stopped. See
161
+ [Starting a transfer again](docs/how-it-works.md#starting-a-transfer-again).
162
+
163
+ ## Upload protocols
164
+
165
+ Pick one with the `protocol` option. Every protocol behaves the same way in the background and
166
+ reports through the same events.
167
+
168
+ | `protocol` | Uploads to | An interrupted upload resumes from |
169
+ |---|---|---|
170
+ | `firebase-resumable` (default) | A Firebase Storage resumable upload session | What the session holds |
171
+ | `s3-multipart` | An Amazon S3 multipart upload with presigned part URLs. S3-compatible services are expected to work; only MinIO is tested | The parts S3 holds, or the plugin's own record of them |
172
+ | `azure-blocks` | An Azure Blob Storage block blob through one SAS URL | The blocks Azure holds |
173
+ | `put` | Any URL that takes the whole file in one `PUT`, e.g. an S3 presigned `PutObject` URL or an Azure blob SAS URL | The start: there is nothing to resume from |
174
+
175
+ [docs/upload-protocols.md](docs/upload-protocols.md) has the server-side setup, the options, URL
176
+ lifetimes and a code example for each one.
177
+
178
+ ## How it works
179
+
180
+ | | Android 14+ | Android 6 to 13 | iOS |
181
+ |---|---|---|---|
182
+ | Runs as | A user-initiated data transfer job | A WorkManager worker in a `dataSync` foreground service | A background `URLSession` |
183
+ | Locked, in the background or removed from Recents | Carries on | Carries on | Carries on, also after the app's process ends |
184
+ | Network drops while the app is off screen | Waits, then resumes by itself | Reported `interrupted`, so start it again at the next launch | The system often retries; otherwise reported `interrupted` |
185
+ | Notification | Shows progress | Shows progress (the service's notification) | None |
186
+
187
+ One transfer runs per direction at a time, and the rest wait in a queue.
188
+ [docs/how-it-works.md](docs/how-it-works.md) covers each platform in detail, including
189
+ system stops, ordering, iOS resends, what is stored on the device, and every failure `reason`.
190
+
191
+ ## FAQ
192
+
193
+ **Why not just use `fetch` from the web view?** The web view's requests run in your app's process,
194
+ which the system suspends soon after the app leaves the screen. This plugin hands the transfer to
195
+ a part of the system that keeps running.
196
+
197
+ **What happens if the user swipes the app away or force-stops it?** The system ends the
198
+ transfer on purpose. It is reported `interrupted` (on iOS at the next launch), and starting it
199
+ again with the same `id` carries on from where it stopped.
200
+
201
+ **Are there limits?** Below Android 14, the system allows a `dataSync` foreground service six
202
+ hours a day. iOS may defer transfers started while the app is in the background. On iOS, resuming
203
+ an upload part-way needs temporary disk space for a copy of the bytes still to send.
204
+
205
+ **Where do my headers go?** To the host in the URL, and nowhere else: a redirect to another host
206
+ is refused rather than followed (on iOS, where the system follows it by itself, the transfer is
207
+ reported `session-refused` when it ends). While a transfer is queued or running its record,
208
+ `headers` included, is kept in the app's sandbox, in storage that is left out of device backups;
209
+ the headers are dropped the moment it finishes, fails, is cancelled or is interrupted (a restart
210
+ brings its own). The URL stays in the record until you call `forget()`, so presigned URLs with a
211
+ short life are the better route for credentials.
212
+
213
+ ## Feedback and contributing
214
+
215
+ Found a bug or want a feature? [Open an issue](https://github.com/sandman-92/capacitor-background-transfer/issues).
216
+ Pull requests are welcome too. [CONTRIBUTING.md](CONTRIBUTING.md) explains how to build the plugin,
217
+ run its tests (including the local S3 and Azure servers) and try a change on a device with the
218
+ [example app](example-app/). To report a security problem privately, see [SECURITY.md](SECURITY.md).
219
+
220
+ ## API
221
+
222
+ <docgen-index>
223
+
224
+ * [`isAvailable()`](#isavailable)
225
+ * [`upload(...)`](#upload)
226
+ * [`download(...)`](#download)
227
+ * [`cancel(...)`](#cancel)
228
+ * [`list()`](#list)
229
+ * [`forget(...)`](#forget)
230
+ * [`addListener('progress', ...)`](#addlistenerprogress-)
231
+ * [`addListener('stateChange', ...)`](#addlistenerstatechange-)
232
+ * [`removeAllListeners()`](#removealllisteners)
233
+ * [Interfaces](#interfaces)
234
+ * [Type Aliases](#type-aliases)
235
+
236
+ </docgen-index>
237
+
238
+ <docgen-api>
239
+ <!--Update the source file JSDoc comments and rerun docgen to update the docs below-->
240
+
241
+ ### isAvailable()
242
+
243
+ ```typescript
244
+ isAvailable() => Promise<AvailableResult>
245
+ ```
246
+
247
+ Whether native background transfers work here. The web says no.
248
+
249
+ **Returns:** <code>Promise&lt;<a href="#availableresult">AvailableResult</a>&gt;</code>
250
+
251
+ --------------------
252
+
253
+
254
+ ### upload(...)
255
+
256
+ ```typescript
257
+ upload(options: UploadOptions) => Promise<TransferEvent>
258
+ ```
259
+
260
+ Queue an upload to an upload you have set up on the server (see
261
+ `UploadProtocol`). Refused at once if its options are missing or don't
262
+ fit together (on Android and iOS also when `partUrls` doesn't match the
263
+ file's size). Call it while the app
264
+ is on screen: Android only lets a user-initiated job be scheduled then,
265
+ and iPhone may defer tasks started from the background.
266
+
267
+ | Param | Type |
268
+ | ------------- | ------------------------------------------------------- |
269
+ | **`options`** | <code><a href="#uploadoptions">UploadOptions</a></code> |
270
+
271
+ **Returns:** <code>Promise&lt;<a href="#transferevent">TransferEvent</a>&gt;</code>
272
+
273
+ --------------------
274
+
275
+
276
+ ### download(...)
277
+
278
+ ```typescript
279
+ download(options: DownloadOptions) => Promise<TransferEvent>
280
+ ```
281
+
282
+ Queue a download. Same rules as `upload`.
283
+
284
+ | Param | Type |
285
+ | ------------- | ----------------------------------------------------------- |
286
+ | **`options`** | <code><a href="#downloadoptions">DownloadOptions</a></code> |
287
+
288
+ **Returns:** <code>Promise&lt;<a href="#transferevent">TransferEvent</a>&gt;</code>
289
+
290
+ --------------------
291
+
292
+
293
+ ### cancel(...)
294
+
295
+ ```typescript
296
+ cancel(options: { id: string; direction: TransferDirection; }) => Promise<void>
297
+ ```
298
+
299
+ Cancel a transfer; its temporary files are removed. Unknown ids are ignored.
300
+
301
+ | Param | Type |
302
+ | ------------- | ------------------------------------------------------------------------------------------- |
303
+ | **`options`** | <code>{ id: string; direction: <a href="#transferdirection">TransferDirection</a>; }</code> |
304
+
305
+ --------------------
306
+
307
+
308
+ ### list()
309
+
310
+ ```typescript
311
+ list() => Promise<{ transfers: TransferRecord[]; }>
312
+ ```
313
+
314
+ Every transfer the plugin remembers, including ones that ran, finished
315
+ or failed while the app was closed. Ask on launch.
316
+
317
+ **Returns:** <code>Promise&lt;{ transfers: TransferRecord[]; }&gt;</code>
318
+
319
+ --------------------
320
+
321
+
322
+ ### forget(...)
323
+
324
+ ```typescript
325
+ forget(options?: { ids?: { id: string; direction: TransferDirection; }[] | undefined; } | undefined) => Promise<void>
326
+ ```
327
+
328
+ Forget finished, failed and cancelled transfers (all of them, or the
329
+ given ids). Queued, running and interrupted ones are kept.
330
+
331
+ | Param | Type |
332
+ | ------------- | -------------------------------------------------------------------------------------------------------- |
333
+ | **`options`** | <code>{ ids?: { id: string; direction: <a href="#transferdirection">TransferDirection</a>; }[]; }</code> |
334
+
335
+ --------------------
336
+
337
+
338
+ ### addListener('progress', ...)
339
+
340
+ ```typescript
341
+ addListener(eventName: 'progress', listener: (event: TransferEvent) => void) => Promise<PluginListenerHandle>
342
+ ```
343
+
344
+ Bytes moved. At most a few events a second per transfer.
345
+
346
+ | Param | Type |
347
+ | --------------- | --------------------------------------------------------------------------- |
348
+ | **`eventName`** | <code>'progress'</code> |
349
+ | **`listener`** | <code>(event: <a href="#transferevent">TransferEvent</a>) =&gt; void</code> |
350
+
351
+ **Returns:** <code>Promise&lt;<a href="#pluginlistenerhandle">PluginListenerHandle</a>&gt;</code>
352
+
353
+ --------------------
354
+
355
+
356
+ ### addListener('stateChange', ...)
357
+
358
+ ```typescript
359
+ addListener(eventName: 'stateChange', listener: (event: TransferEvent) => void) => Promise<PluginListenerHandle>
360
+ ```
361
+
362
+ Any change of `state` (queued, running, interrupted, finished, failed,
363
+ cancelled).
364
+
365
+ | Param | Type |
366
+ | --------------- | --------------------------------------------------------------------------- |
367
+ | **`eventName`** | <code>'stateChange'</code> |
368
+ | **`listener`** | <code>(event: <a href="#transferevent">TransferEvent</a>) =&gt; void</code> |
369
+
370
+ **Returns:** <code>Promise&lt;<a href="#pluginlistenerhandle">PluginListenerHandle</a>&gt;</code>
371
+
372
+ --------------------
373
+
374
+
375
+ ### removeAllListeners()
376
+
377
+ ```typescript
378
+ removeAllListeners() => Promise<void>
379
+ ```
380
+
381
+ --------------------
382
+
383
+
384
+ ### Interfaces
385
+
386
+
387
+ #### AvailableResult
388
+
389
+ | Prop | Type | Description |
390
+ | --------------- | -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
391
+ | **`available`** | <code>boolean</code> | |
392
+ | **`mechanism`** | <code>'job' \| 'worker' \| 'urlsession' \| 'none'</code> | How transfers run here: `job` (Android 14+ user-initiated data transfer job), `worker` (WorkManager `dataSync` foreground service below Android 14), `urlsession` (iPhone background `URLSession`) or `none` (web). |
393
+ | **`warning`** | <code>string</code> | Set when the app is set up so that transfers can't run as they should, e.g. below Android 14 when the manifest doesn't declare WorkManager's foreground service with the `dataSync` type (the worker then stops when the app leaves the screen). For logs, not for people. |
394
+
395
+
396
+ #### TransferEvent
397
+
398
+ | Prop | Type |
399
+ | -------------- | --------------------------------------------------------- |
400
+ | **`transfer`** | <code><a href="#transferrecord">TransferRecord</a></code> |
401
+
402
+
403
+ #### TransferRecord
404
+
405
+ What the plugin knows about one transfer.
406
+
407
+ | Prop | Type | Description |
408
+ | ---------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
409
+ | **`id`** | <code>string</code> | |
410
+ | **`direction`** | <code><a href="#transferdirection">TransferDirection</a></code> | |
411
+ | **`state`** | <code><a href="#transferstate">TransferState</a></code> | |
412
+ | **`url`** | <code>string</code> | |
413
+ | **`path`** | <code>string</code> | |
414
+ | **`protocol`** | <code><a href="#uploadprotocol">UploadProtocol</a></code> | Uploads: the protocol the session speaks. |
415
+ | **`bytes`** | <code>number</code> | Bytes the server holds (upload) or that have landed in `.part` (download). For `s3-multipart` and `azure-blocks`, the parts or blocks stored plus the bytes of the one being sent (so it goes back to the stored parts' end when a part cut off part-way is sent again); for `put`, the bytes sent so far in this attempt. Below `total` until the server has confirmed the whole object. |
416
+ | **`total`** | <code>number</code> | Total size, or -1 until it is known. |
417
+ | **`reason`** | <code><a href="#transferfailurereason">TransferFailureReason</a></code> | Set when `state` is `failed`, `cancelled` or `interrupted`. |
418
+ | **`message`** | <code>string</code> | Detail for logs; not for showing to people. |
419
+ | **`httpStatus`** | <code>number</code> | HTTP status of the response that stopped it, when there was one. |
420
+ | **`updatedAt`** | <code>number</code> | Milliseconds since the epoch. |
421
+
422
+
423
+ #### UploadOptions
424
+
425
+ | Prop | Type | Description |
426
+ | ------------------ | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
427
+ | **`url`** | <code>string</code> | Where the upload goes, which depends on `protocol`: - `firebase-resumable`: the session URL of an upload you have already started (the `X-Goog-Upload-URL` from its `start`). The plugin asks it how many bytes it holds, sends the rest and finalizes. - `put`: the URL to `PUT` the whole file to. - `s3-multipart`: the presigned `CompleteMultipartUpload` URL (`POST`, with the upload's `uploadId`). - `azure-blocks`: the blob's SAS URL (with its `sig` parameter). The blob's properties go in `headers` as `x-ms-blob-content-type` and the other `x-ms-blob-*` headers: they are sent with the commit only. |
428
+ | **`protocol`** | <code><a href="#uploadprotocol">UploadProtocol</a></code> | The protocol the upload speaks. Default `firebase-resumable`. An unknown value is refused. |
429
+ | **`partUrls`** | <code>string[]</code> | `s3-multipart` only, and required there: the presigned `UploadPart` URL of every part, part 1 first. There must be exactly as many as the file needs in `partSize` parts (at most 10,000). They must stay valid until the last part is sent. |
430
+ | **`partSize`** | <code>number</code> | `s3-multipart` only: the size of every part but the last, in bytes. Default 8 MiB. At least 5 MiB when there is more than one part, at most 5 GiB. |
431
+ | **`listPartsUrl`** | <code>string</code> | `s3-multipart` only, optional: the presigned `ListParts` URL (`GET`, with the `uploadId`). When it is given, a resumed upload asks the server which parts it holds instead of trusting the plugin's own record, so a part the server lost is sent again and fresh URLs for the same upload carry on where the old ones stopped. |
432
+ | **`blockSize`** | <code>number</code> | `azure-blocks` only: the size of every block but the last, in bytes. Default 8 MiB, at most 4000 MiB, and at most 50,000 blocks. |
433
+
434
+
435
+ #### DownloadOptions
436
+
437
+ | Prop | Type | Description |
438
+ | --------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
439
+ | **`url`** | <code>string</code> | The URL to fetch, already resolved (a Storage download URL carries its own token). Bytes go to `&lt;path&gt;.part` and the file is renamed to `path` only once every byte has landed. |
440
+
441
+
442
+ #### PluginListenerHandle
443
+
444
+ | Prop | Type |
445
+ | ------------ | ----------------------------------------- |
446
+ | **`remove`** | <code>() =&gt; Promise&lt;void&gt;</code> |
447
+
448
+
449
+ ### Type Aliases
450
+
451
+
452
+ #### TransferDirection
453
+
454
+ Which way a transfer moves bytes.
455
+
456
+ <code>'upload' | 'download'</code>
457
+
458
+
459
+ #### TransferState
460
+
461
+ Where a transfer is.
462
+
463
+ - `queued`: waiting its turn (one transfer runs per direction), or waiting
464
+ for the network on Android 14+, where the system restarts it.
465
+ - `running`: bytes are moving.
466
+ - `interrupted`: stopped by a network drop, the app being swiped away or
467
+ the system, and won't restart by itself. Start it again with the same
468
+ `id` and it carries on from where it stopped.
469
+ - `finished`: every byte landed. For a download the file is at `path`.
470
+ - `failed`: it can't finish as asked; `reason` says why. Its temporary
471
+ files are gone.
472
+ - `cancelled`: `cancel()` was called. Its temporary files are gone.
473
+
474
+ <code>'queued' | 'running' | 'interrupted' | 'finished' | 'failed' | 'cancelled'</code>
475
+
476
+
477
+ #### UploadProtocol
478
+
479
+ The upload protocol a transfer speaks. The plugin never signs anything: you
480
+ create the upload on the server and hand the plugin URLs that carry their
481
+ own authorisation (a session URL, presigned URLs, a SAS URL).
482
+
483
+ - `firebase-resumable`: a Firebase Storage resumable upload (the
484
+ `X-Goog-Upload-*` protocol: `POST` with `X-Goog-Upload-Command` `query`,
485
+ `upload` and `upload, finalize`). `url` is the session URL.
486
+ - `put`: the whole file in one `PUT` to `url`, e.g. an S3 presigned `PUT`
487
+ URL or an Azure blob SAS URL (pass `x-ms-blob-type: BlockBlob` in
488
+ `headers` for Azure). An interrupted upload starts again from the first
489
+ byte. S3 takes at most 5 GB in one `PUT`.
490
+ - `s3-multipart`: an S3 (or S3-compatible) multipart upload you have
491
+ created. `partUrls` are the presigned `UploadPart` URLs, part 1 first;
492
+ `url` is the presigned `CompleteMultipartUpload` URL. The plugin sends the
493
+ parts one at a time, keeps each `ETag`, skips the parts already stored when
494
+ it resumes, then completes the upload listing every part.
495
+ - `azure-blocks`: an Azure block blob. `url` is the blob's SAS URL with
496
+ write permission (`sp` including `w`, or `c` and `w`). The plugin sends
497
+ blocks with stable ids (`Put Block`), skips the ones in the blob's
498
+ uncommitted block list when it resumes, then commits them
499
+ (`Put Block List`).
500
+
501
+ <code>'firebase-resumable' | 'put' | 's3-multipart' | 'azure-blocks'</code>
502
+
503
+
504
+ #### TransferFailureReason
505
+
506
+ Why a transfer stopped without finishing.
507
+
508
+ - `file-missing`: the upload's file isn't there (or is a directory).
509
+ - `disk-full`: no space for a download, or for the remainder copy an
510
+ iPhone upload needs to resume part-way.
511
+ - `session-refused`: the server refused the request (HTTP 4xx other than
512
+ the two below), e.g. Firebase Storage security rules refused the upload at finalize (403), or
513
+ a presigned URL or SAS token expired or lacks a permission (403). `message` names the
514
+ request that was refused (a part, a block, the `PUT`, or the commit).
515
+ - `session-expired`: the upload session or download URL is gone (HTTP 404
516
+ or 410), e.g. an S3 multipart upload that was aborted, found out while
517
+ sending a part or asking ListParts. Start a new session. (An S3 upload
518
+ found gone only at the completion reports `session-closed`: it may have
519
+ been completed.)
520
+ - `session-closed`: the upload can't be confirmed from here. For `firebase-resumable`, the
521
+ session was already closed when the upload started; that isn't proof the object was accepted
522
+ (the Firebase Storage emulator closes a session whose finalize its security rules refused).
523
+ For `s3-multipart` and `azure-blocks`, the request that completes the object was sent in an
524
+ earlier run (or earlier in this one) and its answer never came, so it may or may not have
525
+ been applied. Either way, check the object on the server, and start a new upload if it
526
+ isn't there or is the wrong size.
527
+ - `size-mismatch`: the bytes that landed don't add up to the size the
528
+ server or file said.
529
+ - `network`: the connection dropped. Used with `interrupted`.
530
+ - `stopped-by-system`: the system ended the work (the app was swiped away
531
+ on iPhone, the work was stopped below Android 14). Used with
532
+ `interrupted`.
533
+ - `cancelled`: `cancel()` was called.
534
+ - `server-error`: the server kept answering 5xx.
535
+ - `unknown`: anything else; `message` has the detail.
536
+
537
+ <code>'file-missing' | 'disk-full' | 'session-refused' | 'session-expired' | 'session-closed' | 'size-mismatch' | 'network' | 'stopped-by-system' | 'cancelled' | 'server-error' | 'unknown'</code>
538
+
539
+ </docgen-api>
540
+
541
+ ## License
542
+
543
+ [MIT](LICENSE). Made by [sandman-92](https://github.com/sandman-92).