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.
- package/CapacitorBackgroundTransfer.podspec +19 -0
- package/LICENSE +21 -0
- package/Package.swift +31 -0
- package/README.md +542 -2
- package/android/build.gradle +71 -0
- package/android/src/main/AndroidManifest.xml +20 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/AzureBlockUploader.java +148 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/BackgroundTransferPlugin.java +279 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Downloader.java +244 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Http.java +238 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/JobRuns.java +40 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Notifications.java +54 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Parts.java +25 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/PartsXml.java +199 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Pause.java +28 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Progress.java +13 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/PutUploader.java +47 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Runner.java +369 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/S3MultipartUploader.java +143 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Scheduler.java +144 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferException.java +65 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferJobService.java +115 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferPaths.java +129 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferRecord.java +163 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferStore.java +121 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/TransferWorker.java +85 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadAdapter.java +11 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadAdapters.java +89 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/UploadOptionsCheck.java +104 -0
- package/android/src/main/java/io/github/sandman92/backgroundtransfer/Uploader.java +225 -0
- package/android/src/main/res/.gitkeep +0 -0
- package/dist/docs.json +527 -0
- package/dist/esm/definitions.d.ts +277 -0
- package/dist/esm/definitions.js +24 -0
- package/dist/esm/definitions.js.map +1 -0
- package/dist/esm/index.d.ts +10 -0
- package/dist/esm/index.js +26 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/validate.d.ts +18 -0
- package/dist/esm/validate.js +113 -0
- package/dist/esm/validate.js.map +1 -0
- package/dist/esm/web.d.ts +17 -0
- package/dist/esm/web.js +27 -0
- package/dist/esm/web.js.map +1 -0
- package/dist/plugin.cjs.js +200 -0
- package/dist/plugin.cjs.js.map +1 -0
- package/dist/plugin.js +203 -0
- package/dist/plugin.js.map +1 -0
- package/ios/Sources/BackgroundTransferCore/Files.swift +166 -0
- package/ios/Sources/BackgroundTransferCore/PartsUpload.swift +327 -0
- package/ios/Sources/BackgroundTransferCore/PartsXML.swift +137 -0
- package/ios/Sources/BackgroundTransferCore/TransferPaths.swift +103 -0
- package/ios/Sources/BackgroundTransferCore/TransferRecord.swift +141 -0
- package/ios/Sources/BackgroundTransferCore/TransferStore.swift +69 -0
- package/ios/Sources/BackgroundTransferCore/UploadOptionsCheck.swift +90 -0
- package/ios/Sources/BackgroundTransferCore/UploadOutcome.swift +96 -0
- package/ios/Sources/BackgroundTransferCore/UploadProtocol.swift +30 -0
- package/ios/Sources/BackgroundTransferPlugin/BackgroundTransferPlugin.swift +168 -0
- package/ios/Sources/BackgroundTransferPlugin/TransferManager.swift +1074 -0
- package/package.json +96 -4
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var core = require('@capacitor/core');
|
|
4
|
+
|
|
5
|
+
/** The protocols this version knows. */
|
|
6
|
+
const UPLOAD_PROTOCOLS = [
|
|
7
|
+
'firebase-resumable',
|
|
8
|
+
'put',
|
|
9
|
+
's3-multipart',
|
|
10
|
+
'azure-blocks',
|
|
11
|
+
];
|
|
12
|
+
const MIB = 1024 * 1024;
|
|
13
|
+
/** The limits the plugin checks for `s3-multipart` and `azure-blocks`. */
|
|
14
|
+
const UPLOAD_LIMITS = {
|
|
15
|
+
/** Default `partSize` and `blockSize`: 8 MiB. */
|
|
16
|
+
defaultPartSize: 8 * MIB,
|
|
17
|
+
/** S3's smallest part, other than the last: 5 MiB. */
|
|
18
|
+
s3MinPartSize: 5 * MIB,
|
|
19
|
+
/** S3's largest part: 5 GiB. */
|
|
20
|
+
s3MaxPartSize: 5 * 1024 * MIB,
|
|
21
|
+
/** S3's most parts in one upload. */
|
|
22
|
+
s3MaxParts: 10000,
|
|
23
|
+
/** Azure's largest block: 4000 MiB. */
|
|
24
|
+
azureMaxBlockSize: 4000 * MIB,
|
|
25
|
+
/** Azure's most blocks in one blob. */
|
|
26
|
+
azureMaxBlocks: 50000,
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const HTTP_URL = /^https?:\/\/[^/]+/i;
|
|
30
|
+
// A line break or any other control character in a header name or value.
|
|
31
|
+
// eslint-disable-next-line no-control-regex
|
|
32
|
+
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
33
|
+
/**
|
|
34
|
+
* Checks a transfer's options before they cross to the native side, so both
|
|
35
|
+
* platforms refuse the same mistakes with the same words. Returns the
|
|
36
|
+
* options with `path` as a plain absolute path. The native sides repeat these
|
|
37
|
+
* checks (a script can call the plugin directly), and also confine `path` to
|
|
38
|
+
* the app's own directories, which only they know.
|
|
39
|
+
*/
|
|
40
|
+
function checkTransferOptions(options) {
|
|
41
|
+
if (!options || typeof options !== 'object')
|
|
42
|
+
throw new Error('options are required');
|
|
43
|
+
const { id, url, path, headers } = options;
|
|
44
|
+
if (typeof id !== 'string' || id.trim() === '')
|
|
45
|
+
throw new Error('id is required');
|
|
46
|
+
if (typeof url !== 'string' || !HTTP_URL.test(url))
|
|
47
|
+
throw new Error('url must be an http or https URL');
|
|
48
|
+
const plain = toPlainPath(path);
|
|
49
|
+
if (headers !== undefined) {
|
|
50
|
+
if (headers === null || typeof headers !== 'object' || Array.isArray(headers)) {
|
|
51
|
+
throw new Error('headers must be an object of strings');
|
|
52
|
+
}
|
|
53
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
54
|
+
if (typeof value !== 'string')
|
|
55
|
+
throw new Error(`header ${name} must be a string`);
|
|
56
|
+
if (name === '' || CONTROL.test(name) || CONTROL.test(value))
|
|
57
|
+
throw new Error(`header ${name} must be one line`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return Object.assign(Object.assign({}, options), { path: plain });
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Checks an upload's options as `checkTransferOptions` does, its `protocol`
|
|
64
|
+
* (`firebase-resumable` when omitted, refused when unknown) and the options
|
|
65
|
+
* that go with it. The native sides check the same things, and also that
|
|
66
|
+
* `partUrls` fits the file's size, which only they can read.
|
|
67
|
+
*/
|
|
68
|
+
function checkUploadOptions(options) {
|
|
69
|
+
var _a;
|
|
70
|
+
const checked = checkTransferOptions(options);
|
|
71
|
+
const protocol = (_a = checked.protocol) !== null && _a !== void 0 ? _a : 'firebase-resumable';
|
|
72
|
+
if (!UPLOAD_PROTOCOLS.includes(protocol)) {
|
|
73
|
+
throw new Error(`protocol must be one of ${UPLOAD_PROTOCOLS.join(', ')}`);
|
|
74
|
+
}
|
|
75
|
+
const { partUrls, partSize, listPartsUrl, blockSize } = checked;
|
|
76
|
+
if (protocol !== 's3-multipart' && (partUrls !== undefined || partSize !== undefined || listPartsUrl !== undefined)) {
|
|
77
|
+
throw new Error('partUrls, partSize and listPartsUrl are only for s3-multipart');
|
|
78
|
+
}
|
|
79
|
+
if (protocol !== 'azure-blocks' && blockSize !== undefined) {
|
|
80
|
+
throw new Error('blockSize is only for azure-blocks');
|
|
81
|
+
}
|
|
82
|
+
if (protocol === 's3-multipart') {
|
|
83
|
+
if (!Array.isArray(partUrls) || partUrls.length === 0)
|
|
84
|
+
throw new Error('partUrls is required for s3-multipart');
|
|
85
|
+
if (partUrls.length > UPLOAD_LIMITS.s3MaxParts) {
|
|
86
|
+
throw new Error(`partUrls holds more than ${UPLOAD_LIMITS.s3MaxParts} parts`);
|
|
87
|
+
}
|
|
88
|
+
if (!partUrls.every((u) => typeof u === 'string' && HTTP_URL.test(u))) {
|
|
89
|
+
throw new Error('partUrls must be http or https URLs');
|
|
90
|
+
}
|
|
91
|
+
const size = partSize !== null && partSize !== void 0 ? partSize : UPLOAD_LIMITS.defaultPartSize;
|
|
92
|
+
if (!Number.isSafeInteger(size) || size < 1 || size > UPLOAD_LIMITS.s3MaxPartSize) {
|
|
93
|
+
throw new Error('partSize must be a whole number of bytes up to 5 GiB');
|
|
94
|
+
}
|
|
95
|
+
if (partUrls.length > 1 && size < UPLOAD_LIMITS.s3MinPartSize) {
|
|
96
|
+
throw new Error('partSize must be at least 5 MiB when there is more than one part');
|
|
97
|
+
}
|
|
98
|
+
if (listPartsUrl !== undefined && (typeof listPartsUrl !== 'string' || !HTTP_URL.test(listPartsUrl))) {
|
|
99
|
+
throw new Error('listPartsUrl must be an http or https URL');
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (protocol === 'azure-blocks') {
|
|
103
|
+
if (!isSasUrl(checked.url))
|
|
104
|
+
throw new Error('url must be a blob SAS URL (with a sig parameter)');
|
|
105
|
+
const size = blockSize !== null && blockSize !== void 0 ? blockSize : UPLOAD_LIMITS.defaultPartSize;
|
|
106
|
+
if (!Number.isSafeInteger(size) || size < 1 || size > UPLOAD_LIMITS.azureMaxBlockSize) {
|
|
107
|
+
throw new Error('blockSize must be a whole number of bytes up to 4000 MiB');
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return Object.assign(Object.assign({}, checked), { protocol });
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* A blob URL with a SAS token: a non-empty `sig` parameter, and no `comp` (the plugin adds its
|
|
114
|
+
* own). Parameter names are compared as written, as the native sides do.
|
|
115
|
+
*/
|
|
116
|
+
function isSasUrl(url) {
|
|
117
|
+
const query = url.split('#')[0].split('?')[1];
|
|
118
|
+
if (!query)
|
|
119
|
+
return false;
|
|
120
|
+
const params = query.split('&');
|
|
121
|
+
const names = params.map((p) => p.split('=')[0]);
|
|
122
|
+
return params.some((p) => p.startsWith('sig=') && p.length > 'sig='.length) && !names.includes('comp');
|
|
123
|
+
}
|
|
124
|
+
/** `file:///a/b%20c.mp4` → `/a/b c.mp4`; absolute paths pass through. */
|
|
125
|
+
function toPlainPath(path) {
|
|
126
|
+
if (typeof path !== 'string' || path === '')
|
|
127
|
+
throw new Error('path is required');
|
|
128
|
+
let plain = path;
|
|
129
|
+
if (plain.startsWith('file://')) {
|
|
130
|
+
plain = decodeURIComponent(plain.slice('file://'.length));
|
|
131
|
+
}
|
|
132
|
+
if (!plain.startsWith('/'))
|
|
133
|
+
throw new Error('path must be absolute or a file:// URI');
|
|
134
|
+
if (plain.endsWith('/'))
|
|
135
|
+
throw new Error('path must name a file');
|
|
136
|
+
if (plain.split('/').includes('..'))
|
|
137
|
+
throw new Error('path must not contain ..');
|
|
138
|
+
return plain;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const Native = core.registerPlugin('BackgroundTransfer', {
|
|
142
|
+
web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.BackgroundTransferWeb()),
|
|
143
|
+
});
|
|
144
|
+
/**
|
|
145
|
+
* The plugin, with `upload` and `download` options checked (and `file://`
|
|
146
|
+
* URIs turned into paths) before they reach the native side.
|
|
147
|
+
*/
|
|
148
|
+
const BackgroundTransfer = wrap(Native);
|
|
149
|
+
function wrap(plugin) {
|
|
150
|
+
return {
|
|
151
|
+
isAvailable: () => plugin.isAvailable(),
|
|
152
|
+
upload: async (options) => plugin.upload(checkUploadOptions(options)),
|
|
153
|
+
download: async (options) => plugin.download(checkTransferOptions(options)),
|
|
154
|
+
cancel: (options) => plugin.cancel(options),
|
|
155
|
+
list: () => plugin.list(),
|
|
156
|
+
forget: (options) => plugin.forget(options),
|
|
157
|
+
addListener: ((eventName, listener) => plugin.addListener(eventName, listener)),
|
|
158
|
+
removeAllListeners: () => plugin.removeAllListeners(),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The web has no background transfers: it says so, and every transfer call
|
|
164
|
+
* is refused with Capacitor's `UNAVAILABLE` code, so the app keeps its
|
|
165
|
+
* in-app path there.
|
|
166
|
+
*/
|
|
167
|
+
class BackgroundTransferWeb extends core.WebPlugin {
|
|
168
|
+
async isAvailable() {
|
|
169
|
+
return { available: false, mechanism: 'none' };
|
|
170
|
+
}
|
|
171
|
+
async upload() {
|
|
172
|
+
throw this.unavailable('Background transfers are not available on the web.');
|
|
173
|
+
}
|
|
174
|
+
async download() {
|
|
175
|
+
throw this.unavailable('Background transfers are not available on the web.');
|
|
176
|
+
}
|
|
177
|
+
async cancel() {
|
|
178
|
+
throw this.unavailable('Background transfers are not available on the web.');
|
|
179
|
+
}
|
|
180
|
+
async list() {
|
|
181
|
+
return { transfers: [] };
|
|
182
|
+
}
|
|
183
|
+
async forget() {
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
var web = /*#__PURE__*/Object.freeze({
|
|
189
|
+
__proto__: null,
|
|
190
|
+
BackgroundTransferWeb: BackgroundTransferWeb
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
exports.BackgroundTransfer = BackgroundTransfer;
|
|
194
|
+
exports.UPLOAD_LIMITS = UPLOAD_LIMITS;
|
|
195
|
+
exports.UPLOAD_PROTOCOLS = UPLOAD_PROTOCOLS;
|
|
196
|
+
exports.checkTransferOptions = checkTransferOptions;
|
|
197
|
+
exports.checkUploadOptions = checkUploadOptions;
|
|
198
|
+
exports.toPlainPath = toPlainPath;
|
|
199
|
+
exports.wrap = wrap;
|
|
200
|
+
//# sourceMappingURL=plugin.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.cjs.js","sources":["esm/definitions.js","esm/validate.js","esm/index.js","esm/web.js"],"sourcesContent":["/** The protocols this version knows. */\nexport const UPLOAD_PROTOCOLS = [\n 'firebase-resumable',\n 'put',\n 's3-multipart',\n 'azure-blocks',\n];\nconst MIB = 1024 * 1024;\n/** The limits the plugin checks for `s3-multipart` and `azure-blocks`. */\nexport const UPLOAD_LIMITS = {\n /** Default `partSize` and `blockSize`: 8 MiB. */\n defaultPartSize: 8 * MIB,\n /** S3's smallest part, other than the last: 5 MiB. */\n s3MinPartSize: 5 * MIB,\n /** S3's largest part: 5 GiB. */\n s3MaxPartSize: 5 * 1024 * MIB,\n /** S3's most parts in one upload. */\n s3MaxParts: 10000,\n /** Azure's largest block: 4000 MiB. */\n azureMaxBlockSize: 4000 * MIB,\n /** Azure's most blocks in one blob. */\n azureMaxBlocks: 50000,\n};\n//# sourceMappingURL=definitions.js.map","import { UPLOAD_LIMITS, UPLOAD_PROTOCOLS } from './definitions';\nconst HTTP_URL = /^https?:\\/\\/[^/]+/i;\n// A line break or any other control character in a header name or value.\n// eslint-disable-next-line no-control-regex\nconst CONTROL = /[\\u0000-\\u001f\\u007f]/;\n/**\n * Checks a transfer's options before they cross to the native side, so both\n * platforms refuse the same mistakes with the same words. Returns the\n * options with `path` as a plain absolute path. The native sides repeat these\n * checks (a script can call the plugin directly), and also confine `path` to\n * the app's own directories, which only they know.\n */\nexport function checkTransferOptions(options) {\n if (!options || typeof options !== 'object')\n throw new Error('options are required');\n const { id, url, path, headers } = options;\n if (typeof id !== 'string' || id.trim() === '')\n throw new Error('id is required');\n if (typeof url !== 'string' || !HTTP_URL.test(url))\n throw new Error('url must be an http or https URL');\n const plain = toPlainPath(path);\n if (headers !== undefined) {\n if (headers === null || typeof headers !== 'object' || Array.isArray(headers)) {\n throw new Error('headers must be an object of strings');\n }\n for (const [name, value] of Object.entries(headers)) {\n if (typeof value !== 'string')\n throw new Error(`header ${name} must be a string`);\n if (name === '' || CONTROL.test(name) || CONTROL.test(value))\n throw new Error(`header ${name} must be one line`);\n }\n }\n return Object.assign(Object.assign({}, options), { path: plain });\n}\n/**\n * Checks an upload's options as `checkTransferOptions` does, its `protocol`\n * (`firebase-resumable` when omitted, refused when unknown) and the options\n * that go with it. The native sides check the same things, and also that\n * `partUrls` fits the file's size, which only they can read.\n */\nexport function checkUploadOptions(options) {\n var _a;\n const checked = checkTransferOptions(options);\n const protocol = (_a = checked.protocol) !== null && _a !== void 0 ? _a : 'firebase-resumable';\n if (!UPLOAD_PROTOCOLS.includes(protocol)) {\n throw new Error(`protocol must be one of ${UPLOAD_PROTOCOLS.join(', ')}`);\n }\n const { partUrls, partSize, listPartsUrl, blockSize } = checked;\n if (protocol !== 's3-multipart' && (partUrls !== undefined || partSize !== undefined || listPartsUrl !== undefined)) {\n throw new Error('partUrls, partSize and listPartsUrl are only for s3-multipart');\n }\n if (protocol !== 'azure-blocks' && blockSize !== undefined) {\n throw new Error('blockSize is only for azure-blocks');\n }\n if (protocol === 's3-multipart') {\n if (!Array.isArray(partUrls) || partUrls.length === 0)\n throw new Error('partUrls is required for s3-multipart');\n if (partUrls.length > UPLOAD_LIMITS.s3MaxParts) {\n throw new Error(`partUrls holds more than ${UPLOAD_LIMITS.s3MaxParts} parts`);\n }\n if (!partUrls.every((u) => typeof u === 'string' && HTTP_URL.test(u))) {\n throw new Error('partUrls must be http or https URLs');\n }\n const size = partSize !== null && partSize !== void 0 ? partSize : UPLOAD_LIMITS.defaultPartSize;\n if (!Number.isSafeInteger(size) || size < 1 || size > UPLOAD_LIMITS.s3MaxPartSize) {\n throw new Error('partSize must be a whole number of bytes up to 5 GiB');\n }\n if (partUrls.length > 1 && size < UPLOAD_LIMITS.s3MinPartSize) {\n throw new Error('partSize must be at least 5 MiB when there is more than one part');\n }\n if (listPartsUrl !== undefined && (typeof listPartsUrl !== 'string' || !HTTP_URL.test(listPartsUrl))) {\n throw new Error('listPartsUrl must be an http or https URL');\n }\n }\n if (protocol === 'azure-blocks') {\n if (!isSasUrl(checked.url))\n throw new Error('url must be a blob SAS URL (with a sig parameter)');\n const size = blockSize !== null && blockSize !== void 0 ? blockSize : UPLOAD_LIMITS.defaultPartSize;\n if (!Number.isSafeInteger(size) || size < 1 || size > UPLOAD_LIMITS.azureMaxBlockSize) {\n throw new Error('blockSize must be a whole number of bytes up to 4000 MiB');\n }\n }\n return Object.assign(Object.assign({}, checked), { protocol });\n}\n/**\n * A blob URL with a SAS token: a non-empty `sig` parameter, and no `comp` (the plugin adds its\n * own). Parameter names are compared as written, as the native sides do.\n */\nfunction isSasUrl(url) {\n const query = url.split('#')[0].split('?')[1];\n if (!query)\n return false;\n const params = query.split('&');\n const names = params.map((p) => p.split('=')[0]);\n return params.some((p) => p.startsWith('sig=') && p.length > 'sig='.length) && !names.includes('comp');\n}\n/** `file:///a/b%20c.mp4` → `/a/b c.mp4`; absolute paths pass through. */\nexport function toPlainPath(path) {\n if (typeof path !== 'string' || path === '')\n throw new Error('path is required');\n let plain = path;\n if (plain.startsWith('file://')) {\n plain = decodeURIComponent(plain.slice('file://'.length));\n }\n if (!plain.startsWith('/'))\n throw new Error('path must be absolute or a file:// URI');\n if (plain.endsWith('/'))\n throw new Error('path must name a file');\n if (plain.split('/').includes('..'))\n throw new Error('path must not contain ..');\n return plain;\n}\n//# sourceMappingURL=validate.js.map","import { registerPlugin } from '@capacitor/core';\nimport { checkTransferOptions, checkUploadOptions } from './validate';\nconst Native = registerPlugin('BackgroundTransfer', {\n web: () => import('./web').then((m) => new m.BackgroundTransferWeb()),\n});\n/**\n * The plugin, with `upload` and `download` options checked (and `file://`\n * URIs turned into paths) before they reach the native side.\n */\nconst BackgroundTransfer = wrap(Native);\nexport function wrap(plugin) {\n return {\n isAvailable: () => plugin.isAvailable(),\n upload: async (options) => plugin.upload(checkUploadOptions(options)),\n download: async (options) => plugin.download(checkTransferOptions(options)),\n cancel: (options) => plugin.cancel(options),\n list: () => plugin.list(),\n forget: (options) => plugin.forget(options),\n addListener: ((eventName, listener) => plugin.addListener(eventName, listener)),\n removeAllListeners: () => plugin.removeAllListeners(),\n };\n}\nexport * from './definitions';\nexport { checkTransferOptions, checkUploadOptions, toPlainPath } from './validate';\nexport { BackgroundTransfer };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\n/**\n * The web has no background transfers: it says so, and every transfer call\n * is refused with Capacitor's `UNAVAILABLE` code, so the app keeps its\n * in-app path there.\n */\nexport class BackgroundTransferWeb extends WebPlugin {\n async isAvailable() {\n return { available: false, mechanism: 'none' };\n }\n async upload() {\n throw this.unavailable('Background transfers are not available on the web.');\n }\n async download() {\n throw this.unavailable('Background transfers are not available on the web.');\n }\n async cancel() {\n throw this.unavailable('Background transfers are not available on the web.');\n }\n async list() {\n return { transfers: [] };\n }\n async forget() {\n return;\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;;AAAA;AACY,MAAC,gBAAgB,GAAG;AAChC,IAAI,oBAAoB;AACxB,IAAI,KAAK;AACT,IAAI,cAAc;AAClB,IAAI,cAAc;AAClB;AACA,MAAM,GAAG,GAAG,IAAI,GAAG,IAAI;AACvB;AACY,MAAC,aAAa,GAAG;AAC7B;AACA,IAAI,eAAe,EAAE,CAAC,GAAG,GAAG;AAC5B;AACA,IAAI,aAAa,EAAE,CAAC,GAAG,GAAG;AAC1B;AACA,IAAI,aAAa,EAAE,CAAC,GAAG,IAAI,GAAG,GAAG;AACjC;AACA,IAAI,UAAU,EAAE,KAAK;AACrB;AACA,IAAI,iBAAiB,EAAE,IAAI,GAAG,GAAG;AACjC;AACA,IAAI,cAAc,EAAE,KAAK;AAC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
|
+
|
|
4
|
+
/** The protocols this version knows. */
|
|
5
|
+
const UPLOAD_PROTOCOLS = [
|
|
6
|
+
'firebase-resumable',
|
|
7
|
+
'put',
|
|
8
|
+
's3-multipart',
|
|
9
|
+
'azure-blocks',
|
|
10
|
+
];
|
|
11
|
+
const MIB = 1024 * 1024;
|
|
12
|
+
/** The limits the plugin checks for `s3-multipart` and `azure-blocks`. */
|
|
13
|
+
const UPLOAD_LIMITS = {
|
|
14
|
+
/** Default `partSize` and `blockSize`: 8 MiB. */
|
|
15
|
+
defaultPartSize: 8 * MIB,
|
|
16
|
+
/** S3's smallest part, other than the last: 5 MiB. */
|
|
17
|
+
s3MinPartSize: 5 * MIB,
|
|
18
|
+
/** S3's largest part: 5 GiB. */
|
|
19
|
+
s3MaxPartSize: 5 * 1024 * MIB,
|
|
20
|
+
/** S3's most parts in one upload. */
|
|
21
|
+
s3MaxParts: 10000,
|
|
22
|
+
/** Azure's largest block: 4000 MiB. */
|
|
23
|
+
azureMaxBlockSize: 4000 * MIB,
|
|
24
|
+
/** Azure's most blocks in one blob. */
|
|
25
|
+
azureMaxBlocks: 50000,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const HTTP_URL = /^https?:\/\/[^/]+/i;
|
|
29
|
+
// A line break or any other control character in a header name or value.
|
|
30
|
+
// eslint-disable-next-line no-control-regex
|
|
31
|
+
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
32
|
+
/**
|
|
33
|
+
* Checks a transfer's options before they cross to the native side, so both
|
|
34
|
+
* platforms refuse the same mistakes with the same words. Returns the
|
|
35
|
+
* options with `path` as a plain absolute path. The native sides repeat these
|
|
36
|
+
* checks (a script can call the plugin directly), and also confine `path` to
|
|
37
|
+
* the app's own directories, which only they know.
|
|
38
|
+
*/
|
|
39
|
+
function checkTransferOptions(options) {
|
|
40
|
+
if (!options || typeof options !== 'object')
|
|
41
|
+
throw new Error('options are required');
|
|
42
|
+
const { id, url, path, headers } = options;
|
|
43
|
+
if (typeof id !== 'string' || id.trim() === '')
|
|
44
|
+
throw new Error('id is required');
|
|
45
|
+
if (typeof url !== 'string' || !HTTP_URL.test(url))
|
|
46
|
+
throw new Error('url must be an http or https URL');
|
|
47
|
+
const plain = toPlainPath(path);
|
|
48
|
+
if (headers !== undefined) {
|
|
49
|
+
if (headers === null || typeof headers !== 'object' || Array.isArray(headers)) {
|
|
50
|
+
throw new Error('headers must be an object of strings');
|
|
51
|
+
}
|
|
52
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
53
|
+
if (typeof value !== 'string')
|
|
54
|
+
throw new Error(`header ${name} must be a string`);
|
|
55
|
+
if (name === '' || CONTROL.test(name) || CONTROL.test(value))
|
|
56
|
+
throw new Error(`header ${name} must be one line`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return Object.assign(Object.assign({}, options), { path: plain });
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Checks an upload's options as `checkTransferOptions` does, its `protocol`
|
|
63
|
+
* (`firebase-resumable` when omitted, refused when unknown) and the options
|
|
64
|
+
* that go with it. The native sides check the same things, and also that
|
|
65
|
+
* `partUrls` fits the file's size, which only they can read.
|
|
66
|
+
*/
|
|
67
|
+
function checkUploadOptions(options) {
|
|
68
|
+
var _a;
|
|
69
|
+
const checked = checkTransferOptions(options);
|
|
70
|
+
const protocol = (_a = checked.protocol) !== null && _a !== void 0 ? _a : 'firebase-resumable';
|
|
71
|
+
if (!UPLOAD_PROTOCOLS.includes(protocol)) {
|
|
72
|
+
throw new Error(`protocol must be one of ${UPLOAD_PROTOCOLS.join(', ')}`);
|
|
73
|
+
}
|
|
74
|
+
const { partUrls, partSize, listPartsUrl, blockSize } = checked;
|
|
75
|
+
if (protocol !== 's3-multipart' && (partUrls !== undefined || partSize !== undefined || listPartsUrl !== undefined)) {
|
|
76
|
+
throw new Error('partUrls, partSize and listPartsUrl are only for s3-multipart');
|
|
77
|
+
}
|
|
78
|
+
if (protocol !== 'azure-blocks' && blockSize !== undefined) {
|
|
79
|
+
throw new Error('blockSize is only for azure-blocks');
|
|
80
|
+
}
|
|
81
|
+
if (protocol === 's3-multipart') {
|
|
82
|
+
if (!Array.isArray(partUrls) || partUrls.length === 0)
|
|
83
|
+
throw new Error('partUrls is required for s3-multipart');
|
|
84
|
+
if (partUrls.length > UPLOAD_LIMITS.s3MaxParts) {
|
|
85
|
+
throw new Error(`partUrls holds more than ${UPLOAD_LIMITS.s3MaxParts} parts`);
|
|
86
|
+
}
|
|
87
|
+
if (!partUrls.every((u) => typeof u === 'string' && HTTP_URL.test(u))) {
|
|
88
|
+
throw new Error('partUrls must be http or https URLs');
|
|
89
|
+
}
|
|
90
|
+
const size = partSize !== null && partSize !== void 0 ? partSize : UPLOAD_LIMITS.defaultPartSize;
|
|
91
|
+
if (!Number.isSafeInteger(size) || size < 1 || size > UPLOAD_LIMITS.s3MaxPartSize) {
|
|
92
|
+
throw new Error('partSize must be a whole number of bytes up to 5 GiB');
|
|
93
|
+
}
|
|
94
|
+
if (partUrls.length > 1 && size < UPLOAD_LIMITS.s3MinPartSize) {
|
|
95
|
+
throw new Error('partSize must be at least 5 MiB when there is more than one part');
|
|
96
|
+
}
|
|
97
|
+
if (listPartsUrl !== undefined && (typeof listPartsUrl !== 'string' || !HTTP_URL.test(listPartsUrl))) {
|
|
98
|
+
throw new Error('listPartsUrl must be an http or https URL');
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (protocol === 'azure-blocks') {
|
|
102
|
+
if (!isSasUrl(checked.url))
|
|
103
|
+
throw new Error('url must be a blob SAS URL (with a sig parameter)');
|
|
104
|
+
const size = blockSize !== null && blockSize !== void 0 ? blockSize : UPLOAD_LIMITS.defaultPartSize;
|
|
105
|
+
if (!Number.isSafeInteger(size) || size < 1 || size > UPLOAD_LIMITS.azureMaxBlockSize) {
|
|
106
|
+
throw new Error('blockSize must be a whole number of bytes up to 4000 MiB');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return Object.assign(Object.assign({}, checked), { protocol });
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* A blob URL with a SAS token: a non-empty `sig` parameter, and no `comp` (the plugin adds its
|
|
113
|
+
* own). Parameter names are compared as written, as the native sides do.
|
|
114
|
+
*/
|
|
115
|
+
function isSasUrl(url) {
|
|
116
|
+
const query = url.split('#')[0].split('?')[1];
|
|
117
|
+
if (!query)
|
|
118
|
+
return false;
|
|
119
|
+
const params = query.split('&');
|
|
120
|
+
const names = params.map((p) => p.split('=')[0]);
|
|
121
|
+
return params.some((p) => p.startsWith('sig=') && p.length > 'sig='.length) && !names.includes('comp');
|
|
122
|
+
}
|
|
123
|
+
/** `file:///a/b%20c.mp4` → `/a/b c.mp4`; absolute paths pass through. */
|
|
124
|
+
function toPlainPath(path) {
|
|
125
|
+
if (typeof path !== 'string' || path === '')
|
|
126
|
+
throw new Error('path is required');
|
|
127
|
+
let plain = path;
|
|
128
|
+
if (plain.startsWith('file://')) {
|
|
129
|
+
plain = decodeURIComponent(plain.slice('file://'.length));
|
|
130
|
+
}
|
|
131
|
+
if (!plain.startsWith('/'))
|
|
132
|
+
throw new Error('path must be absolute or a file:// URI');
|
|
133
|
+
if (plain.endsWith('/'))
|
|
134
|
+
throw new Error('path must name a file');
|
|
135
|
+
if (plain.split('/').includes('..'))
|
|
136
|
+
throw new Error('path must not contain ..');
|
|
137
|
+
return plain;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const Native = core.registerPlugin('BackgroundTransfer', {
|
|
141
|
+
web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.BackgroundTransferWeb()),
|
|
142
|
+
});
|
|
143
|
+
/**
|
|
144
|
+
* The plugin, with `upload` and `download` options checked (and `file://`
|
|
145
|
+
* URIs turned into paths) before they reach the native side.
|
|
146
|
+
*/
|
|
147
|
+
const BackgroundTransfer = wrap(Native);
|
|
148
|
+
function wrap(plugin) {
|
|
149
|
+
return {
|
|
150
|
+
isAvailable: () => plugin.isAvailable(),
|
|
151
|
+
upload: async (options) => plugin.upload(checkUploadOptions(options)),
|
|
152
|
+
download: async (options) => plugin.download(checkTransferOptions(options)),
|
|
153
|
+
cancel: (options) => plugin.cancel(options),
|
|
154
|
+
list: () => plugin.list(),
|
|
155
|
+
forget: (options) => plugin.forget(options),
|
|
156
|
+
addListener: ((eventName, listener) => plugin.addListener(eventName, listener)),
|
|
157
|
+
removeAllListeners: () => plugin.removeAllListeners(),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The web has no background transfers: it says so, and every transfer call
|
|
163
|
+
* is refused with Capacitor's `UNAVAILABLE` code, so the app keeps its
|
|
164
|
+
* in-app path there.
|
|
165
|
+
*/
|
|
166
|
+
class BackgroundTransferWeb extends core.WebPlugin {
|
|
167
|
+
async isAvailable() {
|
|
168
|
+
return { available: false, mechanism: 'none' };
|
|
169
|
+
}
|
|
170
|
+
async upload() {
|
|
171
|
+
throw this.unavailable('Background transfers are not available on the web.');
|
|
172
|
+
}
|
|
173
|
+
async download() {
|
|
174
|
+
throw this.unavailable('Background transfers are not available on the web.');
|
|
175
|
+
}
|
|
176
|
+
async cancel() {
|
|
177
|
+
throw this.unavailable('Background transfers are not available on the web.');
|
|
178
|
+
}
|
|
179
|
+
async list() {
|
|
180
|
+
return { transfers: [] };
|
|
181
|
+
}
|
|
182
|
+
async forget() {
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
var web = /*#__PURE__*/Object.freeze({
|
|
188
|
+
__proto__: null,
|
|
189
|
+
BackgroundTransferWeb: BackgroundTransferWeb
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
exports.BackgroundTransfer = BackgroundTransfer;
|
|
193
|
+
exports.UPLOAD_LIMITS = UPLOAD_LIMITS;
|
|
194
|
+
exports.UPLOAD_PROTOCOLS = UPLOAD_PROTOCOLS;
|
|
195
|
+
exports.checkTransferOptions = checkTransferOptions;
|
|
196
|
+
exports.checkUploadOptions = checkUploadOptions;
|
|
197
|
+
exports.toPlainPath = toPlainPath;
|
|
198
|
+
exports.wrap = wrap;
|
|
199
|
+
|
|
200
|
+
return exports;
|
|
201
|
+
|
|
202
|
+
})({}, capacitorExports);
|
|
203
|
+
//# sourceMappingURL=plugin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.js","sources":["esm/definitions.js","esm/validate.js","esm/index.js","esm/web.js"],"sourcesContent":["/** The protocols this version knows. */\nexport const UPLOAD_PROTOCOLS = [\n 'firebase-resumable',\n 'put',\n 's3-multipart',\n 'azure-blocks',\n];\nconst MIB = 1024 * 1024;\n/** The limits the plugin checks for `s3-multipart` and `azure-blocks`. */\nexport const UPLOAD_LIMITS = {\n /** Default `partSize` and `blockSize`: 8 MiB. */\n defaultPartSize: 8 * MIB,\n /** S3's smallest part, other than the last: 5 MiB. */\n s3MinPartSize: 5 * MIB,\n /** S3's largest part: 5 GiB. */\n s3MaxPartSize: 5 * 1024 * MIB,\n /** S3's most parts in one upload. */\n s3MaxParts: 10000,\n /** Azure's largest block: 4000 MiB. */\n azureMaxBlockSize: 4000 * MIB,\n /** Azure's most blocks in one blob. */\n azureMaxBlocks: 50000,\n};\n//# sourceMappingURL=definitions.js.map","import { UPLOAD_LIMITS, UPLOAD_PROTOCOLS } from './definitions';\nconst HTTP_URL = /^https?:\\/\\/[^/]+/i;\n// A line break or any other control character in a header name or value.\n// eslint-disable-next-line no-control-regex\nconst CONTROL = /[\\u0000-\\u001f\\u007f]/;\n/**\n * Checks a transfer's options before they cross to the native side, so both\n * platforms refuse the same mistakes with the same words. Returns the\n * options with `path` as a plain absolute path. The native sides repeat these\n * checks (a script can call the plugin directly), and also confine `path` to\n * the app's own directories, which only they know.\n */\nexport function checkTransferOptions(options) {\n if (!options || typeof options !== 'object')\n throw new Error('options are required');\n const { id, url, path, headers } = options;\n if (typeof id !== 'string' || id.trim() === '')\n throw new Error('id is required');\n if (typeof url !== 'string' || !HTTP_URL.test(url))\n throw new Error('url must be an http or https URL');\n const plain = toPlainPath(path);\n if (headers !== undefined) {\n if (headers === null || typeof headers !== 'object' || Array.isArray(headers)) {\n throw new Error('headers must be an object of strings');\n }\n for (const [name, value] of Object.entries(headers)) {\n if (typeof value !== 'string')\n throw new Error(`header ${name} must be a string`);\n if (name === '' || CONTROL.test(name) || CONTROL.test(value))\n throw new Error(`header ${name} must be one line`);\n }\n }\n return Object.assign(Object.assign({}, options), { path: plain });\n}\n/**\n * Checks an upload's options as `checkTransferOptions` does, its `protocol`\n * (`firebase-resumable` when omitted, refused when unknown) and the options\n * that go with it. The native sides check the same things, and also that\n * `partUrls` fits the file's size, which only they can read.\n */\nexport function checkUploadOptions(options) {\n var _a;\n const checked = checkTransferOptions(options);\n const protocol = (_a = checked.protocol) !== null && _a !== void 0 ? _a : 'firebase-resumable';\n if (!UPLOAD_PROTOCOLS.includes(protocol)) {\n throw new Error(`protocol must be one of ${UPLOAD_PROTOCOLS.join(', ')}`);\n }\n const { partUrls, partSize, listPartsUrl, blockSize } = checked;\n if (protocol !== 's3-multipart' && (partUrls !== undefined || partSize !== undefined || listPartsUrl !== undefined)) {\n throw new Error('partUrls, partSize and listPartsUrl are only for s3-multipart');\n }\n if (protocol !== 'azure-blocks' && blockSize !== undefined) {\n throw new Error('blockSize is only for azure-blocks');\n }\n if (protocol === 's3-multipart') {\n if (!Array.isArray(partUrls) || partUrls.length === 0)\n throw new Error('partUrls is required for s3-multipart');\n if (partUrls.length > UPLOAD_LIMITS.s3MaxParts) {\n throw new Error(`partUrls holds more than ${UPLOAD_LIMITS.s3MaxParts} parts`);\n }\n if (!partUrls.every((u) => typeof u === 'string' && HTTP_URL.test(u))) {\n throw new Error('partUrls must be http or https URLs');\n }\n const size = partSize !== null && partSize !== void 0 ? partSize : UPLOAD_LIMITS.defaultPartSize;\n if (!Number.isSafeInteger(size) || size < 1 || size > UPLOAD_LIMITS.s3MaxPartSize) {\n throw new Error('partSize must be a whole number of bytes up to 5 GiB');\n }\n if (partUrls.length > 1 && size < UPLOAD_LIMITS.s3MinPartSize) {\n throw new Error('partSize must be at least 5 MiB when there is more than one part');\n }\n if (listPartsUrl !== undefined && (typeof listPartsUrl !== 'string' || !HTTP_URL.test(listPartsUrl))) {\n throw new Error('listPartsUrl must be an http or https URL');\n }\n }\n if (protocol === 'azure-blocks') {\n if (!isSasUrl(checked.url))\n throw new Error('url must be a blob SAS URL (with a sig parameter)');\n const size = blockSize !== null && blockSize !== void 0 ? blockSize : UPLOAD_LIMITS.defaultPartSize;\n if (!Number.isSafeInteger(size) || size < 1 || size > UPLOAD_LIMITS.azureMaxBlockSize) {\n throw new Error('blockSize must be a whole number of bytes up to 4000 MiB');\n }\n }\n return Object.assign(Object.assign({}, checked), { protocol });\n}\n/**\n * A blob URL with a SAS token: a non-empty `sig` parameter, and no `comp` (the plugin adds its\n * own). Parameter names are compared as written, as the native sides do.\n */\nfunction isSasUrl(url) {\n const query = url.split('#')[0].split('?')[1];\n if (!query)\n return false;\n const params = query.split('&');\n const names = params.map((p) => p.split('=')[0]);\n return params.some((p) => p.startsWith('sig=') && p.length > 'sig='.length) && !names.includes('comp');\n}\n/** `file:///a/b%20c.mp4` → `/a/b c.mp4`; absolute paths pass through. */\nexport function toPlainPath(path) {\n if (typeof path !== 'string' || path === '')\n throw new Error('path is required');\n let plain = path;\n if (plain.startsWith('file://')) {\n plain = decodeURIComponent(plain.slice('file://'.length));\n }\n if (!plain.startsWith('/'))\n throw new Error('path must be absolute or a file:// URI');\n if (plain.endsWith('/'))\n throw new Error('path must name a file');\n if (plain.split('/').includes('..'))\n throw new Error('path must not contain ..');\n return plain;\n}\n//# sourceMappingURL=validate.js.map","import { registerPlugin } from '@capacitor/core';\nimport { checkTransferOptions, checkUploadOptions } from './validate';\nconst Native = registerPlugin('BackgroundTransfer', {\n web: () => import('./web').then((m) => new m.BackgroundTransferWeb()),\n});\n/**\n * The plugin, with `upload` and `download` options checked (and `file://`\n * URIs turned into paths) before they reach the native side.\n */\nconst BackgroundTransfer = wrap(Native);\nexport function wrap(plugin) {\n return {\n isAvailable: () => plugin.isAvailable(),\n upload: async (options) => plugin.upload(checkUploadOptions(options)),\n download: async (options) => plugin.download(checkTransferOptions(options)),\n cancel: (options) => plugin.cancel(options),\n list: () => plugin.list(),\n forget: (options) => plugin.forget(options),\n addListener: ((eventName, listener) => plugin.addListener(eventName, listener)),\n removeAllListeners: () => plugin.removeAllListeners(),\n };\n}\nexport * from './definitions';\nexport { checkTransferOptions, checkUploadOptions, toPlainPath } from './validate';\nexport { BackgroundTransfer };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\n/**\n * The web has no background transfers: it says so, and every transfer call\n * is refused with Capacitor's `UNAVAILABLE` code, so the app keeps its\n * in-app path there.\n */\nexport class BackgroundTransferWeb extends WebPlugin {\n async isAvailable() {\n return { available: false, mechanism: 'none' };\n }\n async upload() {\n throw this.unavailable('Background transfers are not available on the web.');\n }\n async download() {\n throw this.unavailable('Background transfers are not available on the web.');\n }\n async cancel() {\n throw this.unavailable('Background transfers are not available on the web.');\n }\n async list() {\n return { transfers: [] };\n }\n async forget() {\n return;\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;IAAA;AACY,UAAC,gBAAgB,GAAG;IAChC,IAAI,oBAAoB;IACxB,IAAI,KAAK;IACT,IAAI,cAAc;IAClB,IAAI,cAAc;IAClB;IACA,MAAM,GAAG,GAAG,IAAI,GAAG,IAAI;IACvB;AACY,UAAC,aAAa,GAAG;IAC7B;IACA,IAAI,eAAe,EAAE,CAAC,GAAG,GAAG;IAC5B;IACA,IAAI,aAAa,EAAE,CAAC,GAAG,GAAG;IAC1B;IACA,IAAI,aAAa,EAAE,CAAC,GAAG,IAAI,GAAG,GAAG;IACjC;IACA,IAAI,UAAU,EAAE,KAAK;IACrB;IACA,IAAI,iBAAiB,EAAE,IAAI,GAAG,GAAG;IACjC;IACA,IAAI,cAA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4 MiB at a time.
|
|
4
|
+
public enum Files {
|
|
5
|
+
public static let piece = 4 * 1024 * 1024
|
|
6
|
+
|
|
7
|
+
/// Copies the bytes of `source` after `offset` into a new file at `destination` and returns how
|
|
8
|
+
/// many were written. A background upload can only send a whole file, so resuming part-way
|
|
9
|
+
/// sends this copy. Throws `CocoaError(.fileWriteOutOfSpace)` when the disk is full,
|
|
10
|
+
/// leaving no partial copy behind.
|
|
11
|
+
@discardableResult
|
|
12
|
+
public static func writeRemainder(of source: URL, from offset: Int64, to destination: URL, piece: Int = piece) throws -> Int64 {
|
|
13
|
+
try writeRange(of: source, from: offset, length: nil, to: destination, piece: piece)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/// Copies `length` bytes of `source` from `offset` (or all after it, when nil) into a new file at
|
|
17
|
+
/// `destination`, as `writeRemainder` does: a part or block of an upload in parts is sent from
|
|
18
|
+
/// such a copy. Throws if the file is too short.
|
|
19
|
+
@discardableResult
|
|
20
|
+
public static func writeRange(of source: URL, from offset: Int64, length: Int64?, to destination: URL, piece: Int = piece) throws -> Int64 {
|
|
21
|
+
let size = try fileSize(source)
|
|
22
|
+
if let length = length, length < 0 || offset + length > size {
|
|
23
|
+
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError,
|
|
24
|
+
userInfo: [NSLocalizedDescriptionKey: "range \(offset)+\(length) outside a \(size)-byte file"])
|
|
25
|
+
}
|
|
26
|
+
guard offset >= 0, offset <= size else {
|
|
27
|
+
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError,
|
|
28
|
+
userInfo: [NSLocalizedDescriptionKey: "offset \(offset) outside 0...\(size)"])
|
|
29
|
+
}
|
|
30
|
+
let fm = FileManager.default
|
|
31
|
+
try fm.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
32
|
+
try? fm.removeItem(at: destination)
|
|
33
|
+
guard fm.createFile(atPath: destination.path, contents: nil,
|
|
34
|
+
attributes: [.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication]) else {
|
|
35
|
+
throw CocoaError(.fileWriteUnknown)
|
|
36
|
+
}
|
|
37
|
+
do {
|
|
38
|
+
let input = try FileHandle(forReadingFrom: source)
|
|
39
|
+
defer { try? input.close() }
|
|
40
|
+
let output = try FileHandle(forWritingTo: destination)
|
|
41
|
+
defer { try? output.close() }
|
|
42
|
+
try input.seek(toOffset: UInt64(offset))
|
|
43
|
+
var written: Int64 = 0
|
|
44
|
+
while length.map({ written < $0 }) ?? true {
|
|
45
|
+
let want = length.map { Int(min(Int64(piece), $0 - written)) } ?? piece
|
|
46
|
+
let data = try autoreleasepool { try input.read(upToCount: want) ?? Data() }
|
|
47
|
+
if data.isEmpty { break }
|
|
48
|
+
try output.write(contentsOf: data)
|
|
49
|
+
written += Int64(data.count)
|
|
50
|
+
}
|
|
51
|
+
try output.synchronize()
|
|
52
|
+
if let length = length, written != length {
|
|
53
|
+
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError,
|
|
54
|
+
userInfo: [NSLocalizedDescriptionKey: "copied \(written) of \(length) bytes"])
|
|
55
|
+
}
|
|
56
|
+
return written
|
|
57
|
+
} catch {
|
|
58
|
+
try? fm.removeItem(at: destination)
|
|
59
|
+
throw error
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/// Appends the whole of `piece` to `part` (a resumed download's new bytes), 4 MiB at a time.
|
|
64
|
+
public static func append(_ pieceFile: URL, to part: URL) throws {
|
|
65
|
+
let output = try FileHandle(forWritingTo: part)
|
|
66
|
+
defer { try? output.close() }
|
|
67
|
+
try output.seekToEnd()
|
|
68
|
+
let input = try FileHandle(forReadingFrom: pieceFile)
|
|
69
|
+
defer { try? input.close() }
|
|
70
|
+
while true {
|
|
71
|
+
let data = try autoreleasepool { try input.read(upToCount: piece) ?? Data() }
|
|
72
|
+
if data.isEmpty { break }
|
|
73
|
+
try output.write(contentsOf: data)
|
|
74
|
+
}
|
|
75
|
+
try output.synchronize()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// Moves `part` to `destination` (replacing anything there), but only if it is `size` bytes.
|
|
79
|
+
public static func finish(part: URL, at destination: URL, size: Int64) throws {
|
|
80
|
+
let have = try fileSize(part)
|
|
81
|
+
guard size < 0 || have == size else {
|
|
82
|
+
throw NSError(domain: "BackgroundTransfer", code: 1,
|
|
83
|
+
userInfo: [NSLocalizedDescriptionKey: "part file is \(have) bytes, expected \(size)"])
|
|
84
|
+
}
|
|
85
|
+
let fm = FileManager.default
|
|
86
|
+
if fm.fileExists(atPath: destination.path) { try fm.removeItem(at: destination) }
|
|
87
|
+
try fm.moveItem(at: part, to: destination)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
public static func fileSize(_ url: URL) throws -> Int64 {
|
|
91
|
+
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
|
|
92
|
+
if (attributes[.type] as? FileAttributeType) == .typeDirectory {
|
|
93
|
+
throw CocoaError(.fileReadNoSuchFile)
|
|
94
|
+
}
|
|
95
|
+
return (attributes[.size] as? NSNumber)?.int64Value ?? 0
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/// Removes every file in `directory` whose path isn't in `keep`, and returns what it removed.
|
|
99
|
+
/// Remainder copies left by a process that ended mid-copy are found this way on the next launch.
|
|
100
|
+
@discardableResult
|
|
101
|
+
public static func removeOrphans(in directory: URL, keeping keep: Set<String>) -> [URL] {
|
|
102
|
+
let fm = FileManager.default
|
|
103
|
+
guard let names = try? fm.contentsOfDirectory(atPath: directory.path) else { return [] }
|
|
104
|
+
let kept = Set(keep.map { URL(fileURLWithPath: $0).standardizedFileURL.path })
|
|
105
|
+
var removed: [URL] = []
|
|
106
|
+
for name in names {
|
|
107
|
+
let url = directory.appendingPathComponent(name).standardizedFileURL
|
|
108
|
+
if kept.contains(url.path) { continue }
|
|
109
|
+
if (try? fm.removeItem(at: url)) != nil { removed.append(url) }
|
|
110
|
+
}
|
|
111
|
+
return removed
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/// `<path>.part`: where a download's bytes go until all have landed.
|
|
115
|
+
public static func partURL(for destination: URL) -> URL {
|
|
116
|
+
URL(fileURLWithPath: destination.path + ".part")
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/// Keeps `directory` and everything under it out of iCloud and Finder backups: the plugin's
|
|
120
|
+
/// records hold the headers and URLs (with their tokens) of every transfer, its resume data the
|
|
121
|
+
/// original requests, and none of that belongs on another device.
|
|
122
|
+
public static func excludeFromBackup(_ directory: URL) throws {
|
|
123
|
+
var url = directory
|
|
124
|
+
var values = URLResourceValues()
|
|
125
|
+
values.isExcludedFromBackup = true
|
|
126
|
+
try url.setResourceValues(values)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/// Whether `url` is excluded from backups (for the tests).
|
|
130
|
+
public static func isExcludedFromBackup(_ url: URL) -> Bool {
|
|
131
|
+
(try? url.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup) ?? false
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// A parsed `Content-Range` header.
|
|
136
|
+
public struct ContentRange: Equatable {
|
|
137
|
+
public let start: Int64 // -1 for `bytes */total`
|
|
138
|
+
public let end: Int64
|
|
139
|
+
public let total: Int64 // -1 for `/*`
|
|
140
|
+
|
|
141
|
+
public init(start: Int64, end: Int64, total: Int64) {
|
|
142
|
+
self.start = start
|
|
143
|
+
self.end = end
|
|
144
|
+
self.total = total
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/// Where a request's `Range: bytes=N-` asks to start: N, or 0 with no (or another kind of) Range.
|
|
148
|
+
public static func requestedStart(_ rangeHeader: String?) -> Int64 {
|
|
149
|
+
guard let h = rangeHeader?.trimmingCharacters(in: .whitespaces), h.hasPrefix("bytes="), h.hasSuffix("-") else { return 0 }
|
|
150
|
+
return Int64(h.dropFirst("bytes=".count).dropLast()) ?? 0
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/// `bytes 100-199/1000`, `bytes */1000` or `bytes 0-9/*`; nil otherwise.
|
|
154
|
+
public static func parse(_ header: String?) -> ContentRange? {
|
|
155
|
+
guard let header = header?.trimmingCharacters(in: .whitespaces), header.hasPrefix("bytes ") else { return nil }
|
|
156
|
+
let rest = header.dropFirst("bytes ".count)
|
|
157
|
+
let parts = rest.split(separator: "/", omittingEmptySubsequences: false)
|
|
158
|
+
guard parts.count == 2 else { return nil }
|
|
159
|
+
let total: Int64
|
|
160
|
+
if parts[1] == "*" { total = -1 } else if let t = Int64(parts[1]) { total = t } else { return nil }
|
|
161
|
+
if parts[0] == "*" { return ContentRange(start: -1, end: -1, total: total) }
|
|
162
|
+
let bounds = parts[0].split(separator: "-")
|
|
163
|
+
guard bounds.count == 2, let s = Int64(bounds[0]), let e = Int64(bounds[1]), s <= e else { return nil }
|
|
164
|
+
return ContentRange(start: s, end: e, total: total)
|
|
165
|
+
}
|
|
166
|
+
}
|