@capgo/capacitor-uploader 8.2.12 → 8.3.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/README.md +71 -5
- package/android/src/main/java/ee/forgr/capacitor/uploader/UploaderPlugin.java +69 -2
- package/dist/docs.json +50 -1
- package/dist/esm/definitions.d.ts +63 -0
- package/dist/esm/definitions.js.map +1 -1
- package/dist/esm/web.d.ts +3 -0
- package/dist/esm/web.js +3 -0
- package/dist/esm/web.js.map +1 -1
- package/dist/plugin.cjs.js +3 -0
- package/dist/plugin.cjs.js.map +1 -1
- package/dist/plugin.js +3 -0
- package/dist/plugin.js.map +1 -1
- package/ios/Sources/UploaderPlugin/UploaderPlugin.swift +11 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -65,6 +65,32 @@ Add the following to your `AndroidManifest.xml` file:
|
|
|
65
65
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
|
66
66
|
```
|
|
67
67
|
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
## iOS
|
|
71
|
+
|
|
72
|
+
On iOS the plugin uploads through a background `URLSession` using the identifier `CapacitorUploaderBackgroundSession`.
|
|
73
|
+
|
|
74
|
+
Uploads often work without extra `Info.plist` keys. To allow the system to wake your app when background transfers finish, add the `fetch` background mode:
|
|
75
|
+
|
|
76
|
+
```xml
|
|
77
|
+
<key>UIBackgroundModes</key>
|
|
78
|
+
<array>
|
|
79
|
+
<string>fetch</string>
|
|
80
|
+
</array>
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Do **not** add the `processing` background mode for this plugin alone. App Store Connect requires `BGTaskSchedulerPermittedIdentifiers` whenever `processing` is declared, and this plugin does not register `BGTaskScheduler` tasks. If your app already includes `processing` (for example from older documentation) and validation fails, add:
|
|
84
|
+
|
|
85
|
+
```xml
|
|
86
|
+
<key>BGTaskSchedulerPermittedIdentifiers</key>
|
|
87
|
+
<array>
|
|
88
|
+
<string>CapacitorUploaderBackgroundSession</string>
|
|
89
|
+
</array>
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
See [issue #115](https://github.com/Cap-go/capacitor-uploader/issues/115) for context.
|
|
93
|
+
|
|
68
94
|
## Example S3 upload
|
|
69
95
|
|
|
70
96
|
```typescript
|
|
@@ -232,6 +258,7 @@ Documentation for the [Capacitor Camera preview](https://github.com/Cap-go/camer
|
|
|
232
258
|
* [`startUpload(...)`](#startupload)
|
|
233
259
|
* [`removeUpload(...)`](#removeupload)
|
|
234
260
|
* [`addListener('events', ...)`](#addlistenerevents-)
|
|
261
|
+
* [`acknowledgeEvent(...)`](#acknowledgeevent)
|
|
235
262
|
* [`getPluginVersion()`](#getpluginversion)
|
|
236
263
|
* [Interfaces](#interfaces)
|
|
237
264
|
|
|
@@ -242,6 +269,20 @@ Documentation for the [Capacitor Camera preview](https://github.com/Cap-go/camer
|
|
|
242
269
|
|
|
243
270
|
Capacitor Uploader Plugin for uploading files with background support and progress tracking.
|
|
244
271
|
|
|
272
|
+
### iOS setup
|
|
273
|
+
|
|
274
|
+
On iOS the native layer uses a background `URLSession` with the identifier
|
|
275
|
+
`CapacitorUploaderBackgroundSession`. Many apps can upload without adding
|
|
276
|
+
`UIBackgroundModes`; add `fetch` when you need uploads to continue after the app
|
|
277
|
+
is suspended.
|
|
278
|
+
|
|
279
|
+
App Store Connect rejects builds that declare `UIBackgroundModes` → `processing`
|
|
280
|
+
without `BGTaskSchedulerPermittedIdentifiers`. This plugin does not schedule
|
|
281
|
+
`BGTaskScheduler` work, so avoid `processing` unless another feature needs it.
|
|
282
|
+
If `processing` is present (for example from older setup guides), include
|
|
283
|
+
`CapacitorUploaderBackgroundSession` in `BGTaskSchedulerPermittedIdentifiers`
|
|
284
|
+
in your app's `Info.plist`.
|
|
285
|
+
|
|
245
286
|
### startUpload(...)
|
|
246
287
|
|
|
247
288
|
```typescript
|
|
@@ -308,6 +349,30 @@ Events are fired for:
|
|
|
308
349
|
--------------------
|
|
309
350
|
|
|
310
351
|
|
|
352
|
+
### acknowledgeEvent(...)
|
|
353
|
+
|
|
354
|
+
```typescript
|
|
355
|
+
acknowledgeEvent(options: { eventId: string; }) => Promise<void>
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
Acknowledge receipt of an upload event and remove it from the plugin cache.
|
|
359
|
+
|
|
360
|
+
Completed and failed events are stored in the plugin's persistent cache so they can be
|
|
361
|
+
re-delivered if the app is closed or backgrounded before the event is processed.
|
|
362
|
+
Call this method after successfully handling a 'completed' or 'failed' event to prevent
|
|
363
|
+
it from being re-broadcast the next time the plugin initialises.
|
|
364
|
+
|
|
365
|
+
Progress ('uploading') events do not have an eventId and do not need to be acknowledged.
|
|
366
|
+
|
|
367
|
+
| Param | Type | Description |
|
|
368
|
+
| ------------- | --------------------------------- | ---------------------------------------------- |
|
|
369
|
+
| **`options`** | <code>{ eventId: string; }</code> | - Object containing the eventId to acknowledge |
|
|
370
|
+
|
|
371
|
+
**Since:** 0.0.2
|
|
372
|
+
|
|
373
|
+
--------------------
|
|
374
|
+
|
|
375
|
+
|
|
311
376
|
### getPluginVersion()
|
|
312
377
|
|
|
313
378
|
```typescript
|
|
@@ -365,11 +430,12 @@ Configuration options for uploading a file.
|
|
|
365
430
|
|
|
366
431
|
Event emitted during the upload lifecycle.
|
|
367
432
|
|
|
368
|
-
| Prop | Type | Description
|
|
369
|
-
| ------------- | ----------------------------------------------------------------------- |
|
|
370
|
-
| **`name`** | <code>'uploading' \| 'completed' \| 'failed'</code> | The current status of the upload. - 'uploading': Upload is in progress - 'completed': Upload finished successfully - 'failed': Upload encountered an error
|
|
371
|
-
| **`payload`** | <code>{ percent?: number; error?: string; statusCode?: number; }</code> | Additional data about the upload event.
|
|
372
|
-
| **`id`** | <code>string</code> | Unique identifier for this upload task.
|
|
433
|
+
| Prop | Type | Description | Since |
|
|
434
|
+
| ------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
|
|
435
|
+
| **`name`** | <code>'uploading' \| 'completed' \| 'failed'</code> | The current status of the upload. - 'uploading': Upload is in progress - 'completed': Upload finished successfully - 'failed': Upload encountered an error | 0.0.1 |
|
|
436
|
+
| **`payload`** | <code>{ percent?: number; error?: string; statusCode?: number; }</code> | Additional data about the upload event. | 0.0.1 |
|
|
437
|
+
| **`id`** | <code>string</code> | Unique identifier for this upload task. | 0.0.1 |
|
|
438
|
+
| **`eventId`** | <code>string</code> | Unique identifier for this specific event instance. Only present on 'completed' and 'failed' events. Used with acknowledgeEvent() to confirm receipt and remove the event from the plugin cache. Progress ('uploading') events do not have an eventId and are not persisted. | 0.0.2 |
|
|
373
439
|
|
|
374
440
|
</docgen-api>
|
|
375
441
|
|
|
@@ -3,8 +3,10 @@ package ee.forgr.capacitor.uploader;
|
|
|
3
3
|
import android.app.NotificationChannel;
|
|
4
4
|
import android.app.NotificationManager;
|
|
5
5
|
import android.content.Context;
|
|
6
|
+
import android.content.SharedPreferences;
|
|
6
7
|
import android.net.Uri;
|
|
7
8
|
import android.os.Build;
|
|
9
|
+
import android.util.Log;
|
|
8
10
|
import android.webkit.MimeTypeMap;
|
|
9
11
|
import com.getcapacitor.JSArray;
|
|
10
12
|
import com.getcapacitor.JSObject;
|
|
@@ -16,10 +18,12 @@ import java.util.ArrayList;
|
|
|
16
18
|
import java.util.HashMap;
|
|
17
19
|
import java.util.Iterator;
|
|
18
20
|
import java.util.Map;
|
|
21
|
+
import java.util.UUID;
|
|
19
22
|
import net.gotev.uploadservice.data.UploadInfo;
|
|
20
23
|
import net.gotev.uploadservice.network.ServerResponse;
|
|
21
24
|
import net.gotev.uploadservice.observer.request.RequestObserver;
|
|
22
25
|
import net.gotev.uploadservice.observer.request.RequestObserverDelegate;
|
|
26
|
+
import org.json.JSONException;
|
|
23
27
|
import org.json.JSONObject;
|
|
24
28
|
|
|
25
29
|
@CapacitorPlugin(name = "Uploader")
|
|
@@ -29,7 +33,7 @@ public class UploaderPlugin extends Plugin {
|
|
|
29
33
|
|
|
30
34
|
private static final String CAPACITOR_CONTENT_PATH_PREFIX = "/_capacitor_content_";
|
|
31
35
|
|
|
32
|
-
private final String pluginVersion = "8.
|
|
36
|
+
private final String pluginVersion = "8.3.0";
|
|
33
37
|
|
|
34
38
|
private Uploader implementation;
|
|
35
39
|
|
|
@@ -37,6 +41,51 @@ public class UploaderPlugin extends Plugin {
|
|
|
37
41
|
private static final String CHANNEL_NAME = "Uploader Notifications";
|
|
38
42
|
private static final String CHANNEL_DESCRIPTION = "Notifications for file uploads";
|
|
39
43
|
|
|
44
|
+
private static final String PREFS_NAME = "CapacitorUploaderPrefs";
|
|
45
|
+
private static final String PENDING_EVENTS_KEY = "pending_events";
|
|
46
|
+
private static final String TAG = "UploaderPlugin";
|
|
47
|
+
|
|
48
|
+
private void saveEventToPrefs(String eventId, JSObject event) {
|
|
49
|
+
SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
|
|
50
|
+
String existingJson = prefs.getString(PENDING_EVENTS_KEY, "{}");
|
|
51
|
+
try {
|
|
52
|
+
JSONObject pendingEvents = new JSONObject(existingJson);
|
|
53
|
+
pendingEvents.put(eventId, new JSONObject(event.toString()));
|
|
54
|
+
prefs.edit().putString(PENDING_EVENTS_KEY, pendingEvents.toString()).apply();
|
|
55
|
+
} catch (JSONException e) {
|
|
56
|
+
Log.e(TAG, "Failed to persist upload event", e);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
private void removeEventFromPrefs(String eventId) {
|
|
61
|
+
SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
|
|
62
|
+
String existingJson = prefs.getString(PENDING_EVENTS_KEY, "{}");
|
|
63
|
+
try {
|
|
64
|
+
JSONObject pendingEvents = new JSONObject(existingJson);
|
|
65
|
+
pendingEvents.remove(eventId);
|
|
66
|
+
prefs.edit().putString(PENDING_EVENTS_KEY, pendingEvents.toString()).apply();
|
|
67
|
+
} catch (JSONException e) {
|
|
68
|
+
Log.e(TAG, "Failed to remove upload event from prefs", e);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private void replayPendingEvents() {
|
|
73
|
+
SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
|
|
74
|
+
String existingJson = prefs.getString(PENDING_EVENTS_KEY, "{}");
|
|
75
|
+
try {
|
|
76
|
+
JSONObject pendingEvents = new JSONObject(existingJson);
|
|
77
|
+
Iterator<String> keys = pendingEvents.keys();
|
|
78
|
+
while (keys.hasNext()) {
|
|
79
|
+
String eventId = keys.next();
|
|
80
|
+
JSONObject eventJson = pendingEvents.getJSONObject(eventId);
|
|
81
|
+
JSObject event = JSObject.fromJSONObject(eventJson);
|
|
82
|
+
notifyListeners("events", event);
|
|
83
|
+
}
|
|
84
|
+
} catch (JSONException e) {
|
|
85
|
+
Log.e(TAG, "Failed to replay pending upload events", e);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
40
89
|
private void createNotificationChannel() {
|
|
41
90
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
42
91
|
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
|
|
@@ -76,6 +125,9 @@ public class UploaderPlugin extends Plugin {
|
|
|
76
125
|
payload.put("statusCode", serverResponse.getCode());
|
|
77
126
|
event.put("payload", payload);
|
|
78
127
|
event.put("id", uploadInfo.getUploadId());
|
|
128
|
+
String eventId = UUID.randomUUID().toString();
|
|
129
|
+
event.put("eventId", eventId);
|
|
130
|
+
saveEventToPrefs(eventId, event);
|
|
79
131
|
notifyListeners("events", event);
|
|
80
132
|
}
|
|
81
133
|
|
|
@@ -87,6 +139,9 @@ public class UploaderPlugin extends Plugin {
|
|
|
87
139
|
payload.put("error", exception.getMessage());
|
|
88
140
|
event.put("payload", payload);
|
|
89
141
|
event.put("id", uploadInfo.getUploadId());
|
|
142
|
+
String eventId = UUID.randomUUID().toString();
|
|
143
|
+
event.put("eventId", eventId);
|
|
144
|
+
saveEventToPrefs(eventId, event);
|
|
90
145
|
notifyListeners("events", event);
|
|
91
146
|
}
|
|
92
147
|
|
|
@@ -100,12 +155,13 @@ public class UploaderPlugin extends Plugin {
|
|
|
100
155
|
|
|
101
156
|
@Override
|
|
102
157
|
public void onCompletedWhileNotObserving() {
|
|
103
|
-
|
|
158
|
+
replayPendingEvents();
|
|
104
159
|
}
|
|
105
160
|
}
|
|
106
161
|
);
|
|
107
162
|
|
|
108
163
|
implementation = new Uploader(getContext().getApplicationContext());
|
|
164
|
+
replayPendingEvents();
|
|
109
165
|
}
|
|
110
166
|
|
|
111
167
|
public static String getMimeType(String url) {
|
|
@@ -263,6 +319,17 @@ public class UploaderPlugin extends Plugin {
|
|
|
263
319
|
return map;
|
|
264
320
|
}
|
|
265
321
|
|
|
322
|
+
@PluginMethod
|
|
323
|
+
public void acknowledgeEvent(PluginCall call) {
|
|
324
|
+
String eventId = call.getString("eventId");
|
|
325
|
+
if (eventId == null || eventId.isEmpty()) {
|
|
326
|
+
call.reject("Missing required parameter: eventId");
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
removeEventFromPrefs(eventId);
|
|
330
|
+
call.resolve();
|
|
331
|
+
}
|
|
332
|
+
|
|
266
333
|
@PluginMethod
|
|
267
334
|
public void getPluginVersion(final PluginCall call) {
|
|
268
335
|
try {
|
package/dist/docs.json
CHANGED
|
@@ -2,8 +2,12 @@
|
|
|
2
2
|
"api": {
|
|
3
3
|
"name": "UploaderPlugin",
|
|
4
4
|
"slug": "uploaderplugin",
|
|
5
|
-
"docs": "Capacitor Uploader Plugin for uploading files with background support and progress tracking.",
|
|
5
|
+
"docs": "Capacitor Uploader Plugin for uploading files with background support and progress tracking.\n\n### iOS setup\n\nOn iOS the native layer uses a background `URLSession` with the identifier\n`CapacitorUploaderBackgroundSession`. Many apps can upload without adding\n`UIBackgroundModes`; add `fetch` when you need uploads to continue after the app\nis suspended.\n\nApp Store Connect rejects builds that declare `UIBackgroundModes` → `processing`\nwithout `BGTaskSchedulerPermittedIdentifiers`. This plugin does not schedule\n`BGTaskScheduler` work, so avoid `processing` unless another feature needs it.\nIf `processing` is present (for example from older setup guides), include\n`CapacitorUploaderBackgroundSession` in `BGTaskSchedulerPermittedIdentifiers`\nin your app's `Info.plist`.",
|
|
6
6
|
"tags": [
|
|
7
|
+
{
|
|
8
|
+
"text": "```xml\n<key>UIBackgroundModes</key>\n<array>\n <string>fetch</string>\n</array>\n<key>BGTaskSchedulerPermittedIdentifiers</key>\n<array>\n <string>CapacitorUploaderBackgroundSession</string>\n</array>\n```",
|
|
9
|
+
"name": "example"
|
|
10
|
+
},
|
|
7
11
|
{
|
|
8
12
|
"text": "0.0.1",
|
|
9
13
|
"name": "since"
|
|
@@ -135,6 +139,39 @@
|
|
|
135
139
|
],
|
|
136
140
|
"slug": "addlistenerevents-"
|
|
137
141
|
},
|
|
142
|
+
{
|
|
143
|
+
"name": "acknowledgeEvent",
|
|
144
|
+
"signature": "(options: { eventId: string; }) => Promise<void>",
|
|
145
|
+
"parameters": [
|
|
146
|
+
{
|
|
147
|
+
"name": "options",
|
|
148
|
+
"docs": "- Object containing the eventId to acknowledge",
|
|
149
|
+
"type": "{ eventId: string; }"
|
|
150
|
+
}
|
|
151
|
+
],
|
|
152
|
+
"returns": "Promise<void>",
|
|
153
|
+
"tags": [
|
|
154
|
+
{
|
|
155
|
+
"name": "param",
|
|
156
|
+
"text": "options - Object containing the eventId to acknowledge"
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
"name": "returns",
|
|
160
|
+
"text": "Promise that resolves when the event has been removed from the cache"
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
"name": "since",
|
|
164
|
+
"text": "0.0.2"
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
"name": "example",
|
|
168
|
+
"text": "```typescript\nconst listener = await Uploader.addListener('events', async (event) => {\n if (event.name === 'completed' || event.name === 'failed') {\n handleUploadResult(event);\n if (event.eventId) {\n await Uploader.acknowledgeEvent({ eventId: event.eventId });\n }\n }\n});\n```"
|
|
169
|
+
}
|
|
170
|
+
],
|
|
171
|
+
"docs": "Acknowledge receipt of an upload event and remove it from the plugin cache.\n\nCompleted and failed events are stored in the plugin's persistent cache so they can be\nre-delivered if the app is closed or backgrounded before the event is processed.\nCall this method after successfully handling a 'completed' or 'failed' event to prevent\nit from being re-broadcast the next time the plugin initialises.\n\nProgress ('uploading') events do not have an eventId and do not need to be acknowledged.",
|
|
172
|
+
"complexTypes": [],
|
|
173
|
+
"slug": "acknowledgeevent"
|
|
174
|
+
},
|
|
138
175
|
{
|
|
139
176
|
"name": "getPluginVersion",
|
|
140
177
|
"signature": "() => Promise<{ version: string; }>",
|
|
@@ -450,6 +487,18 @@
|
|
|
450
487
|
"docs": "Unique identifier for this upload task.",
|
|
451
488
|
"complexTypes": [],
|
|
452
489
|
"type": "string"
|
|
490
|
+
},
|
|
491
|
+
{
|
|
492
|
+
"name": "eventId",
|
|
493
|
+
"tags": [
|
|
494
|
+
{
|
|
495
|
+
"text": "0.0.2",
|
|
496
|
+
"name": "since"
|
|
497
|
+
}
|
|
498
|
+
],
|
|
499
|
+
"docs": "Unique identifier for this specific event instance.\nOnly present on 'completed' and 'failed' events.\nUsed with acknowledgeEvent() to confirm receipt and remove the event from the plugin cache.\nProgress ('uploading') events do not have an eventId and are not persisted.",
|
|
500
|
+
"complexTypes": [],
|
|
501
|
+
"type": "string | undefined"
|
|
453
502
|
}
|
|
454
503
|
]
|
|
455
504
|
}
|
|
@@ -180,10 +180,45 @@ export interface UploadEvent {
|
|
|
180
180
|
* @since 0.0.1
|
|
181
181
|
*/
|
|
182
182
|
id: string;
|
|
183
|
+
/**
|
|
184
|
+
* Unique identifier for this specific event instance.
|
|
185
|
+
* Only present on 'completed' and 'failed' events.
|
|
186
|
+
* Used with acknowledgeEvent() to confirm receipt and remove the event from the plugin cache.
|
|
187
|
+
* Progress ('uploading') events do not have an eventId and are not persisted.
|
|
188
|
+
*
|
|
189
|
+
* @since 0.0.2
|
|
190
|
+
*/
|
|
191
|
+
eventId?: string;
|
|
183
192
|
}
|
|
184
193
|
/**
|
|
185
194
|
* Capacitor Uploader Plugin for uploading files with background support and progress tracking.
|
|
186
195
|
*
|
|
196
|
+
* ### iOS setup
|
|
197
|
+
*
|
|
198
|
+
* On iOS the native layer uses a background `URLSession` with the identifier
|
|
199
|
+
* `CapacitorUploaderBackgroundSession`. Many apps can upload without adding
|
|
200
|
+
* `UIBackgroundModes`; add `fetch` when you need uploads to continue after the app
|
|
201
|
+
* is suspended.
|
|
202
|
+
*
|
|
203
|
+
* App Store Connect rejects builds that declare `UIBackgroundModes` → `processing`
|
|
204
|
+
* without `BGTaskSchedulerPermittedIdentifiers`. This plugin does not schedule
|
|
205
|
+
* `BGTaskScheduler` work, so avoid `processing` unless another feature needs it.
|
|
206
|
+
* If `processing` is present (for example from older setup guides), include
|
|
207
|
+
* `CapacitorUploaderBackgroundSession` in `BGTaskSchedulerPermittedIdentifiers`
|
|
208
|
+
* in your app's `Info.plist`.
|
|
209
|
+
*
|
|
210
|
+
* @example
|
|
211
|
+
* ```xml
|
|
212
|
+
* <key>UIBackgroundModes</key>
|
|
213
|
+
* <array>
|
|
214
|
+
* <string>fetch</string>
|
|
215
|
+
* </array>
|
|
216
|
+
* <key>BGTaskSchedulerPermittedIdentifiers</key>
|
|
217
|
+
* <array>
|
|
218
|
+
* <string>CapacitorUploaderBackgroundSession</string>
|
|
219
|
+
* </array>
|
|
220
|
+
* ```
|
|
221
|
+
*
|
|
187
222
|
* @since 0.0.1
|
|
188
223
|
*/
|
|
189
224
|
export interface UploaderPlugin {
|
|
@@ -277,6 +312,34 @@ export interface UploaderPlugin {
|
|
|
277
312
|
* ```
|
|
278
313
|
*/
|
|
279
314
|
addListener(eventName: 'events', listenerFunc: (state: UploadEvent) => void): Promise<PluginListenerHandle>;
|
|
315
|
+
/**
|
|
316
|
+
* Acknowledge receipt of an upload event and remove it from the plugin cache.
|
|
317
|
+
*
|
|
318
|
+
* Completed and failed events are stored in the plugin's persistent cache so they can be
|
|
319
|
+
* re-delivered if the app is closed or backgrounded before the event is processed.
|
|
320
|
+
* Call this method after successfully handling a 'completed' or 'failed' event to prevent
|
|
321
|
+
* it from being re-broadcast the next time the plugin initialises.
|
|
322
|
+
*
|
|
323
|
+
* Progress ('uploading') events do not have an eventId and do not need to be acknowledged.
|
|
324
|
+
*
|
|
325
|
+
* @param options - Object containing the eventId to acknowledge
|
|
326
|
+
* @returns Promise that resolves when the event has been removed from the cache
|
|
327
|
+
* @since 0.0.2
|
|
328
|
+
* @example
|
|
329
|
+
* ```typescript
|
|
330
|
+
* const listener = await Uploader.addListener('events', async (event) => {
|
|
331
|
+
* if (event.name === 'completed' || event.name === 'failed') {
|
|
332
|
+
* handleUploadResult(event);
|
|
333
|
+
* if (event.eventId) {
|
|
334
|
+
* await Uploader.acknowledgeEvent({ eventId: event.eventId });
|
|
335
|
+
* }
|
|
336
|
+
* }
|
|
337
|
+
* });
|
|
338
|
+
* ```
|
|
339
|
+
*/
|
|
340
|
+
acknowledgeEvent(options: {
|
|
341
|
+
eventId: string;
|
|
342
|
+
}): Promise<void>;
|
|
280
343
|
/**
|
|
281
344
|
* Get the native Capacitor plugin version.
|
|
282
345
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\n/**\n * Configuration options for uploading a file.\n *\n * @since 0.0.1\n */\nexport interface UploadFileOption {\n /**\n * The local file path of the file to upload.\n * Can be a file:// URL or an absolute path.\n *\n * @since 0.0.3\n */\n filePath: string;\n\n /**\n * The form field name for the file part when using multipart upload.\n *\n * If omitted, `uploadOption.fileField` is used (defaults to `'file'`).\n *\n * @since 0.0.3\n */\n fieldName?: string;\n\n /**\n * The MIME type of this file.\n * If not specified, the plugin will attempt to determine it automatically.\n *\n * @since 0.0.3\n */\n mimeType?: string;\n}\n\nexport interface uploadOption {\n /**\n * The local file path of the file to upload.\n * Can be a file:// URL or an absolute path.\n *\n * If you need to upload multiple files in a single multipart request, use `files`.\n *\n * @since 0.0.1\n */\n filePath?: string;\n\n /**\n * Multiple files to upload in a single request.\n *\n * When provided, uploads are sent as `multipart/form-data` with one part per file.\n * Use `fieldName` to control each part name (e.g. `images[]`).\n *\n * Note: `PUT` uploads (e.g. presigned S3 URLs) only support a single file.\n *\n * @since 0.0.3\n */\n files?: UploadFileOption[];\n\n /**\n * The server URL endpoint where the file should be uploaded.\n *\n * @since 0.0.1\n */\n serverUrl: string;\n\n /**\n * The title of the upload notification shown to the user.\n * Android only.\n *\n * @default 'Uploading'\n * @since 0.0.1\n */\n notificationTitle?: string;\n\n /**\n * HTTP headers to send with the upload request.\n * Useful for authentication tokens, content types, etc.\n *\n * @since 0.0.1\n * @example\n * ```typescript\n * headers: {\n * 'Authorization': 'Bearer token123',\n * 'X-Custom-Header': 'value'\n * }\n * ```\n */\n headers: {\n [key: string]: string;\n };\n\n /**\n * The HTTP method to use for the upload request.\n *\n * @default 'POST'\n * @since 0.0.1\n */\n method?: 'PUT' | 'POST';\n\n /**\n * The MIME type of the file being uploaded.\n * If not specified, the plugin will attempt to determine it automatically.\n *\n * @since 0.0.1\n * @example 'image/jpeg', 'application/pdf', 'video/mp4'\n */\n mimeType?: string;\n\n /**\n * Additional form parameters to send with the upload request.\n * These will be included as form data in multipart uploads.\n *\n * @since 0.0.1\n */\n parameters?: { [key: string]: string };\n\n /**\n * The maximum number of times to retry the upload if it fails.\n *\n * @since 0.0.1\n * @default 0\n */\n maxRetries?: number;\n\n /**\n * The type of upload to perform.\n * - 'binary': Uploads the file as raw binary data in the request body\n * - 'multipart': Uploads the file as multipart/form-data\n *\n * @default 'binary' when `method` is `'PUT'`, otherwise `'multipart'`\n * @since 0.0.2\n */\n uploadType?: 'binary' | 'multipart';\n\n /**\n * The form field name for the file when using multipart upload type.\n * Only used when uploadType is 'multipart'.\n *\n * For multi-file uploads via `files`, this is used as the default field name\n * when a file entry does not specify `fieldName`.\n *\n * @default 'file'\n * @since 0.0.2\n */\n fileField?: string;\n}\n\n/**\n * Event emitted during the upload lifecycle.\n *\n * @since 0.0.1\n */\nexport interface UploadEvent {\n /**\n * The current status of the upload.\n * - 'uploading': Upload is in progress\n * - 'completed': Upload finished successfully\n * - 'failed': Upload encountered an error\n *\n * @since 0.0.1\n */\n name: 'uploading' | 'completed' | 'failed';\n\n /**\n * Additional data about the upload event.\n *\n * @since 0.0.1\n */\n payload: {\n /**\n * Upload progress percentage from 0 to 100.\n * Only present during 'uploading' events.\n *\n * @since 0.0.1\n */\n percent?: number;\n\n /**\n * Error message if the upload failed.\n * Only present during 'failed' events.\n *\n * @since 0.0.1\n */\n error?: string;\n\n /**\n * HTTP status code returned by the server.\n * Present during 'completed' and 'failed' events.\n *\n * @since 0.0.1\n */\n statusCode?: number;\n };\n\n /**\n * Unique identifier for this upload task.\n *\n * @since 0.0.1\n */\n id: string;\n}\n\n/**\n * Capacitor Uploader Plugin for uploading files with background support and progress tracking.\n *\n * @since 0.0.1\n */\nexport interface UploaderPlugin {\n /**\n * Start uploading a file to a server.\n *\n * The upload will continue in the background even if the app is closed or backgrounded.\n * Listen to upload events to track progress, completion, or failure.\n *\n * @param options - Configuration for the upload\n * @returns Promise that resolves with the upload ID\n * @throws Error if the upload fails to start\n * @since 0.0.1\n * @example\n * ```typescript\n * const { id } = await Uploader.startUpload({\n * filePath: 'file:///path/to/file.jpg',\n * serverUrl: 'https://example.com/upload',\n * headers: {\n * 'Authorization': 'Bearer token'\n * },\n * method: 'POST',\n * uploadType: 'multipart',\n * fileField: 'photo'\n * });\n * console.log('Upload started with ID:', id);\n * ```\n *\n * @example\n * ```typescript\n * const { id } = await Uploader.startUpload({\n * serverUrl: 'https://api.example.com/upload',\n * method: 'POST',\n * uploadType: 'multipart',\n * files: [\n * { filePath: 'file:///...photo1.jpg', fieldName: 'images[]', mimeType: 'image/jpeg' },\n * { filePath: 'file:///...photo2.jpg', fieldName: 'images[]', mimeType: 'image/jpeg' },\n * ],\n * parameters: { albumId: '7' },\n * headers: { Authorization: 'Bearer token' },\n * });\n * console.log('Upload started with ID:', id);\n * ```\n */\n startUpload(options: uploadOption): Promise<{ id: string }>;\n\n /**\n * Cancel and remove an ongoing upload.\n *\n * This will stop the upload if it's in progress and clean up resources.\n *\n * @param options - Object containing the upload ID to remove\n * @returns Promise that resolves when the upload is removed\n * @throws Error if the upload ID is not found\n * @since 0.0.1\n * @example\n * ```typescript\n * await Uploader.removeUpload({ id: 'upload-123' });\n * ```\n */\n removeUpload(options: { id: string }): Promise<void>;\n\n /**\n * Listen for upload progress and status events.\n *\n * Events are fired for:\n * - Upload progress updates (with percent)\n * - Upload completion (with statusCode)\n * - Upload failure (with error and statusCode)\n *\n * @param eventName - Must be 'events'\n * @param listenerFunc - Callback function to handle upload events\n * @returns Promise that resolves with a listener handle for removal\n * @since 0.0.1\n * @example\n * ```typescript\n * const listener = await Uploader.addListener('events', (event) => {\n * if (event.name === 'uploading') {\n * console.log(`Upload ${event.id}: ${event.payload.percent}%`);\n * } else if (event.name === 'completed') {\n * console.log(`Upload ${event.id} completed`);\n * } else if (event.name === 'failed') {\n * console.error(`Upload ${event.id} failed:`, event.payload.error);\n * }\n * });\n *\n * // Remove listener when done\n * await listener.remove();\n * ```\n */\n addListener(eventName: 'events', listenerFunc: (state: UploadEvent) => void): Promise<PluginListenerHandle>;\n\n /**\n * Get the native Capacitor plugin version.\n *\n * @returns Promise that resolves with the plugin version\n * @throws Error if getting the version fails\n * @since 0.0.1\n * @example\n * ```typescript\n * const { version } = await Uploader.getPluginVersion();\n * console.log('Plugin version:', version);\n * ```\n */\n getPluginVersion(): Promise<{ version: string }>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\n/**\n * Configuration options for uploading a file.\n *\n * @since 0.0.1\n */\nexport interface UploadFileOption {\n /**\n * The local file path of the file to upload.\n * Can be a file:// URL or an absolute path.\n *\n * @since 0.0.3\n */\n filePath: string;\n\n /**\n * The form field name for the file part when using multipart upload.\n *\n * If omitted, `uploadOption.fileField` is used (defaults to `'file'`).\n *\n * @since 0.0.3\n */\n fieldName?: string;\n\n /**\n * The MIME type of this file.\n * If not specified, the plugin will attempt to determine it automatically.\n *\n * @since 0.0.3\n */\n mimeType?: string;\n}\n\nexport interface uploadOption {\n /**\n * The local file path of the file to upload.\n * Can be a file:// URL or an absolute path.\n *\n * If you need to upload multiple files in a single multipart request, use `files`.\n *\n * @since 0.0.1\n */\n filePath?: string;\n\n /**\n * Multiple files to upload in a single request.\n *\n * When provided, uploads are sent as `multipart/form-data` with one part per file.\n * Use `fieldName` to control each part name (e.g. `images[]`).\n *\n * Note: `PUT` uploads (e.g. presigned S3 URLs) only support a single file.\n *\n * @since 0.0.3\n */\n files?: UploadFileOption[];\n\n /**\n * The server URL endpoint where the file should be uploaded.\n *\n * @since 0.0.1\n */\n serverUrl: string;\n\n /**\n * The title of the upload notification shown to the user.\n * Android only.\n *\n * @default 'Uploading'\n * @since 0.0.1\n */\n notificationTitle?: string;\n\n /**\n * HTTP headers to send with the upload request.\n * Useful for authentication tokens, content types, etc.\n *\n * @since 0.0.1\n * @example\n * ```typescript\n * headers: {\n * 'Authorization': 'Bearer token123',\n * 'X-Custom-Header': 'value'\n * }\n * ```\n */\n headers: {\n [key: string]: string;\n };\n\n /**\n * The HTTP method to use for the upload request.\n *\n * @default 'POST'\n * @since 0.0.1\n */\n method?: 'PUT' | 'POST';\n\n /**\n * The MIME type of the file being uploaded.\n * If not specified, the plugin will attempt to determine it automatically.\n *\n * @since 0.0.1\n * @example 'image/jpeg', 'application/pdf', 'video/mp4'\n */\n mimeType?: string;\n\n /**\n * Additional form parameters to send with the upload request.\n * These will be included as form data in multipart uploads.\n *\n * @since 0.0.1\n */\n parameters?: { [key: string]: string };\n\n /**\n * The maximum number of times to retry the upload if it fails.\n *\n * @since 0.0.1\n * @default 0\n */\n maxRetries?: number;\n\n /**\n * The type of upload to perform.\n * - 'binary': Uploads the file as raw binary data in the request body\n * - 'multipart': Uploads the file as multipart/form-data\n *\n * @default 'binary' when `method` is `'PUT'`, otherwise `'multipart'`\n * @since 0.0.2\n */\n uploadType?: 'binary' | 'multipart';\n\n /**\n * The form field name for the file when using multipart upload type.\n * Only used when uploadType is 'multipart'.\n *\n * For multi-file uploads via `files`, this is used as the default field name\n * when a file entry does not specify `fieldName`.\n *\n * @default 'file'\n * @since 0.0.2\n */\n fileField?: string;\n}\n\n/**\n * Event emitted during the upload lifecycle.\n *\n * @since 0.0.1\n */\nexport interface UploadEvent {\n /**\n * The current status of the upload.\n * - 'uploading': Upload is in progress\n * - 'completed': Upload finished successfully\n * - 'failed': Upload encountered an error\n *\n * @since 0.0.1\n */\n name: 'uploading' | 'completed' | 'failed';\n\n /**\n * Additional data about the upload event.\n *\n * @since 0.0.1\n */\n payload: {\n /**\n * Upload progress percentage from 0 to 100.\n * Only present during 'uploading' events.\n *\n * @since 0.0.1\n */\n percent?: number;\n\n /**\n * Error message if the upload failed.\n * Only present during 'failed' events.\n *\n * @since 0.0.1\n */\n error?: string;\n\n /**\n * HTTP status code returned by the server.\n * Present during 'completed' and 'failed' events.\n *\n * @since 0.0.1\n */\n statusCode?: number;\n };\n\n /**\n * Unique identifier for this upload task.\n *\n * @since 0.0.1\n */\n id: string;\n\n /**\n * Unique identifier for this specific event instance.\n * Only present on 'completed' and 'failed' events.\n * Used with acknowledgeEvent() to confirm receipt and remove the event from the plugin cache.\n * Progress ('uploading') events do not have an eventId and are not persisted.\n *\n * @since 0.0.2\n */\n eventId?: string;\n}\n\n/**\n * Capacitor Uploader Plugin for uploading files with background support and progress tracking.\n *\n * ### iOS setup\n *\n * On iOS the native layer uses a background `URLSession` with the identifier\n * `CapacitorUploaderBackgroundSession`. Many apps can upload without adding\n * `UIBackgroundModes`; add `fetch` when you need uploads to continue after the app\n * is suspended.\n *\n * App Store Connect rejects builds that declare `UIBackgroundModes` → `processing`\n * without `BGTaskSchedulerPermittedIdentifiers`. This plugin does not schedule\n * `BGTaskScheduler` work, so avoid `processing` unless another feature needs it.\n * If `processing` is present (for example from older setup guides), include\n * `CapacitorUploaderBackgroundSession` in `BGTaskSchedulerPermittedIdentifiers`\n * in your app's `Info.plist`.\n *\n * @example\n * ```xml\n * <key>UIBackgroundModes</key>\n * <array>\n * <string>fetch</string>\n * </array>\n * <key>BGTaskSchedulerPermittedIdentifiers</key>\n * <array>\n * <string>CapacitorUploaderBackgroundSession</string>\n * </array>\n * ```\n *\n * @since 0.0.1\n */\nexport interface UploaderPlugin {\n /**\n * Start uploading a file to a server.\n *\n * The upload will continue in the background even if the app is closed or backgrounded.\n * Listen to upload events to track progress, completion, or failure.\n *\n * @param options - Configuration for the upload\n * @returns Promise that resolves with the upload ID\n * @throws Error if the upload fails to start\n * @since 0.0.1\n * @example\n * ```typescript\n * const { id } = await Uploader.startUpload({\n * filePath: 'file:///path/to/file.jpg',\n * serverUrl: 'https://example.com/upload',\n * headers: {\n * 'Authorization': 'Bearer token'\n * },\n * method: 'POST',\n * uploadType: 'multipart',\n * fileField: 'photo'\n * });\n * console.log('Upload started with ID:', id);\n * ```\n *\n * @example\n * ```typescript\n * const { id } = await Uploader.startUpload({\n * serverUrl: 'https://api.example.com/upload',\n * method: 'POST',\n * uploadType: 'multipart',\n * files: [\n * { filePath: 'file:///...photo1.jpg', fieldName: 'images[]', mimeType: 'image/jpeg' },\n * { filePath: 'file:///...photo2.jpg', fieldName: 'images[]', mimeType: 'image/jpeg' },\n * ],\n * parameters: { albumId: '7' },\n * headers: { Authorization: 'Bearer token' },\n * });\n * console.log('Upload started with ID:', id);\n * ```\n */\n startUpload(options: uploadOption): Promise<{ id: string }>;\n\n /**\n * Cancel and remove an ongoing upload.\n *\n * This will stop the upload if it's in progress and clean up resources.\n *\n * @param options - Object containing the upload ID to remove\n * @returns Promise that resolves when the upload is removed\n * @throws Error if the upload ID is not found\n * @since 0.0.1\n * @example\n * ```typescript\n * await Uploader.removeUpload({ id: 'upload-123' });\n * ```\n */\n removeUpload(options: { id: string }): Promise<void>;\n\n /**\n * Listen for upload progress and status events.\n *\n * Events are fired for:\n * - Upload progress updates (with percent)\n * - Upload completion (with statusCode)\n * - Upload failure (with error and statusCode)\n *\n * @param eventName - Must be 'events'\n * @param listenerFunc - Callback function to handle upload events\n * @returns Promise that resolves with a listener handle for removal\n * @since 0.0.1\n * @example\n * ```typescript\n * const listener = await Uploader.addListener('events', (event) => {\n * if (event.name === 'uploading') {\n * console.log(`Upload ${event.id}: ${event.payload.percent}%`);\n * } else if (event.name === 'completed') {\n * console.log(`Upload ${event.id} completed`);\n * } else if (event.name === 'failed') {\n * console.error(`Upload ${event.id} failed:`, event.payload.error);\n * }\n * });\n *\n * // Remove listener when done\n * await listener.remove();\n * ```\n */\n addListener(eventName: 'events', listenerFunc: (state: UploadEvent) => void): Promise<PluginListenerHandle>;\n\n /**\n * Acknowledge receipt of an upload event and remove it from the plugin cache.\n *\n * Completed and failed events are stored in the plugin's persistent cache so they can be\n * re-delivered if the app is closed or backgrounded before the event is processed.\n * Call this method after successfully handling a 'completed' or 'failed' event to prevent\n * it from being re-broadcast the next time the plugin initialises.\n *\n * Progress ('uploading') events do not have an eventId and do not need to be acknowledged.\n *\n * @param options - Object containing the eventId to acknowledge\n * @returns Promise that resolves when the event has been removed from the cache\n * @since 0.0.2\n * @example\n * ```typescript\n * const listener = await Uploader.addListener('events', async (event) => {\n * if (event.name === 'completed' || event.name === 'failed') {\n * handleUploadResult(event);\n * if (event.eventId) {\n * await Uploader.acknowledgeEvent({ eventId: event.eventId });\n * }\n * }\n * });\n * ```\n */\n acknowledgeEvent(options: { eventId: string }): Promise<void>;\n\n /**\n * Get the native Capacitor plugin version.\n *\n * @returns Promise that resolves with the plugin version\n * @throws Error if getting the version fails\n * @since 0.0.1\n * @example\n * ```typescript\n * const { version } = await Uploader.getPluginVersion();\n * console.log('Plugin version:', version);\n * ```\n */\n getPluginVersion(): Promise<{ version: string }>;\n}\n"]}
|
package/dist/esm/web.d.ts
CHANGED
|
@@ -13,6 +13,9 @@ export declare class UploaderWeb extends WebPlugin implements UploaderPlugin {
|
|
|
13
13
|
private getFileFromPath;
|
|
14
14
|
private getFileFromIndexedDB;
|
|
15
15
|
private getFileFromSystem;
|
|
16
|
+
acknowledgeEvent(_options: {
|
|
17
|
+
eventId: string;
|
|
18
|
+
}): Promise<void>;
|
|
16
19
|
getPluginVersion(): Promise<{
|
|
17
20
|
version: string;
|
|
18
21
|
}>;
|
package/dist/esm/web.js
CHANGED
|
@@ -161,6 +161,9 @@ export class UploaderWeb extends WebPlugin {
|
|
|
161
161
|
return null;
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
|
+
async acknowledgeEvent(_options) {
|
|
165
|
+
// Web uploads run in-process; events are not persisted for replay.
|
|
166
|
+
}
|
|
164
167
|
async getPluginVersion() {
|
|
165
168
|
return { version: 'web' };
|
|
166
169
|
}
|
package/dist/esm/web.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAE7B,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG1C,MAAM,OAAO,WAAY,SAAQ,SAAS;IAA1C;;QACU,YAAO,GAAkE,IAAI,GAAG,EAAE,CAAC;IA4K7F,CAAC;IA1KC,KAAK,CAAC,WAAW,CAAC,OAAqB;QACrC,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;QAEpC,MAA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,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC5B,CAAC;CACF","sourcesContent":["import { WebPlugin } from '@capacitor/core';\nimport { openDB } from 'idb';\n\nimport { PathHelper } from './PathHelper';\nimport type { UploadFileOption, UploaderPlugin, uploadOption } from './definitions';\n\nexport class UploaderWeb extends WebPlugin implements UploaderPlugin {\n private uploads: Map<string, { controller: AbortController; retries: number }> = new Map();\n\n async startUpload(options: uploadOption): Promise<{ id: string }> {\n console.log('startUpload', options);\n\n const id = Math.random().toString(36).substring(2, 15);\n const controller = new AbortController();\n const maxRetries = options.maxRetries || 3;\n this.uploads.set(id, { controller, retries: maxRetries });\n\n this.doUpload(id, options);\n\n return { id };\n }\n\n async removeUpload(options: { id: string }): Promise<void> {\n console.log('removeUpload', options);\n const upload = this.uploads.get(options.id);\n if (upload) {\n upload.controller.abort();\n this.uploads.delete(options.id);\n this.notifyListeners('events', {\n name: 'cancelled',\n id: options.id,\n payload: {},\n });\n }\n }\n\n private async doUpload(id: string, options: uploadOption) {\n const { serverUrl, headers = {}, method = 'POST', parameters = {} } = options;\n const upload = this.uploads.get(id);\n\n if (!upload) return;\n\n try {\n const files = this.normalizeFiles(options);\n if (files.length === 0) throw new Error('Missing required parameter: filePath or files');\n\n const resolvedMethod = method.toUpperCase();\n const uploadType = options.uploadType ?? (resolvedMethod === 'PUT' ? 'binary' : 'multipart');\n\n let body: BodyInit;\n if (resolvedMethod === 'PUT' || uploadType === 'binary') {\n if (files.length !== 1) throw new Error('Binary uploads only support a single file');\n const file = await this.getFileFromPath(files[0].filePath);\n if (!file) throw new Error('File not found');\n body = file;\n } else {\n const formData = new FormData();\n\n for (const fileOption of files) {\n const file = await this.getFileFromPath(fileOption.filePath);\n if (!file) throw new Error('File not found');\n const fieldName = fileOption.fieldName ?? options.fileField ?? 'file';\n formData.append(fieldName, file);\n }\n\n for (const [key, value] of Object.entries(parameters)) {\n formData.append(key, value);\n }\n\n body = formData;\n }\n\n const response = await fetch(serverUrl, {\n method: resolvedMethod,\n headers,\n body,\n signal: upload.controller.signal,\n });\n\n if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);\n\n this.notifyListeners('events', {\n name: 'completed',\n id,\n payload: { statusCode: response.status },\n });\n\n this.uploads.delete(id);\n } catch (error) {\n if ((error as Error).name === 'AbortError') return;\n\n if (upload.retries > 0) {\n upload.retries--;\n console.log(`Retrying upload (retries left: ${upload.retries})`);\n setTimeout(() => this.doUpload(id, options), 1000);\n } else {\n this.notifyListeners('events', {\n name: 'failed',\n id,\n payload: { error: (error as Error).message },\n });\n this.uploads.delete(id);\n }\n }\n }\n\n private normalizeFiles(options: uploadOption): UploadFileOption[] {\n if (options.files && options.files.length > 0) return options.files;\n if (options.filePath) {\n return [\n {\n filePath: options.filePath,\n fieldName: options.fileField,\n mimeType: options.mimeType,\n },\n ];\n }\n return [];\n }\n\n private async getFileFromPath(filePath: string): Promise<File | null> {\n // Check if the path is an IndexedDB path\n if (PathHelper.isIndexedDBPath(filePath)) {\n return this.getFileFromIndexedDB(filePath);\n }\n\n // Otherwise, treat it as a file path from the system\n return this.getFileFromSystem(filePath);\n }\n\n // Retrieve the file from IndexedDB\n private async getFileFromIndexedDB(filePath: string): Promise<File | null> {\n // Parse the path to get the database, store name, and key\n const { database, storeName, key } = PathHelper.parseIndexedDBPath(filePath);\n\n try {\n // Open the IndexedDB database and access the object store\n const db = await openDB(database, 1, {\n upgrade(db) {\n if (!db.objectStoreNames.contains(storeName)) {\n db.createObjectStore(storeName);\n }\n },\n });\n\n // Get the blob from the store\n const blob = await db.get(storeName, key);\n if (!blob) {\n console.error(`File with key \"${key}\" not found in store \"${storeName}\" in database \"${database}\"`);\n return null;\n }\n\n // Convert the Blob to a File object\n return new File([blob], key, { type: blob.type });\n } catch (error) {\n console.error('Error retrieving file from IndexedDB:', error);\n return null;\n }\n }\n\n // Retrieve the file from the system (local file)\n private async getFileFromSystem(filePath: string): Promise<File | null> {\n try {\n // This is a simplified version. In a real-world scenario,\n // you might need to handle different types of paths or use a file system API.\n const response = await fetch(filePath);\n const blob = await response.blob();\n return new File([blob], filePath.split('/').pop() || 'file', {\n type: blob.type,\n });\n } catch (error) {\n console.error('Error getting file from system:', error);\n return null;\n }\n }\n\n async getPluginVersion(): Promise<{ version: string }> {\n return { version: 'web' };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAE7B,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG1C,MAAM,OAAO,WAAY,SAAQ,SAAS;IAA1C;;QACU,YAAO,GAAkE,IAAI,GAAG,EAAE,CAAC;IAgL7F,CAAC;IA9KC,KAAK,CAAC,WAAW,CAAC,OAAqB;QACrC,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;QAEpC,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACvD,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;QACzC,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,CAAC,CAAC;QAC3C,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,CAAC;QAE1D,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAE3B,OAAO,EAAE,EAAE,EAAE,CAAC;IAChB,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,OAAuB;QACxC,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;QACrC,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,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AC9D,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,iDAAiD;IACzC,KAAK,CAAC,iBAAiB,CAAC,QAAgB;QAC9C,IAAI,CAAC;YACH,0DAA0D;YAC1D,8EAA8E;YAC9E,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,QAAQ,CAAC,CAAC;YACvC,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;YACnC,OAAO,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,MAAM,EAAE;gBAC3D,IAAI,EAAE,IAAI,CAAC,IAAI;aAChB,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;YACxD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,QAA6B;QAClD,mEAAmE;IACrE,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC5B,CAAC;CACF","sourcesContent":["import { WebPlugin } from '@capacitor/core';\nimport { openDB } from 'idb';\n\nimport { PathHelper } from './PathHelper';\nimport type { UploadFileOption, UploaderPlugin, uploadOption } from './definitions';\n\nexport class UploaderWeb extends WebPlugin implements UploaderPlugin {\n private uploads: Map<string, { controller: AbortController; retries: number }> = new Map();\n\n async startUpload(options: uploadOption): Promise<{ id: string }> {\n console.log('startUpload', options);\n\n const id = Math.random().toString(36).substring(2, 15);\n const controller = new AbortController();\n const maxRetries = options.maxRetries || 3;\n this.uploads.set(id, { controller, retries: maxRetries });\n\n this.doUpload(id, options);\n\n return { id };\n }\n\n async removeUpload(options: { id: string }): Promise<void> {\n console.log('removeUpload', options);\n const upload = this.uploads.get(options.id);\n if (upload) {\n upload.controller.abort();\n this.uploads.delete(options.id);\n this.notifyListeners('events', {\n name: 'cancelled',\n id: options.id,\n payload: {},\n });\n }\n }\n\n private async doUpload(id: string, options: uploadOption) {\n const { serverUrl, headers = {}, method = 'POST', parameters = {} } = options;\n const upload = this.uploads.get(id);\n\n if (!upload) return;\n\n try {\n const files = this.normalizeFiles(options);\n if (files.length === 0) throw new Error('Missing required parameter: filePath or files');\n\n const resolvedMethod = method.toUpperCase();\n const uploadType = options.uploadType ?? (resolvedMethod === 'PUT' ? 'binary' : 'multipart');\n\n let body: BodyInit;\n if (resolvedMethod === 'PUT' || uploadType === 'binary') {\n if (files.length !== 1) throw new Error('Binary uploads only support a single file');\n const file = await this.getFileFromPath(files[0].filePath);\n if (!file) throw new Error('File not found');\n body = file;\n } else {\n const formData = new FormData();\n\n for (const fileOption of files) {\n const file = await this.getFileFromPath(fileOption.filePath);\n if (!file) throw new Error('File not found');\n const fieldName = fileOption.fieldName ?? options.fileField ?? 'file';\n formData.append(fieldName, file);\n }\n\n for (const [key, value] of Object.entries(parameters)) {\n formData.append(key, value);\n }\n\n body = formData;\n }\n\n const response = await fetch(serverUrl, {\n method: resolvedMethod,\n headers,\n body,\n signal: upload.controller.signal,\n });\n\n if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);\n\n this.notifyListeners('events', {\n name: 'completed',\n id,\n payload: { statusCode: response.status },\n });\n\n this.uploads.delete(id);\n } catch (error) {\n if ((error as Error).name === 'AbortError') return;\n\n if (upload.retries > 0) {\n upload.retries--;\n console.log(`Retrying upload (retries left: ${upload.retries})`);\n setTimeout(() => this.doUpload(id, options), 1000);\n } else {\n this.notifyListeners('events', {\n name: 'failed',\n id,\n payload: { error: (error as Error).message },\n });\n this.uploads.delete(id);\n }\n }\n }\n\n private normalizeFiles(options: uploadOption): UploadFileOption[] {\n if (options.files && options.files.length > 0) return options.files;\n if (options.filePath) {\n return [\n {\n filePath: options.filePath,\n fieldName: options.fileField,\n mimeType: options.mimeType,\n },\n ];\n }\n return [];\n }\n\n private async getFileFromPath(filePath: string): Promise<File | null> {\n // Check if the path is an IndexedDB path\n if (PathHelper.isIndexedDBPath(filePath)) {\n return this.getFileFromIndexedDB(filePath);\n }\n\n // Otherwise, treat it as a file path from the system\n return this.getFileFromSystem(filePath);\n }\n\n // Retrieve the file from IndexedDB\n private async getFileFromIndexedDB(filePath: string): Promise<File | null> {\n // Parse the path to get the database, store name, and key\n const { database, storeName, key } = PathHelper.parseIndexedDBPath(filePath);\n\n try {\n // Open the IndexedDB database and access the object store\n const db = await openDB(database, 1, {\n upgrade(db) {\n if (!db.objectStoreNames.contains(storeName)) {\n db.createObjectStore(storeName);\n }\n },\n });\n\n // Get the blob from the store\n const blob = await db.get(storeName, key);\n if (!blob) {\n console.error(`File with key \"${key}\" not found in store \"${storeName}\" in database \"${database}\"`);\n return null;\n }\n\n // Convert the Blob to a File object\n return new File([blob], key, { type: blob.type });\n } catch (error) {\n console.error('Error retrieving file from IndexedDB:', error);\n return null;\n }\n }\n\n // Retrieve the file from the system (local file)\n private async getFileFromSystem(filePath: string): Promise<File | null> {\n try {\n // This is a simplified version. In a real-world scenario,\n // you might need to handle different types of paths or use a file system API.\n const response = await fetch(filePath);\n const blob = await response.blob();\n return new File([blob], filePath.split('/').pop() || 'file', {\n type: blob.type,\n });\n } catch (error) {\n console.error('Error getting file from system:', error);\n return null;\n }\n }\n\n async acknowledgeEvent(_options: { eventId: string }): Promise<void> {\n // Web uploads run in-process; events are not persisted for replay.\n }\n\n async getPluginVersion(): Promise<{ version: string }> {\n return { version: 'web' };\n }\n}\n"]}
|
package/dist/plugin.cjs.js
CHANGED
|
@@ -188,6 +188,9 @@ class UploaderWeb extends core.WebPlugin {
|
|
|
188
188
|
return null;
|
|
189
189
|
}
|
|
190
190
|
}
|
|
191
|
+
async acknowledgeEvent(_options) {
|
|
192
|
+
// Web uploads run in-process; events are not persisted for replay.
|
|
193
|
+
}
|
|
191
194
|
async getPluginVersion() {
|
|
192
195
|
return { version: 'web' };
|
|
193
196
|
}
|
package/dist/plugin.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.cjs.js","sources":["esm/index.js","esm/PathHelper.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst Uploader = registerPlugin('Uploader', {\n web: () => import('./web').then((m) => new m.UploaderWeb()),\n});\nexport * from './definitions';\nexport { Uploader };\n//# sourceMappingURL=index.js.map","export class PathHelper {\n // Check if the path follows the idb://[databaseName]/[storeName]/[key] format\n static isIndexedDBPath(path) {\n const regex = /^idb:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/;\n return regex.test(path);\n }\n // Parse the path to extract database, storeName, and key\n static parseIndexedDBPath(path) {\n const regex = /^idb:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/;\n const match = path.match(regex);\n if (!match) {\n throw new Error('Invalid IndexedDB path format');\n }\n return {\n database: match[1],\n storeName: match[2],\n key: match[3],\n };\n }\n}\n//# sourceMappingURL=PathHelper.js.map","import { WebPlugin } from '@capacitor/core';\nimport { openDB } from 'idb';\nimport { PathHelper } from './PathHelper';\nexport class UploaderWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.uploads = new Map();\n }\n async startUpload(options) {\n console.log('startUpload', options);\n const id = Math.random().toString(36).substring(2, 15);\n const controller = new AbortController();\n const maxRetries = options.maxRetries || 3;\n this.uploads.set(id, { controller, retries: maxRetries });\n this.doUpload(id, options);\n return { id };\n }\n async removeUpload(options) {\n console.log('removeUpload', options);\n const upload = this.uploads.get(options.id);\n if (upload) {\n upload.controller.abort();\n this.uploads.delete(options.id);\n this.notifyListeners('events', {\n name: 'cancelled',\n id: options.id,\n payload: {},\n });\n }\n }\n async doUpload(id, options) {\n var _a, _b, _c;\n const { serverUrl, headers = {}, method = 'POST', parameters = {} } = options;\n const upload = this.uploads.get(id);\n if (!upload)\n return;\n try {\n const files = this.normalizeFiles(options);\n if (files.length === 0)\n throw new Error('Missing required parameter: filePath or files');\n const resolvedMethod = method.toUpperCase();\n const uploadType = (_a = options.uploadType) !== null && _a !== void 0 ? _a : (resolvedMethod === 'PUT' ? 'binary' : 'multipart');\n let body;\n if (resolvedMethod === 'PUT' || uploadType === 'binary') {\n if (files.length !== 1)\n throw new Error('Binary uploads only support a single file');\n const file = await this.getFileFromPath(files[0].filePath);\n if (!file)\n throw new Error('File not found');\n body = file;\n }\n else {\n const formData = new FormData();\n for (const fileOption of files) {\n const file = await this.getFileFromPath(fileOption.filePath);\n if (!file)\n throw new Error('File not found');\n const fieldName = (_c = (_b = fileOption.fieldName) !== null && _b !== void 0 ? _b : options.fileField) !== null && _c !== void 0 ? _c : 'file';\n formData.append(fieldName, file);\n }\n for (const [key, value] of Object.entries(parameters)) {\n formData.append(key, value);\n }\n body = formData;\n }\n const response = await fetch(serverUrl, {\n method: resolvedMethod,\n headers,\n body,\n signal: upload.controller.signal,\n });\n if (!response.ok)\n throw new Error(`HTTP error! status: ${response.status}`);\n this.notifyListeners('events', {\n name: 'completed',\n id,\n payload: { statusCode: response.status },\n });\n this.uploads.delete(id);\n }\n catch (error) {\n if (error.name === 'AbortError')\n return;\n if (upload.retries > 0) {\n upload.retries--;\n console.log(`Retrying upload (retries left: ${upload.retries})`);\n setTimeout(() => this.doUpload(id, options), 1000);\n }\n else {\n this.notifyListeners('events', {\n name: 'failed',\n id,\n payload: { error: error.message },\n });\n this.uploads.delete(id);\n }\n }\n }\n normalizeFiles(options) {\n if (options.files && options.files.length > 0)\n return options.files;\n if (options.filePath) {\n return [\n {\n filePath: options.filePath,\n fieldName: options.fileField,\n mimeType: options.mimeType,\n },\n ];\n }\n return [];\n }\n async getFileFromPath(filePath) {\n // Check if the path is an IndexedDB path\n if (PathHelper.isIndexedDBPath(filePath)) {\n return this.getFileFromIndexedDB(filePath);\n }\n // Otherwise, treat it as a file path from the system\n return this.getFileFromSystem(filePath);\n }\n // Retrieve the file from IndexedDB\n async getFileFromIndexedDB(filePath) {\n // Parse the path to get the database, store name, and key\n const { database, storeName, key } = PathHelper.parseIndexedDBPath(filePath);\n try {\n // Open the IndexedDB database and access the object store\n const db = await openDB(database, 1, {\n upgrade(db) {\n if (!db.objectStoreNames.contains(storeName)) {\n db.createObjectStore(storeName);\n }\n },\n });\n // Get the blob from the store\n const blob = await db.get(storeName, key);\n if (!blob) {\n console.error(`File with key \"${key}\" not found in store \"${storeName}\" in database \"${database}\"`);\n return null;\n }\n // Convert the Blob to a File object\n return new File([blob], key, { type: blob.type });\n }\n catch (error) {\n console.error('Error retrieving file from IndexedDB:', error);\n return null;\n }\n }\n // Retrieve the file from the system (local file)\n async getFileFromSystem(filePath) {\n try {\n // This is a simplified version. In a real-world scenario,\n // you might need to handle different types of paths or use a file system API.\n const response = await fetch(filePath);\n const blob = await response.blob();\n return new File([blob], filePath.split('/').pop() || 'file', {\n type: blob.type,\n });\n }\n catch (error) {\n console.error('Error getting file from system:', error);\n return null;\n }\n }\n async getPluginVersion() {\n return { version: 'web' };\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin","openDB"],"mappings":";;;;;AACK,MAAC,QAAQ,GAAGA,mBAAc,CAAC,UAAU,EAAE;AAC5C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;AAC/D,CAAC;;ACHM,MAAM,UAAU,CAAC;AACxB;AACA,IAAI,OAAO,eAAe,CAAC,IAAI,EAAE;AACjC,QAAQ,MAAM,KAAK,GAAG,kCAAkC;AACxD,QAAQ,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;AAC/B,IAAI;AACJ;AACA,IAAI,OAAO,kBAAkB,CAAC,IAAI,EAAE;AACpC,QAAQ,MAAM,KAAK,GAAG,kCAAkC;AACxD,QAAQ,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;AACvC,QAAQ,IAAI,CAAC,KAAK,EAAE;AACpB,YAAY,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m/index.js","esm/PathHelper.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst Uploader = registerPlugin('Uploader', {\n web: () => import('./web').then((m) => new m.UploaderWeb()),\n});\nexport * from './definitions';\nexport { Uploader };\n//# sourceMappingURL=index.js.map","export class PathHelper {\n // Check if the path follows the idb://[databaseName]/[storeName]/[key] format\n static isIndexedDBPath(path) {\n const regex = /^idb:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/;\n return regex.test(path);\n }\n // Parse the path to extract database, storeName, and key\n static parseIndexedDBPath(path) {\n const regex = /^idb:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/;\n const match = path.match(regex);\n if (!match) {\n throw new Error('Invalid IndexedDB path format');\n }\n return {\n database: match[1],\n storeName: match[2],\n key: match[3],\n };\n }\n}\n//# sourceMappingURL=PathHelper.js.map","import { WebPlugin } from '@capacitor/core';\nimport { openDB } from 'idb';\nimport { PathHelper } from './PathHelper';\nexport class UploaderWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.uploads = new Map();\n }\n async startUpload(options) {\n console.log('startUpload', options);\n const id = Math.random().toString(36).substring(2, 15);\n const controller = new AbortController();\n const maxRetries = options.maxRetries || 3;\n this.uploads.set(id, { controller, retries: maxRetries });\n this.doUpload(id, options);\n return { id };\n }\n async removeUpload(options) {\n console.log('removeUpload', options);\n const upload = this.uploads.get(options.id);\n if (upload) {\n upload.controller.abort();\n this.uploads.delete(options.id);\n this.notifyListeners('events', {\n name: 'cancelled',\n id: options.id,\n payload: {},\n });\n }\n }\n async doUpload(id, options) {\n var _a, _b, _c;\n const { serverUrl, headers = {}, method = 'POST', parameters = {} } = options;\n const upload = this.uploads.get(id);\n if (!upload)\n return;\n try {\n const files = this.normalizeFiles(options);\n if (files.length === 0)\n throw new Error('Missing required parameter: filePath or files');\n const resolvedMethod = method.toUpperCase();\n const uploadType = (_a = options.uploadType) !== null && _a !== void 0 ? _a : (resolvedMethod === 'PUT' ? 'binary' : 'multipart');\n let body;\n if (resolvedMethod === 'PUT' || uploadType === 'binary') {\n if (files.length !== 1)\n throw new Error('Binary uploads only support a single file');\n const file = await this.getFileFromPath(files[0].filePath);\n if (!file)\n throw new Error('File not found');\n body = file;\n }\n else {\n const formData = new FormData();\n for (const fileOption of files) {\n const file = await this.getFileFromPath(fileOption.filePath);\n if (!file)\n throw new Error('File not found');\n const fieldName = (_c = (_b = fileOption.fieldName) !== null && _b !== void 0 ? _b : options.fileField) !== null && _c !== void 0 ? _c : 'file';\n formData.append(fieldName, file);\n }\n for (const [key, value] of Object.entries(parameters)) {\n formData.append(key, value);\n }\n body = formData;\n }\n const response = await fetch(serverUrl, {\n method: resolvedMethod,\n headers,\n body,\n signal: upload.controller.signal,\n });\n if (!response.ok)\n throw new Error(`HTTP error! status: ${response.status}`);\n this.notifyListeners('events', {\n name: 'completed',\n id,\n payload: { statusCode: response.status },\n });\n this.uploads.delete(id);\n }\n catch (error) {\n if (error.name === 'AbortError')\n return;\n if (upload.retries > 0) {\n upload.retries--;\n console.log(`Retrying upload (retries left: ${upload.retries})`);\n setTimeout(() => this.doUpload(id, options), 1000);\n }\n else {\n this.notifyListeners('events', {\n name: 'failed',\n id,\n payload: { error: error.message },\n });\n this.uploads.delete(id);\n }\n }\n }\n normalizeFiles(options) {\n if (options.files && options.files.length > 0)\n return options.files;\n if (options.filePath) {\n return [\n {\n filePath: options.filePath,\n fieldName: options.fileField,\n mimeType: options.mimeType,\n },\n ];\n }\n return [];\n }\n async getFileFromPath(filePath) {\n // Check if the path is an IndexedDB path\n if (PathHelper.isIndexedDBPath(filePath)) {\n return this.getFileFromIndexedDB(filePath);\n }\n // Otherwise, treat it as a file path from the system\n return this.getFileFromSystem(filePath);\n }\n // Retrieve the file from IndexedDB\n async getFileFromIndexedDB(filePath) {\n // Parse the path to get the database, store name, and key\n const { database, storeName, key } = PathHelper.parseIndexedDBPath(filePath);\n try {\n // Open the IndexedDB database and access the object store\n const db = await openDB(database, 1, {\n upgrade(db) {\n if (!db.objectStoreNames.contains(storeName)) {\n db.createObjectStore(storeName);\n }\n },\n });\n // Get the blob from the store\n const blob = await db.get(storeName, key);\n if (!blob) {\n console.error(`File with key \"${key}\" not found in store \"${storeName}\" in database \"${database}\"`);\n return null;\n }\n // Convert the Blob to a File object\n return new File([blob], key, { type: blob.type });\n }\n catch (error) {\n console.error('Error retrieving file from IndexedDB:', error);\n return null;\n }\n }\n // Retrieve the file from the system (local file)\n async getFileFromSystem(filePath) {\n try {\n // This is a simplified version. In a real-world scenario,\n // you might need to handle different types of paths or use a file system API.\n const response = await fetch(filePath);\n const blob = await response.blob();\n return new File([blob], filePath.split('/').pop() || 'file', {\n type: blob.type,\n });\n }\n catch (error) {\n console.error('Error getting file from system:', error);\n return null;\n }\n }\n async acknowledgeEvent(_options) {\n // Web uploads run in-process; events are not persisted for replay.\n }\n async getPluginVersion() {\n return { version: 'web' };\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin","openDB"],"mappings":";;;;;AACK,MAAC,QAAQ,GAAGA,mBAAc,CAAC,UAAU,EAAE;AAC5C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;AAC/D,CAAC;;ACHM,MAAM,UAAU,CAAC;AACxB;AACA,IAAI,OAAO,eAAe,CAAC,IAAI,EAAE;AACjC,QAAQ,MAAM,KAAK,GAAG,kCAAkC;AACxD,QAAQ,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;AAC/B,IAAI;AACJ;AACA,IAAI,OAAO,kBAAkB,CAAC,IAAI,EAAE;AACpC,QAAQ,MAAM,KAAK,GAAG,kCAAkC;AACxD,QAAQ,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;AACvC,QAAQ,IAAI,CAAC,KAAK,EAAE;AACpB,YAAY,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC;AAC5D,QAA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-186,6 +186,9 @@ var capacitorCapacitorUpdater = (function (exports, core, idb) {
|
|
|
186
186
|
return null;
|
|
187
187
|
}
|
|
188
188
|
}
|
|
189
|
+
async acknowledgeEvent(_options) {
|
|
190
|
+
// Web uploads run in-process; events are not persisted for replay.
|
|
191
|
+
}
|
|
189
192
|
async getPluginVersion() {
|
|
190
193
|
return { version: 'web' };
|
|
191
194
|
}
|
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","sources":["esm/index.js","esm/PathHelper.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst Uploader = registerPlugin('Uploader', {\n web: () => import('./web').then((m) => new m.UploaderWeb()),\n});\nexport * from './definitions';\nexport { Uploader };\n//# sourceMappingURL=index.js.map","export class PathHelper {\n // Check if the path follows the idb://[databaseName]/[storeName]/[key] format\n static isIndexedDBPath(path) {\n const regex = /^idb:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/;\n return regex.test(path);\n }\n // Parse the path to extract database, storeName, and key\n static parseIndexedDBPath(path) {\n const regex = /^idb:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/;\n const match = path.match(regex);\n if (!match) {\n throw new Error('Invalid IndexedDB path format');\n }\n return {\n database: match[1],\n storeName: match[2],\n key: match[3],\n };\n }\n}\n//# sourceMappingURL=PathHelper.js.map","import { WebPlugin } from '@capacitor/core';\nimport { openDB } from 'idb';\nimport { PathHelper } from './PathHelper';\nexport class UploaderWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.uploads = new Map();\n }\n async startUpload(options) {\n console.log('startUpload', options);\n const id = Math.random().toString(36).substring(2, 15);\n const controller = new AbortController();\n const maxRetries = options.maxRetries || 3;\n this.uploads.set(id, { controller, retries: maxRetries });\n this.doUpload(id, options);\n return { id };\n }\n async removeUpload(options) {\n console.log('removeUpload', options);\n const upload = this.uploads.get(options.id);\n if (upload) {\n upload.controller.abort();\n this.uploads.delete(options.id);\n this.notifyListeners('events', {\n name: 'cancelled',\n id: options.id,\n payload: {},\n });\n }\n }\n async doUpload(id, options) {\n var _a, _b, _c;\n const { serverUrl, headers = {}, method = 'POST', parameters = {} } = options;\n const upload = this.uploads.get(id);\n if (!upload)\n return;\n try {\n const files = this.normalizeFiles(options);\n if (files.length === 0)\n throw new Error('Missing required parameter: filePath or files');\n const resolvedMethod = method.toUpperCase();\n const uploadType = (_a = options.uploadType) !== null && _a !== void 0 ? _a : (resolvedMethod === 'PUT' ? 'binary' : 'multipart');\n let body;\n if (resolvedMethod === 'PUT' || uploadType === 'binary') {\n if (files.length !== 1)\n throw new Error('Binary uploads only support a single file');\n const file = await this.getFileFromPath(files[0].filePath);\n if (!file)\n throw new Error('File not found');\n body = file;\n }\n else {\n const formData = new FormData();\n for (const fileOption of files) {\n const file = await this.getFileFromPath(fileOption.filePath);\n if (!file)\n throw new Error('File not found');\n const fieldName = (_c = (_b = fileOption.fieldName) !== null && _b !== void 0 ? _b : options.fileField) !== null && _c !== void 0 ? _c : 'file';\n formData.append(fieldName, file);\n }\n for (const [key, value] of Object.entries(parameters)) {\n formData.append(key, value);\n }\n body = formData;\n }\n const response = await fetch(serverUrl, {\n method: resolvedMethod,\n headers,\n body,\n signal: upload.controller.signal,\n });\n if (!response.ok)\n throw new Error(`HTTP error! status: ${response.status}`);\n this.notifyListeners('events', {\n name: 'completed',\n id,\n payload: { statusCode: response.status },\n });\n this.uploads.delete(id);\n }\n catch (error) {\n if (error.name === 'AbortError')\n return;\n if (upload.retries > 0) {\n upload.retries--;\n console.log(`Retrying upload (retries left: ${upload.retries})`);\n setTimeout(() => this.doUpload(id, options), 1000);\n }\n else {\n this.notifyListeners('events', {\n name: 'failed',\n id,\n payload: { error: error.message },\n });\n this.uploads.delete(id);\n }\n }\n }\n normalizeFiles(options) {\n if (options.files && options.files.length > 0)\n return options.files;\n if (options.filePath) {\n return [\n {\n filePath: options.filePath,\n fieldName: options.fileField,\n mimeType: options.mimeType,\n },\n ];\n }\n return [];\n }\n async getFileFromPath(filePath) {\n // Check if the path is an IndexedDB path\n if (PathHelper.isIndexedDBPath(filePath)) {\n return this.getFileFromIndexedDB(filePath);\n }\n // Otherwise, treat it as a file path from the system\n return this.getFileFromSystem(filePath);\n }\n // Retrieve the file from IndexedDB\n async getFileFromIndexedDB(filePath) {\n // Parse the path to get the database, store name, and key\n const { database, storeName, key } = PathHelper.parseIndexedDBPath(filePath);\n try {\n // Open the IndexedDB database and access the object store\n const db = await openDB(database, 1, {\n upgrade(db) {\n if (!db.objectStoreNames.contains(storeName)) {\n db.createObjectStore(storeName);\n }\n },\n });\n // Get the blob from the store\n const blob = await db.get(storeName, key);\n if (!blob) {\n console.error(`File with key \"${key}\" not found in store \"${storeName}\" in database \"${database}\"`);\n return null;\n }\n // Convert the Blob to a File object\n return new File([blob], key, { type: blob.type });\n }\n catch (error) {\n console.error('Error retrieving file from IndexedDB:', error);\n return null;\n }\n }\n // Retrieve the file from the system (local file)\n async getFileFromSystem(filePath) {\n try {\n // This is a simplified version. In a real-world scenario,\n // you might need to handle different types of paths or use a file system API.\n const response = await fetch(filePath);\n const blob = await response.blob();\n return new File([blob], filePath.split('/').pop() || 'file', {\n type: blob.type,\n });\n }\n catch (error) {\n console.error('Error getting file from system:', error);\n return null;\n }\n }\n async getPluginVersion() {\n return { version: 'web' };\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin","openDB"],"mappings":";;;AACK,UAAC,QAAQ,GAAGA,mBAAc,CAAC,UAAU,EAAE;IAC5C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;IAC/D,CAAC;;ICHM,MAAM,UAAU,CAAC;IACxB;IACA,IAAI,OAAO,eAAe,CAAC,IAAI,EAAE;IACjC,QAAQ,MAAM,KAAK,GAAG,kCAAkC;IACxD,QAAQ,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,C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,EAAE,KAAK,CAAC;IACnE,YAAY,OAAO,IAAI;IACvB,QAAQ;IACR,IAAI;IACJ,IAAI,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE;IACjC,IAAI;IACJ;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"plugin.js","sources":["esm/index.js","esm/PathHelper.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst Uploader = registerPlugin('Uploader', {\n web: () => import('./web').then((m) => new m.UploaderWeb()),\n});\nexport * from './definitions';\nexport { Uploader };\n//# sourceMappingURL=index.js.map","export class PathHelper {\n // Check if the path follows the idb://[databaseName]/[storeName]/[key] format\n static isIndexedDBPath(path) {\n const regex = /^idb:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/;\n return regex.test(path);\n }\n // Parse the path to extract database, storeName, and key\n static parseIndexedDBPath(path) {\n const regex = /^idb:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/;\n const match = path.match(regex);\n if (!match) {\n throw new Error('Invalid IndexedDB path format');\n }\n return {\n database: match[1],\n storeName: match[2],\n key: match[3],\n };\n }\n}\n//# sourceMappingURL=PathHelper.js.map","import { WebPlugin } from '@capacitor/core';\nimport { openDB } from 'idb';\nimport { PathHelper } from './PathHelper';\nexport class UploaderWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.uploads = new Map();\n }\n async startUpload(options) {\n console.log('startUpload', options);\n const id = Math.random().toString(36).substring(2, 15);\n const controller = new AbortController();\n const maxRetries = options.maxRetries || 3;\n this.uploads.set(id, { controller, retries: maxRetries });\n this.doUpload(id, options);\n return { id };\n }\n async removeUpload(options) {\n console.log('removeUpload', options);\n const upload = this.uploads.get(options.id);\n if (upload) {\n upload.controller.abort();\n this.uploads.delete(options.id);\n this.notifyListeners('events', {\n name: 'cancelled',\n id: options.id,\n payload: {},\n });\n }\n }\n async doUpload(id, options) {\n var _a, _b, _c;\n const { serverUrl, headers = {}, method = 'POST', parameters = {} } = options;\n const upload = this.uploads.get(id);\n if (!upload)\n return;\n try {\n const files = this.normalizeFiles(options);\n if (files.length === 0)\n throw new Error('Missing required parameter: filePath or files');\n const resolvedMethod = method.toUpperCase();\n const uploadType = (_a = options.uploadType) !== null && _a !== void 0 ? _a : (resolvedMethod === 'PUT' ? 'binary' : 'multipart');\n let body;\n if (resolvedMethod === 'PUT' || uploadType === 'binary') {\n if (files.length !== 1)\n throw new Error('Binary uploads only support a single file');\n const file = await this.getFileFromPath(files[0].filePath);\n if (!file)\n throw new Error('File not found');\n body = file;\n }\n else {\n const formData = new FormData();\n for (const fileOption of files) {\n const file = await this.getFileFromPath(fileOption.filePath);\n if (!file)\n throw new Error('File not found');\n const fieldName = (_c = (_b = fileOption.fieldName) !== null && _b !== void 0 ? _b : options.fileField) !== null && _c !== void 0 ? _c : 'file';\n formData.append(fieldName, file);\n }\n for (const [key, value] of Object.entries(parameters)) {\n formData.append(key, value);\n }\n body = formData;\n }\n const response = await fetch(serverUrl, {\n method: resolvedMethod,\n headers,\n body,\n signal: upload.controller.signal,\n });\n if (!response.ok)\n throw new Error(`HTTP error! status: ${response.status}`);\n this.notifyListeners('events', {\n name: 'completed',\n id,\n payload: { statusCode: response.status },\n });\n this.uploads.delete(id);\n }\n catch (error) {\n if (error.name === 'AbortError')\n return;\n if (upload.retries > 0) {\n upload.retries--;\n console.log(`Retrying upload (retries left: ${upload.retries})`);\n setTimeout(() => this.doUpload(id, options), 1000);\n }\n else {\n this.notifyListeners('events', {\n name: 'failed',\n id,\n payload: { error: error.message },\n });\n this.uploads.delete(id);\n }\n }\n }\n normalizeFiles(options) {\n if (options.files && options.files.length > 0)\n return options.files;\n if (options.filePath) {\n return [\n {\n filePath: options.filePath,\n fieldName: options.fileField,\n mimeType: options.mimeType,\n },\n ];\n }\n return [];\n }\n async getFileFromPath(filePath) {\n // Check if the path is an IndexedDB path\n if (PathHelper.isIndexedDBPath(filePath)) {\n return this.getFileFromIndexedDB(filePath);\n }\n // Otherwise, treat it as a file path from the system\n return this.getFileFromSystem(filePath);\n }\n // Retrieve the file from IndexedDB\n async getFileFromIndexedDB(filePath) {\n // Parse the path to get the database, store name, and key\n const { database, storeName, key } = PathHelper.parseIndexedDBPath(filePath);\n try {\n // Open the IndexedDB database and access the object store\n const db = await openDB(database, 1, {\n upgrade(db) {\n if (!db.objectStoreNames.contains(storeName)) {\n db.createObjectStore(storeName);\n }\n },\n });\n // Get the blob from the store\n const blob = await db.get(storeName, key);\n if (!blob) {\n console.error(`File with key \"${key}\" not found in store \"${storeName}\" in database \"${database}\"`);\n return null;\n }\n // Convert the Blob to a File object\n return new File([blob], key, { type: blob.type });\n }\n catch (error) {\n console.error('Error retrieving file from IndexedDB:', error);\n return null;\n }\n }\n // Retrieve the file from the system (local file)\n async getFileFromSystem(filePath) {\n try {\n // This is a simplified version. In a real-world scenario,\n // you might need to handle different types of paths or use a file system API.\n const response = await fetch(filePath);\n const blob = await response.blob();\n return new File([blob], filePath.split('/').pop() || 'file', {\n type: blob.type,\n });\n }\n catch (error) {\n console.error('Error getting file from system:', error);\n return null;\n }\n }\n async acknowledgeEvent(_options) {\n // Web uploads run in-process; events are not persisted for replay.\n }\n async getPluginVersion() {\n return { version: 'web' };\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin","openDB"],"mappings":";;;AACK,UAAC,QAAQ,GAAGA,mBAAc,CAAC,UAAU,EAAE;IAC5C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;IAC/D,CAAC;;ICHM,MAAM,UAAU,CAAC;IACxB;IACA,IAAI,OAAO,eAAe,CAAC,IAAI,EAAE;IACjC,QAAQ,MAAM,KAAK,GAAG,kCAAkC;IACxD,QAAQ,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;IAC/B,IAAI;IACJ;IACA,IAAI,OAAO,kBAAkB,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QAAQ;IACR,IAAI;IACJ,IAAI,MAAM,gBAAgB,CAAC,QAAQ,EAAE;IACrC;IACA,IAAI;IACJ,IAAI,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE;IACjC,IAAI;IACJ;;;;;;;;;;;;;;;"}
|
|
@@ -3,13 +3,14 @@ import Capacitor
|
|
|
3
3
|
|
|
4
4
|
@objc(UploaderPlugin)
|
|
5
5
|
public class UploaderPlugin: CAPPlugin, CAPBridgedPlugin {
|
|
6
|
-
private let pluginVersion: String = "8.
|
|
6
|
+
private let pluginVersion: String = "8.3.0"
|
|
7
7
|
public let identifier = "UploaderPlugin"
|
|
8
8
|
public let jsName = "Uploader"
|
|
9
9
|
public let pluginMethods: [CAPPluginMethod] = [
|
|
10
10
|
CAPPluginMethod(name: "startUpload", returnType: CAPPluginReturnPromise),
|
|
11
11
|
CAPPluginMethod(name: "removeUpload", returnType: CAPPluginReturnPromise),
|
|
12
|
-
CAPPluginMethod(name: "getPluginVersion", returnType: CAPPluginReturnPromise)
|
|
12
|
+
CAPPluginMethod(name: "getPluginVersion", returnType: CAPPluginReturnPromise),
|
|
13
|
+
CAPPluginMethod(name: "acknowledgeEvent", returnType: CAPPluginReturnPromise)
|
|
13
14
|
]
|
|
14
15
|
private let implementation = Uploader()
|
|
15
16
|
|
|
@@ -68,6 +69,14 @@ public class UploaderPlugin: CAPPlugin, CAPBridgedPlugin {
|
|
|
68
69
|
}
|
|
69
70
|
}
|
|
70
71
|
|
|
72
|
+
@objc func acknowledgeEvent(_ call: CAPPluginCall) {
|
|
73
|
+
guard let eventId = call.getString("eventId"), !eventId.isEmpty else {
|
|
74
|
+
call.reject("Missing required parameter: eventId")
|
|
75
|
+
return
|
|
76
|
+
}
|
|
77
|
+
call.resolve()
|
|
78
|
+
}
|
|
79
|
+
|
|
71
80
|
@objc func removeUpload(_ call: CAPPluginCall) {
|
|
72
81
|
guard let id = call.getString("id") else {
|
|
73
82
|
call.reject("Missing required parameter: id")
|