Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<script setup lang="ts">
import BootstrapModal from "@/components/modals/BootstrapModal.vue";
import { useS3ObjectStore } from "@/stores";
import { GetObjectCommand } from "@aws-sdk/client-s3";
import { computed, reactive, watch } from "vue";
import { filesize } from "filesize";
import FontAwesomeIcon from "@/components/FontAwesomeIcon.vue";
const props = defineProps<{
modalId: string;
bucketName: string;
keys: string[];
}>();
const downloadState = reactive<{
downloading: boolean;
doneFiles: number;
totalFiles: number;
fileSize: number;
downloadedBytes: number;
currentFile: string;
folder: string;
controller?: AbortController;
downloadedFiles: Set<string>;
errorFiles: Set<string>;
}>({
downloading: false,
doneFiles: 0,
totalFiles: 0,
fileSize: 0,
downloadedBytes: 0,
currentFile: "",
folder: "",
controller: undefined,
downloadedFiles: new Set<string>(),
errorFiles: new Set<string>(),
});
const objKeys = computed<string[]>(() => {
return props.keys
.map((key) => {
if (key.endsWith("/")) {
return objectRepository.objectMapping[props.bucketName]
.filter((obj) => obj.Key?.startsWith(key))
.map((obj) => obj.Key ?? "")
.filter((obj) => obj.length > 0)
.filter((obj) => !obj.endsWith("/"));
}
return key;
})
.flat();
});
watch(
() => props.keys,
() => {
if (!downloadState.downloading) {
downloadState.downloading = false;
downloadState.doneFiles = 0;
downloadState.totalFiles = 0;
downloadState.fileSize = 0;
downloadState.downloadedBytes = 0;
downloadState.currentFile = "";
downloadState.folder = "";
downloadState.controller = undefined;
downloadState.downloadedFiles = new Set<string>();
downloadState.errorFiles = new Set<string>();
}
},
);
interface Range {
start: number;
end: number;
}
interface RangeLength extends Range {
length: number;
}
const objectRepository = useS3ObjectStore();
const PART_SIZE = 10 * 1024 * 1024;
function getObjectRange(
bucket: string,
key: string,
range?: Range,
abortController?: AbortController,
) {
const command = new GetObjectCommand({
Bucket: bucket,
Key: key,
Range: range != undefined ? `bytes=${range.start}-${range.end}` : undefined,
});
return objectRepository.client.send(command, {
abortSignal: abortController?.signal,
});
}
/**
* @param {string | undefined} contentRange
*/
function getRangeAndLength(contentRange: string) {
const [, numbers] = contentRange.split(" ");
const [range, length] = numbers.split("/");
const [start, end] = range.split("-");
return {
start: Number.parseInt(start),
end: Number.parseInt(end),
length: Number.parseInt(length),
};
}
function isComplete(range: RangeLength) {
return range.end === range.length - 1;
}
async function downloadInChunks(
bucket: string,
key: string,
handle: FileSystemWritableFileStream,
abortController?: AbortController,
) {
let rangeAndLength: RangeLength = { start: -1, end: -1, length: -1 };
downloadState.fileSize = 0;
downloadState.downloadedBytes = 0;
await objectRepository.fetchS3ObjectMeta(bucket, key);
while (!isComplete(rangeAndLength)) {
const nextRange: Range = {
start: rangeAndLength.end + 1,
end: rangeAndLength.end + PART_SIZE,
};
if (rangeAndLength.length > 0) {
downloadState.fileSize = rangeAndLength.length;
nextRange.end = Math.min(
rangeAndLength.length - 1,
rangeAndLength.end + PART_SIZE,
);
}
try {
const metaKey = bucket + "/" + key;
const response = await getObjectRange(
bucket,
key,
objectRepository.objectMetaMapping[metaKey]?.ContentLength !=
undefined &&
objectRepository.objectMetaMapping[metaKey]?.ContentLength < PART_SIZE
? undefined
: nextRange,
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
abortController,
);
if (response.Body != undefined) {
await handle.write(await response.Body.transformToByteArray());
downloadState.downloadedBytes += PART_SIZE;
if (response.ContentRange == undefined) {
break;
}
rangeAndLength = getRangeAndLength(response.ContentRange);
} else {
break;
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
} catch (err: Error) {
if (err.name === "InvalidRange") {
break;
}
throw err;
}
}
}
async function downloadFiles() {
let dirHandle: FileSystemDirectoryHandle;
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
dirHandle = await window.showDirectoryPicker();
} catch {
return;
}
downloadState.folder = dirHandle.name;
downloadState.downloading = true;
downloadState.totalFiles = objKeys.value.length;
downloadState.doneFiles = 0;
downloadState.controller = new AbortController();
downloadState.downloadedFiles = new Set<string>();
downloadState.errorFiles = new Set<string>();
outer: for (const file of objKeys.value) {
let subHandle = dirHandle;
const subFolders = file.split("/");
if (subFolders[subFolders.length - 1].length === 0) {
continue;
}
downloadState.currentFile = file;
for (const folder of subFolders.slice(0, subFolders.length - 1)) {
try {
subHandle = await subHandle.getDirectoryHandle(folder, {
create: true,
});
} catch {
continue outer;
}
}
const fileHandle = await subHandle.getFileHandle(
subFolders[subFolders.length - 1],
{
create: true,
},
);
const writeStream = await fileHandle.createWritable({
keepExistingData: false,
});
try {
await downloadInChunks(
props.bucketName,
file,
writeStream,
downloadState.controller,
);
downloadState.downloadedFiles.add(file);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
} catch (caught: Error) {
downloadState.errorFiles.add(file);
await writeStream.truncate(0);
if (caught.name === "AbortError") {
break;
}
} finally {
downloadState.doneFiles++;
await writeStream.close();
}
}
downloadState.controller = undefined;
downloadState.downloading = false;
}
function determineIcon(key: string): string {
if (downloadState.errorFiles.has(key)) {
return "circle-xmark";
}
if (downloadState.downloadedFiles.has(key)) {
return "circle-check";
}
if (downloadState.currentFile === key) {
return "circle-down";
}
return "circle-pause";
}
function determineColor(key: string): string {
if (downloadState.errorFiles.has(key)) {
return "text-danger";
}
if (downloadState.downloadedFiles.has(key)) {
return "text-success";
}
if (downloadState.currentFile === key) {
return "text-info";
}
return "text-warning";
}
function abortDownload() {
downloadState.controller?.abort();
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const enableDownload = typeof window.showDirectoryPicker === "function";
</script>
<template>
<bootstrap-modal
:modal-id="modalId"
modal-label="Download Objects"
static-backdrop
size-modifier-modal="xl"
v-on="{ 'hidden.bs.modal': abortDownload }"
>
<template #header>Download files</template>
<template #body>
<div class="row">
<h4>Files to download</h4>
<div class="col overflow-auto" style="max-height: 70vh">
<div v-for="key in objKeys" :key="key">
<font-awesome-icon
:icon="`fa-solid fa-${determineIcon(key)}`"
:class="determineColor(key)"
/>
{{ key }}
</div>
</div>
<div v-if="!enableDownload" class="col">
<p>
Your browser doesn't support selecting a folder to download the
files into. Look
<a
target="_blank"
href="https://developer.mozilla.org/en-US/docs/Web/API/Window/showDirectoryPicker#browser_compatibility"
>here</a
>
for a compatibility table
</p>
</div>
<div v-if="downloadState.downloading" class="col-4">
<p class="text-warning">
<font-awesome-icon
icon="fa-solid fa-triangle-exclamation"
class="me-2"
/>
Do not close the modal during the download
</p>
<p>Download into folder {{ downloadState.folder }}</p>
<div
v-if="downloadState.totalFiles > 1"
class="progress mt-2"
role="progressbar"
aria-label="Example with label"
:aria-valuenow="
Math.ceil(
(downloadState.doneFiles * 100) / downloadState.totalFiles,
)
"
aria-valuemin="0"
aria-valuemax="100"
>
<div
class="progress-bar"
:style="{
width: `${(downloadState.doneFiles * 100) / downloadState.totalFiles}%`,
}"
>
{{ downloadState.doneFiles }} / {{ downloadState.totalFiles }}
</div>
</div>
<div v-if="downloadState.fileSize > 0">
<div class="mt-2">
{{
filesize(
Math.min(
downloadState.downloadedBytes,
downloadState.fileSize,
),
)
}}/{{ filesize(downloadState.fileSize) }}
</div>
<div
class="progress mt-2"
role="progressbar"
aria-label="Example with label"
:aria-valuenow="
Math.min(
Math.ceil(
(downloadState.downloadedBytes * 100) /
downloadState.fileSize,
),
100,
)
"
aria-valuemin="0"
aria-valuemax="100"
>
<div
class="progress-bar progress-bar-striped progress-bar-animated bg-success"
:style="{
width: `${Math.min((downloadState.downloadedBytes * 100) / downloadState.fileSize, 100)}%`,
}"
>
{{
Math.min(
Math.ceil(
(downloadState.downloadedBytes * 100) /
downloadState.fileSize,
),
100,
)
}}%
</div>
</div>
</div>
</div>
</div>
</template>
<template #footer>
<button
v-if="!downloadState.downloading"
type="button"
class="btn btn-secondary"
data-bs-dismiss="modal"
>
Close
</button>
<button
v-if="!downloadState.downloading"
type="button"
class="btn btn-primary"
:disabled="!enableDownload"
@click="downloadFiles()"
>