-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileops.ts
More file actions
321 lines (306 loc) · 8.6 KB
/
fileops.ts
File metadata and controls
321 lines (306 loc) · 8.6 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
import { PromptProps } from "@components";
import { BubbleI, ProgressFileI } from "@models";
import Endpoints from "./Endpoints";
import { getCurrentFilesPath } from "./routes";
import { FileI } from "./file";
import { normalizeURL } from "./util";
type PFunc = (prompt?: PromptProps) => void;
type BFunc = (key: string, bubble: BubbleI) => void;
type AddPFunc = (files: ProgressFileI[]) => void;
type UpdatePFunc = (file: ProgressFileI) => void;
/**
* helper function for renaming a file/folder
* @param file the file/folder that should be renamed
* @param setPrompt a dispatcher function for getting the new name
* @param addBubble a dispatcher function for showing errors, if there are any
* @returns a promise which resolves when the rename is done
*/
export function onRename(
file: FileI,
setPrompt: PFunc,
addBubble: BFunc
): Promise<void> {
return new Promise((resolve) => {
if (!file) return;
setPrompt({
fieldName: file.type === "FILE" ? "file name" : "folder name",
initial: file.name,
type: "INPUT",
callback: async (val) => {
if (file.type !== "header") {
const base = normalizeURL(getCurrentFilesPath());
try {
await Endpoints.getInstance().move(base + file.name, base + val);
resolve();
} catch (err) {
addBubble("rename-error", {
title: `Could not rename ${file.type === "FILE" ? "file" : "folder"
}`,
type: "ERROR",
message: `renaming of ${file.name} failed`,
});
resolve();
}
}
},
});
});
}
/**
* helper function for creating a folder
* @param setPrompt dispatcher function for getting the name of the folder
* @param addBubble function for showing errors, if there are any
* @returns a promise which resolves when the folder is created
*/
export function onCreateFolder(
setPrompt: PFunc,
addBubble: BFunc
): Promise<void> {
return new Promise((resolve) => {
setPrompt({
fieldName: "folder name",
initial: "",
type: "INPUT",
callback: async (value: string) => {
try {
await Endpoints.getInstance().mkdir(
normalizeURL(getCurrentFilesPath()) + value
);
} catch (err) {
addBubble("mkdir-error", {
title: `Failed to create directory "${value}"`,
message: err.message,
type: "ERROR",
});
}
resolve();
},
});
});
}
/**
* helper function when multiple files are selected that should be downloaded
* @param selected the selected files to be downloaded
* @returns nothing
*/
export function onFilesDownload(selected: Set<FileI>): void {
if (selected.size <= 0) return;
const url = normalizeURL(getCurrentFilesPath());
const urls = [];
for (const f of selected) {
urls.push(url + f.name);
}
Endpoints.getInstance().getFiles(urls);
}
/**
* helper function for moving files/folders
* @param files the files/folders that should be moved
* @param folder the folder to which they should be moved to
* @param addBubble function to show errors, if there are any
* @returns a promise which resolves when all files were moved
*/
export async function onMove(
files: FileI[],
folder: FileI,
addBubble: BFunc
): Promise<void> {
if (files.length <= 0) return;
const base = normalizeURL(getCurrentFilesPath());
try {
await Promise.all(
files.map((f) =>
Endpoints.getInstance().move(
base + f.name,
`${base}${folder.name}/${f.name}`
)
)
);
} catch (e) {
addBubble("move-error", {
title: "Could not move files/folders",
type: "ERROR",
message: e.msg,
});
}
}
/**
* helper function for deleting files/folders
* @param selected the files/folders that should be deleted
* @param setPrompt prompt for asking the user if he is sure
* @param addBubble function to show errors, if there are any
* @returns a promise which resolves when the files/folders are delted
*/
export function onDelete(
selected: Set<FileI>,
setPrompt: PFunc,
addBubble: BFunc
): Promise<void> {
if (selected.size <= 0) return Promise.resolve();
return new Promise((resolve) => {
setPrompt({
fieldName: "delete",
type: "DELETE",
callback: async (value: string | "true") => {
if (value === "true") {
const files: string[] = [];
for (const file of selected) {
const n = normalizeURL(getCurrentFilesPath(), false, false);
files.push(
(n === "" ? "" : n + "/") + file.name
);
}
try {
await Endpoints.getInstance().delete(files);
} catch (err) {
addBubble("mkdir-error", {
title: `Failed to files/folders"`,
message: err.message,
type: "ERROR",
});
}
}
resolve();
},
});
});
}
/**
* helper function for downloading a selected file
* @param file the selected file that should be downloaded
* @returns nothing
*/
export function onFileDownload(file: FileI): void {
if (!file) return;
const url = normalizeURL(getCurrentFilesPath());
Endpoints.getInstance().getFile(url + file.name, file.name);
}
/**
* helper function for download a selected folder
* @param file the folder that should be downloaded
* @returns nothing
*/
export function onFolderDownload(file: FileI): void {
if (!file) return;
const url = normalizeURL(getCurrentFilesPath());
Endpoints.getInstance().getFiles([url + file.name], `${file.name}.zip`);
}
/**
* helper function for upload dragged in files/folders
* @param entry the file system entry for a file/folder
* @param addBubble function to show errors, if there are any
* @param getFolder function to update the folder view of the user
* @param addProgress function to add a file to the upload progress status
* @param updateProgress function to update the upload status of a file
* @param relativePath the relativePath (for nested directories)
* @returns a promise which resolves when all files/folders are uploaded/created
*/
export async function onFileUpload(
entry: FileSystemEntry | null,
addBubble: BFunc,
getFolder: () => void,
addProgress: AddPFunc,
updateProgress: UpdatePFunc,
relativePath?: string,
): Promise<void> {
if (!entry) return;
const base = normalizeURL(getCurrentFilesPath(), false, false) === "" ? "" : normalizeURL(getCurrentFilesPath(), true, false);
const folder = `${base}${relativePath ? relativePath + "/" : ""}`;
try {
if (entry.isDirectory) {
const dir = entry as FileSystemDirectoryEntry;
await Endpoints.getInstance().mkdir(`${folder}${entry.name}`);
const files = await listFilesInDirectory(dir);
if (normalizeURL(folder, false, true) === normalizeURL(base, false, true)) {
getFolder();
}
await Promise.all(
files.map((f) =>
onFileUpload(
f,
addBubble,
getFolder,
addProgress,
updateProgress,
(relativePath ? relativePath + "/" : "") + dir.name
)
)
);
} else if (entry.isFile) {
const fileEntry = entry as FileSystemFileEntry;
const file = await getFile(fileEntry);
return new Promise((resolve) => {
addProgress([{
cwd: folder,
name: file.name,
progress: 0,
total: file.size
}])
Endpoints.getInstance().uploadFile(file, folder, (e) => // upload progress as percentage
updateProgress({
cwd: folder,
name: file.name,
progress: e.loaded,
total: e.total
})
, () => {
updateProgress({
cwd: folder,
name: file.name,
progress: file.size,
total: file.size
})
if (normalizeURL(folder, false, true) === normalizeURL(base, false, true)) {
getFolder();
}
resolve();
}, () => {
addBubble(`upload-error-${file.name}`, {
title: `Could not upload ${file.name}`,
type: "ERROR",
})
resolve()
});
})
}
} catch (e) {
addBubble(`file-error-${entry.name}`, {
title: `Could not upload ${entry.name}`,
type: "ERROR",
message: e.msg,
});
}
}
/**
* a wrapper function for the FileSystemFileEntry.file() function
* @param item the file systementry which should be converted
* @returns a promise which resolves with the file object
*/
function getFile(item: FileSystemFileEntry): Promise<File> {
return new Promise((resolve, reject) => {
item.file((f) => resolve(f), reject);
});
}
/**
* gets all files/folders in a folder
* @param dir the folder that should be listed
* @returns a promise with the contents of a directory
*/
function listFilesInDirectory(
dir: FileSystemDirectoryEntry
): Promise<FileSystemEntry[]> {
return new Promise((resolve, reject) => {
const r = dir.createReader();
const files: FileSystemEntry[] = [];
const doBatch = () => {
r.readEntries((entries) => {
if (entries.length > 0) {
entries.forEach((e) => files.push(e));
doBatch();
} else {
resolve(files);
}
}, reject);
};
doBatch();
});
}