-
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathBackupCreateFlow.tsx
More file actions
485 lines (447 loc) · 14 KB
/
Copy pathBackupCreateFlow.tsx
File metadata and controls
485 lines (447 loc) · 14 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
import {
FolderOpenTwoTone,
DownloadOutlined,
CheckCircleOutlined,
} from "@ant-design/icons";
import {
Button,
Tooltip,
message,
Card,
List,
Checkbox,
Typography,
Progress,
Radio,
Space,
} from "antd";
import type { RadioChangeEvent } from "antd";
import React, { useState } from "react";
import { useMutation, gql, useQuery } from "@apollo/client";
import environment from "shared/environment";
import checks from "renderer/compatibility/checks";
import { useTranslation } from "react-i18next";
import legacyDownload from "js-file-download";
import { delay } from "shared/tools";
const notAvailable = !environment.isElectron && !checks.hasFilesystemApi;
type ModelInfo = {
fileName: string;
displayName: string;
};
const BackupCreateFlow: React.FC = () => {
const { t } = useTranslation("backup");
const [directory, setDirectory] = useState<string | null>(null);
const [selectedModels, setSelectedModels] = useState<string[]>([]);
const [creating, setCreating] = useState(false);
const [progress, setProgress] = useState(0);
const [downloadFormat, setDownloadFormat] = useState<
"etx" | "zip" | "individual"
>("etx");
const [includeLabels, setIncludeLabels] = useState(false);
const [selectDirectory] = useMutation(
gql(/* GraphQL */ `
mutation PickSdcardDirectory {
pickSdcardDirectory {
id
}
}
`)
);
const [createBackup] = useMutation(
gql(/* GraphQL */ `
mutation CreateBackupFromSdcard(
$directoryId: ID!
$selectedModels: [String!]
$fileName: String
$includeLabels: Boolean
) {
createBackupFromSdcard(
directoryId: $directoryId
selectedModels: $selectedModels
fileName: $fileName
includeLabels: $includeLabels
) {
id
name
base64Data
}
}
`)
);
const [downloadIndividualModels] = useMutation(
gql(/* GraphQL */ `
mutation DownloadIndividualModels(
$directoryId: ID!
$selectedModels: [String!]!
$includeLabels: Boolean
) {
downloadIndividualModels(
directoryId: $directoryId
selectedModels: $selectedModels
includeLabels: $includeLabels
) {
fileName
base64Data
}
}
`)
);
const { data: directoryInfo } = useQuery(
gql(/* GraphQL */ `
query SdcardDirectoryInfo($directoryId: ID!) {
sdcardModelsDirectory(id: $directoryId) {
id
name
isValid
hasLabels
pack {
target
version
}
}
}
`),
{
variables: {
directoryId: directory ?? "",
},
skip: !directory,
fetchPolicy: "cache-and-network",
}
);
const { data: modelsData } = useQuery(
gql(/* GraphQL */ `
query SdcardModelsWithNames($directoryId: ID!) {
sdcardModelsWithNames(directoryId: $directoryId) {
fileName
displayName
}
}
`),
{
variables: {
directoryId: directory ?? "",
},
skip: !directory,
fetchPolicy: "cache-and-network",
}
);
const directoryData = directoryInfo?.sdcardModelsDirectory;
const availableModels: ModelInfo[] = (modelsData?.sdcardModelsWithNames ??
[]) as ModelInfo[];
const handleSelectDirectory = (): void => {
void selectDirectory().then((result) => {
if (result.data?.pickSdcardDirectory) {
const pickedDirectoryData = result.data.pickSdcardDirectory;
setDirectory(pickedDirectoryData.id);
void message.success(t(`SD Card selected successfully`));
}
});
};
const handleSelectAll = (checked: boolean): void => {
if (checked) {
setSelectedModels(availableModels.map((m: ModelInfo) => m.fileName));
} else {
setSelectedModels([]);
}
};
const handleModelToggle = (fileName: string, checked: boolean): void => {
if (checked) {
setSelectedModels([...selectedModels, fileName]);
} else {
setSelectedModels(selectedModels.filter((m) => m !== fileName));
}
};
const handleCreateBackup = (): void => {
if (!directory) {
void message.error(t(`Please select SD Card first`));
return;
}
if (selectedModels.length === 0) {
void message.error(t(`Please select at least one model`));
return;
}
setCreating(true);
setProgress(0);
const isoString = new Date().toISOString();
const timestamp = isoString.replace(/[:.]/g, "-").split("T")[0]!;
// Simulate progress
const interval = setInterval(() => {
setProgress((prev) => {
if (prev >= 90) {
clearInterval(interval);
return prev;
}
return prev + 10;
});
}, 200);
if (downloadFormat === "individual") {
// Download individual files
void downloadIndividualModels({
variables: {
directoryId: directory,
selectedModels,
includeLabels,
},
})
.then(async (result) => {
clearInterval(interval);
setProgress(100);
if (result.data?.downloadIndividualModels) {
const files = result.data.downloadIndividualModels as {
fileName: string;
base64Data: string;
}[];
// Trigger downloads sequentially with a 200ms gap between each.
// Chromium blocks programmatic downloads when more than ~10 are
// fired simultaneously; a sequential approach avoids that entirely.
// eslint-disable-next-line no-restricted-syntax
for (const file of files) {
legacyDownload(
Buffer.from(file.base64Data, "base64"),
file.fileName,
"application/octet-stream"
);
// eslint-disable-next-line no-await-in-loop
await delay(200);
}
void message.success(
t(`{{count}} files downloaded`, { count: files.length })
);
setTimeout(() => {
setCreating(false);
setProgress(0);
setSelectedModels([]);
}, 1000);
}
})
.catch((e: Error) => {
clearInterval(interval);
void message.error(`${t(`Error creating backup`)}: ${e.message}`);
setCreating(false);
setProgress(0);
});
} else {
// Download as .etx or .zip
const extension = downloadFormat === "etx" ? "etx" : "zip";
const fileName = `backup-${timestamp}.${extension}`;
// For .etx format, always include labels when the radio has them (Companion compatibility)
const { hasLabels } = directoryData as { hasLabels?: boolean };
const effectiveIncludeLabels =
downloadFormat === "etx" && hasLabels ? true : includeLabels;
void createBackup({
variables: {
directoryId: directory,
selectedModels,
fileName,
includeLabels: effectiveIncludeLabels,
},
})
.then((result) => {
clearInterval(interval);
setProgress(100);
if (result.data?.createBackupFromSdcard) {
const { base64Data, name } = result.data.createBackupFromSdcard;
// Download the file
const blob = new Blob([Buffer.from(base64Data, "base64")], {
type: "application/octet-stream",
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = name;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
void message.success(t(`Backup created successfully`));
setTimeout(() => {
setCreating(false);
setProgress(0);
setSelectedModels([]);
}, 1000);
}
})
.catch((e: Error) => {
clearInterval(interval);
void message.error(`${t(`Error creating backup`)}: ${e.message}`);
setCreating(false);
setProgress(0);
});
}
};
const sdCardSelectionArea = (
<Card size="small">
<div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
{!directory ? (
<>
<FolderOpenTwoTone
style={{
fontSize: "32px",
opacity: notAvailable ? "0.2" : undefined,
}}
/>
<div style={{ flex: 1 }}>
<Typography.Text strong>{t(`SD Card`)}</Typography.Text>
<div>
<Typography.Text type="secondary" style={{ fontSize: "12px" }}>
{t(`Select your SD Card to create a backup`)}
</Typography.Text>
</div>
</div>
<Tooltip
trigger={notAvailable ? ["hover", "click"] : []}
placement="left"
title={t(`This feature is not supported by your browser`)}
>
<Button
type="primary"
disabled={notAvailable || creating}
onClick={handleSelectDirectory}
>
{t(`Select SD Card`)}
</Button>
</Tooltip>
</>
) : (
<>
<CheckCircleOutlined
style={{
fontSize: "32px",
color: "#52c41a",
}}
/>
<div style={{ flex: 1 }}>
<Typography.Text strong>
{directoryData?.name ?? t(`SD Card`)}
</Typography.Text>
<div>
<Typography.Text type="secondary" style={{ fontSize: "12px" }}>
{availableModels.length > 0
? `${availableModels.length} ${t(`models available`)}`
: t(`No models found`)}
</Typography.Text>
</div>
</div>
<Button
size="small"
disabled={creating}
onClick={handleSelectDirectory}
>
{t(`Change`)}
</Button>
</>
)}
</div>
</Card>
);
return (
<div
style={{
display: "flex",
flexDirection: "column",
gap: "16px",
width: "100%",
padding: "8px 0",
}}
>
{sdCardSelectionArea}
{directory && availableModels.length > 0 && (
<Card style={{ width: "100%" }} title={t(`Select models to backup`)}>
<div style={{ marginBottom: "16px" }}>
<Checkbox
checked={
selectedModels.length === availableModels.length &&
availableModels.length > 0
}
indeterminate={
selectedModels.length > 0 &&
selectedModels.length < availableModels.length
}
onChange={(e) => handleSelectAll(e.target.checked)}
>
{t(`Select all`)}
</Checkbox>
</div>
<List
bordered
style={{ maxHeight: "300px", overflowY: "auto" }}
dataSource={availableModels}
renderItem={(model: ModelInfo) => (
<List.Item>
<Checkbox
checked={selectedModels.includes(model.fileName)}
onChange={(e) =>
handleModelToggle(model.fileName, e.target.checked)
}
>
{model.displayName}
</Checkbox>
</List.Item>
)}
/>
<div style={{ marginTop: "16px" }}>
<Typography.Text strong>{t(`Export format`)}</Typography.Text>
<Radio.Group
value={downloadFormat}
onChange={(e: RadioChangeEvent) => {
const value = e.target.value as "etx" | "zip" | "individual";
setDownloadFormat(value);
}}
style={{ display: "block", marginTop: "8px" }}
>
<Space direction="vertical">
<Radio value="etx">
{t(`Single .etx file (EdgeTX backup)`)}
</Radio>
<Radio value="zip">{t(`Single .zip file`)}</Radio>
<Radio value="individual">{t(`Individual .yml files`)}</Radio>
</Space>
</Radio.Group>
</div>
{(directoryData as { hasLabels?: boolean }).hasLabels && (
<div style={{ marginTop: "16px" }}>
{downloadFormat === "etx" ? (
<Tooltip
title={t(
"labels.yml is always included in .etx backups for Companion compatibility"
)}
>
<Checkbox checked disabled>
{t(`Include labels.yml file`)}
</Checkbox>
</Tooltip>
) : (
<Checkbox
checked={includeLabels}
onChange={(e) => setIncludeLabels(e.target.checked)}
>
{t(`Include labels.yml file`)}
</Checkbox>
)}
</div>
)}
<div style={{ marginTop: "16px" }}>
<Button
type="primary"
icon={<DownloadOutlined />}
onClick={handleCreateBackup}
disabled={selectedModels.length === 0 || creating}
loading={creating}
block
>
{t(`Create backup`)} ({selectedModels.length} {t(`models`)})
</Button>
</div>
{creating && (
<div style={{ marginTop: "16px" }}>
<Typography.Text>{t(`Creating backup...`)}</Typography.Text>
<Progress percent={progress} status="active" />
</div>
)}
</Card>
)}
</div>
);
};
export default BackupCreateFlow;