forked from coder/code-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.ts
More file actions
358 lines (320 loc) · 10.3 KB
/
upload.ts
File metadata and controls
358 lines (320 loc) · 10.3 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
import { exec } from "child_process";
import { appendFile } from "fs";
import { promisify } from "util";
import { logger } from "@coder/logger";
import { escapePath } from "@coder/protocol";
import { NotificationService, INotificationService, ProgressService, IProgressService, IProgress, Severity } from "./fill/notification";
export interface IURI {
readonly path: string;
readonly fsPath: string;
readonly scheme: string;
}
/**
* Represents an uploadable directory, so we can query for existing files once.
*/
interface IUploadableDirectory {
existingFiles: string[];
filesToUpload: Map<string, File>;
preparePromise?: Promise<void>;
}
/**
* There doesn't seem to be a provided type for entries, so here is an
* incomplete version.
*/
interface IEntry {
name: string;
isFile: boolean;
file: (cb: (file: File) => void) => void;
createReader: () => ({
readEntries: (cb: (entries: Array<IEntry>) => void) => void;
});
}
/**
* Handles file uploads.
*/
export class Upload {
private readonly maxParallelUploads = 100;
private readonly readSize = 32000; // ~32kb max while reading in the file.
private readonly packetSize = 32000; // ~32kb max when writing.
private readonly logger = logger.named("Upload");
private readonly currentlyUploadingFiles = new Map<string, File>();
private readonly queueByDirectory = new Map<string, IUploadableDirectory>();
private progress: IProgress | undefined;
private uploadPromise: Promise<string[]> | undefined;
private resolveUploadPromise: (() => void) | undefined;
private finished = 0;
private uploadedFilePaths = <string[]>[];
private total = 0;
public constructor(
private _notificationService: INotificationService,
private _progressService: IProgressService,
) {}
public set notificationService(service: INotificationService) {
this._notificationService = service;
}
public get notificationService(): INotificationService {
return this._notificationService;
}
public set progressService(service: IProgressService) {
this._progressService = service;
}
public get progressService(): IProgressService {
return this._progressService;
}
/**
* Upload dropped files. This will try to upload everything it can. Errors
* will show via notifications. If an upload operation is ongoing, the files
* will be added to that operation.
*/
public async uploadDropped(event: DragEvent, uploadDir: IURI): Promise<string[]> {
this.addDirectory(uploadDir.path);
await this.queueFiles(event, uploadDir);
this.logger.debug( // -1 so we don't include the uploadDir itself.
`Uploading ${this.queueByDirectory.size - 1} directories and ${this.total} files`,
);
await this.prepareDirectories();
if (!this.uploadPromise) {
this.uploadPromise = this.progressService.start("Uploading files...", (progress) => {
return new Promise((resolve): void => {
this.progress = progress;
this.resolveUploadPromise = (): void => {
const uploaded = this.uploadedFilePaths;
this.uploadPromise = undefined;
this.resolveUploadPromise = undefined;
this.uploadedFilePaths = [];
this.finished = 0;
this.total = 0;
resolve(uploaded);
};
});
}, () => {
this.cancel();
});
}
this.uploadFiles();
return this.uploadPromise;
}
/**
* Cancel all file uploads.
*/
public async cancel(): Promise<void> {
this.currentlyUploadingFiles.clear();
this.queueByDirectory.clear();
}
/**
* Create directories and get existing files.
* On failure, show the error and remove the failed directory from the queue.
*/
private async prepareDirectories(): Promise<void> {
await Promise.all(Array.from(this.queueByDirectory).map(([path, dir]) => {
if (!dir.preparePromise) {
dir.preparePromise = this.prepareDirectory(path, dir);
}
return dir.preparePromise;
}));
}
/**
* Create a directory and get existing files.
* On failure, show the error and remove the directory from the queue.
*/
private async prepareDirectory(path: string, dir: IUploadableDirectory): Promise<void> {
await Promise.all([
promisify(exec)(`mkdir -p ${escapePath(path)}`).catch((error) => {
const message = error.message.toLowerCase();
if (message.includes("file exists")) {
throw new Error(`Unable to create directory at ${path} because a file exists there`);
}
throw new Error(error.message || `Unable to upload ${path}`);
}),
// Only get files, so we don't show an override option that will just
// fail anyway.
promisify(exec)(`find ${escapePath(path)} -maxdepth 1 -not -type d`).then((stdio) => {
dir.existingFiles = stdio.stdout.split("\n");
}),
]).catch((error) => {
this.queueByDirectory.delete(path);
this.notificationService.error(error);
});
}
/**
* Upload as many files as possible. When finished, resolve the upload promise.
*/
private uploadFiles(): void {
const finishFileUpload = (path: string): void => {
++this.finished;
this.currentlyUploadingFiles.delete(path);
this.progress!.report(Math.floor((this.finished / this.total) * 100));
this.uploadFiles();
};
while (this.queueByDirectory.size > 0 && this.currentlyUploadingFiles.size < this.maxParallelUploads) {
const [dirPath, dir] = this.queueByDirectory.entries().next().value;
if (dir.filesToUpload.size === 0) {
this.queueByDirectory.delete(dirPath);
continue;
}
const [filePath, item] = dir.filesToUpload.entries().next().value;
this.currentlyUploadingFiles.set(filePath, item);
dir.filesToUpload.delete(filePath);
this.uploadFile(filePath, item, dir.existingFiles).then(() => {
finishFileUpload(filePath);
}).catch((error) => {
this.notificationService.error(error);
finishFileUpload(filePath);
});
}
if (this.queueByDirectory.size === 0 && this.currentlyUploadingFiles.size === 0) {
this.resolveUploadPromise!();
}
}
/**
* Upload a file.
*/
private async uploadFile(path: string, file: File, existingFiles: string[]): Promise<void> {
if (existingFiles.includes(path)) {
const shouldOverwrite = await new Promise((resolve): void => {
this.notificationService.prompt(
Severity.Error,
`${path} already exists. Overwrite?`,
[{
label: "Yes",
run: (): void => resolve(true),
}, {
label: "No",
run: (): void => resolve(false),
}],
() => resolve(false),
);
});
if (!shouldOverwrite) {
return;
}
}
await new Promise(async (resolve, reject): Promise<void> => {
let readOffset = 0;
const reader = new FileReader();
const seek = (): void => {
const slice = file.slice(readOffset, readOffset + this.readSize);
readOffset += this.readSize;
reader.readAsArrayBuffer(slice);
};
const rm = async (): Promise<void> => {
await promisify(exec)(`rm -f ${escapePath(path)}`);
};
await rm();
const load = async (): Promise<void> => {
const buffer = new Uint8Array(reader.result as ArrayBuffer);
let bufferOffset = 0;
while (bufferOffset <= buffer.length) {
// Got canceled while sending data.
if (!this.currentlyUploadingFiles.has(path)) {
await rm();
return resolve();
}
const data = buffer.slice(bufferOffset, bufferOffset + this.packetSize);
try {
await promisify(appendFile)(path, data);
} catch (error) {
await rm();
const message = error.message.toLowerCase();
if (message.includes("no space")) {
return reject(new Error("You are out of disk space"));
} else if (message.includes("is a directory")) {
return reject(new Error(`Unable to upload ${path} because there is a directory there`));
}
return reject(new Error(error.message || `Unable to upload ${path}`));
}
bufferOffset += this.packetSize;
}
if (readOffset >= file.size) {
this.uploadedFilePaths.push(path);
return resolve();
}
seek();
};
reader.addEventListener("load", load);
seek();
});
}
/**
* Queue files from a drop event. We have to get the files first; we can't do
* it in tandem with uploading or the entries will disappear.
*/
private async queueFiles(event: DragEvent, uploadDir: IURI): Promise<void> {
if (!event.dataTransfer || !event.dataTransfer.items) {
return;
}
const promises: Array<Promise<void>> = [];
for (let i = 0; i < event.dataTransfer.items.length; i++) {
const item = event.dataTransfer.items[i];
if (typeof item.webkitGetAsEntry === "function") {
promises.push(this.traverseItem(item.webkitGetAsEntry(), uploadDir.fsPath).catch(this.notificationService.error));
} else {
const file = item.getAsFile();
if (file) {
this.addFile(uploadDir.fsPath, uploadDir.fsPath + "/" + file.name, file);
}
}
}
await Promise.all(promises);
}
/**
* Traverses an entry and add files to the queue.
*/
private async traverseItem(entry: IEntry, parentPath: string): Promise<void> {
if (entry.isFile) {
return new Promise<void>((resolve): void => {
entry.file((file) => {
this.addFile(
parentPath,
parentPath + "/" + file.name,
file,
);
resolve();
});
});
}
parentPath += "/" + entry.name;
this.addDirectory(parentPath);
await new Promise((resolve): void => {
const promises: Array<Promise<void>> = [];
const dirReader = entry.createReader();
// According to the spec, readEntries() must be called until it calls
// the callback with an empty array.
const readEntries = (): void => {
dirReader.readEntries((entries) => {
if (entries.length === 0) {
Promise.all(promises).then(resolve).catch((error) => {
this.notificationService.error(error);
resolve();
});
} else {
promises.push(...entries.map((child) => this.traverseItem(child, parentPath)));
readEntries();
}
});
};
readEntries();
});
}
/**
* Add a file to the queue.
*/
private addFile(parentPath: string, path: string, file: File): void {
++this.total;
this.addDirectory(parentPath);
this.queueByDirectory.get(parentPath)!.filesToUpload.set(path, file);
}
/**
* Add a directory to the queue.
*/
private addDirectory(path: string): void {
if (!this.queueByDirectory.has(path)) {
this.queueByDirectory.set(path, {
existingFiles: [],
filesToUpload: new Map(),
});
}
}
}
// Global instance.
export const upload = new Upload(new NotificationService(), new ProgressService());