-
-
Notifications
You must be signed in to change notification settings - Fork 350
/
Copy pathFlow.js
656 lines (604 loc) · 17.7 KB
/
Flow.js
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
/**
* @license MIT
*/
import Eventizer from './Eventizer';
import FlowFile from './FlowFile';
import {each} from './tools';
/**
* Flow.js is a library providing multiple simultaneous, stable and
* resumable uploads via the HTML5 File API.
* @param [opts]
* @param {number|Function} [opts.chunkSize]
* @param {bool} [opts.forceChunkSize]
* @param {number} [opts.simultaneousUploads]
* @param {bool} [opts.singleFile]
* @param {string} [opts.fileParameterName]
* @param {number} [opts.progressCallbacksInterval]
* @param {number} [opts.speedSmoothingFactor]
* @param {Object|Function} [opts.query]
* @param {Object|Function} [opts.headers]
* @param {bool} [opts.withCredentials]
* @param {Function} [opts.preprocess]
* @param {string} [opts.method]
* @param {string|Function} [opts.testMethod]
* @param {string|Function} [opts.uploadMethod]
* @param {bool} [opts.prioritizeFirstAndLastChunk]
* @param {bool} [opts.allowDuplicateUploads]
* @param {string|Function} [opts.target]
* @param {number} [opts.maxChunkRetries]
* @param {number} [opts.chunkRetryInterval]
* @param {Array.<number>} [opts.permanentErrors]
* @param {Array.<number>} [opts.successStatuses]
* @param {Function} [opts.initFileFn]
* @param {Function} [opts.readFileFn]
* @param {Function} [opts.generateUniqueIdentifier]
* @constructor
*/
export default class Flow extends Eventizer {
/**
* For the events object:
* - keys: stands for event name
* - values: array list of callbacks
* All keys are lowercased as on() would do.
*/
constructor(opts, events) {
super(events);
/**
* Library version
* @type {string}
*/
Flow.version = '<%= version %>';
/**
* Check if directory upload is supported
* @type {boolean}
*/
this.supportDirectory = (
/Chrome/.test(window.navigator.userAgent) ||
/Firefox/.test(window.navigator.userAgent) ||
/Edge/.test(window.navigator.userAgent)
);
/**
* List of FlowFile objects
* @type {Array.<FlowFile>}
*/
this.files = [];
/**
* Default options for flow.js
* @type {Object}
*/
this.defaults = {
chunkSize: 1024 * 1024,
forceChunkSize: false,
simultaneousUploads: 3,
singleFile: false,
fileParameterName: 'file',
progressCallbacksInterval: 500,
speedSmoothingFactor: 0.1,
query: {},
headers: {},
withCredentials: false,
preprocess: null,
changeRawDataBeforeSend: null,
method: 'multipart',
testMethod: 'GET',
uploadMethod: 'POST',
prioritizeFirstAndLastChunk: false,
allowDuplicateUploads: false,
target: '/',
testChunks: true,
generateUniqueIdentifier: null,
maxChunkRetries: 0,
chunkRetryInterval: null,
permanentErrors: [404, 413, 415, 500, 501],
successStatuses: [200, 201, 202],
onDropStopPropagation: false,
initFileFn: null,
readFileFn: (fileObj, startByte, endByte, fileType, chunk) => fileObj.file.slice(startByte, endByte, fileType),
asyncReadFileFn: null
};
/**
* Current options
* @type {Object}
*/
this.opts = {};
/**
* Current options
* @type {Object}
*/
this.opts = Object.assign({}, this.defaults, opts || {});
// A workaround for using this.method.bind(this) as a (removable) event handler.
// https://stackoverflow.com/questions/11565471
this._onDropBound = null;
}
/**
* On drop event
* @function
* @param {MouseEvent} event
*/
async onDrop(event) {
if (this.opts.onDropStopPropagation) {
event.stopPropagation();
}
event.preventDefault();
var dataTransfer = event.dataTransfer;
if (dataTransfer.items && dataTransfer.items[0] &&
dataTransfer.items[0].webkitGetAsEntry) {
this.webkitReadDataTransfer(event);
} else {
await this.addFiles(dataTransfer.files, event);
}
}
/**
* Prevent default
* @function
* @param {MouseEvent} event
*/
preventEvent(event) {
event.preventDefault();
}
/**
* Read webkit dataTransfer object
* @param event
*/
webkitReadDataTransfer(event) {
var queue = event.dataTransfer.items.length;
var decrement = () => {
if (--queue == 0) {
this.addFiles(files, event);
}
};
var files = [];
for (let item of event.dataTransfer.items) {
var entry = item.webkitGetAsEntry();
if (!entry) {
decrement();
return ;
}
if (entry.isFile) {
// due to a bug in Chrome's File System API impl - #149735
fileReadSuccess(item.getAsFile(), entry.fullPath);
} else {
readDirectory(entry.createReader());
}
}
function readDirectory(reader) {
reader.readEntries((entries) => {
if (entries.length) {
queue += entries.length;
var fullPaths = {};
for (let entry of entries) {
if (entry.isFile) {
fullPaths[entry.name] = entry.fullPath;
entry.file((file) => fileReadSuccess(file, fullPaths[file.name]), readError);
} else if (entry.isDirectory) {
readDirectory(entry.createReader());
}
}
readDirectory(reader);
} else {
decrement();
}
}, readError);
}
function fileReadSuccess(file, fullPath) {
// relative path should not start with "/"
file.relativePath = fullPath.substring(1);
files.push(file);
decrement();
}
function readError(fileError) {
decrement();
throw fileError;
}
}
/**
* Generate unique identifier for a file
* @function
* @param {FlowFile} file
* @returns {string}
*/
generateUniqueIdentifier(file) {
var custom = this.opts.generateUniqueIdentifier;
if (typeof custom === 'function') {
return custom(file);
}
// Some confusion in different versions of Firefox
var relativePath = file.relativePath || file.webkitRelativePath || file.fileName || file.name;
return file.size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, '');
}
/**
* Upload next chunk from the queue
* @function
* @returns {boolean}
* @private
*/
async uploadNextChunk(preventEvents) {
// In some cases (such as videos) it's really handy to upload the first
// and last chunk of a file quickly; this let's the server check the file's
// metadata and determine if there's even a point in continuing.
var found = false;
if (this.opts.prioritizeFirstAndLastChunk) {
for (let file of this.files) {
if (!file.paused && file.chunks.length &&
file.chunks[0].status() === 'pending') {
await file.chunks[0].send();
found = true;
break;
}
if (!file.paused && file.chunks.length > 1 &&
file.chunks[file.chunks.length - 1].status() === 'pending') {
await file.chunks[file.chunks.length - 1].send();
found = true;
break;
}
}
if (found) {
return found;
}
}
// Now, simply look for the next, best thing to upload
outer_loop:
for (let file of this.files) {
if (file.paused) {
continue;
}
for (let chunk of file.chunks) {
if (chunk.status() === 'pending') {
await chunk.send();
found = true;
break outer_loop;
}
}
}
if (found) {
return true;
}
// The are no more outstanding chunks to upload, check if everything is done
var outstanding = false;
for (let file of this.files) {
if (!file.isComplete()) {
outstanding = true;
break;
}
}
if (!outstanding && !preventEvents) {
// All chunks have been uploaded, complete
this.emit('complete');
}
return false;
}
/**
* Assign a browse action to one or more DOM nodes.
* @function
* @param {Element|Array.<Element>} domNodes
* @param {boolean} isDirectory Pass in true to allow directories to
* @param {boolean} singleFile prevent multi file upload
* @param {Object} attributes set custom attributes:
* http://www.w3.org/TR/html-markup/input.file.html#input.file-attributes
* eg: accept: 'image/*'
* be selected (Chrome only).
*/
assignBrowse(domNodes, isDirectory, singleFile, attributes) {
if (domNodes instanceof Element) {
domNodes = [domNodes];
}
each(domNodes, function (domNode) {
var input;
if (domNode.tagName === 'INPUT' && domNode.type === 'file') {
input = domNode;
} else {
input = document.createElement('input');
input.setAttribute('type', 'file');
// display:none - not working in opera 12
Object.assign(input.style, {
visibility: 'hidden',
position: 'absolute',
width: '1px',
height: '1px'
});
// for opera 12 browser, input must be assigned to a document
domNode.appendChild(input);
// https://developer.mozilla.org/en/using_files_from_web_applications)
// event listener is executed two times
// first one - original mouse click event
// second - input.click(), input is inside domNode
domNode.addEventListener('click', function() {
input.click();
}, false);
}
if (!this.opts.singleFile && !singleFile) {
input.setAttribute('multiple', 'multiple');
}
if (isDirectory) {
input.setAttribute('webkitdirectory', 'webkitdirectory');
}
each(attributes, function (value, key) {
input.setAttribute(key, value);
});
// When new files are added, simply append them to the overall list
input.addEventListener('change', async e => {
if (e.target.value) {
input.setAttribute('readonly', 'readonly');
await this.addFiles(e.target.files, e);
e.target.value = '';
input.removeAttribute('readonly');
}
}, false);
}, this);
}
/**
* Assign one or more DOM nodes as a drop target.
* @function
* @param {Element|Array.<Element>} domNodes
*/
assignDrop(domNodes) {
if (typeof domNodes.length === 'undefined') {
domNodes = [domNodes];
}
this._onDropBound = this.onDrop.bind(this);
for (let domNode of domNodes) {
domNode.addEventListener('dragover', this.preventEvent, false);
domNode.addEventListener('dragenter', this.preventEvent, false);
domNode.addEventListener('drop', this._onDropBound, false);
}
}
/**
* Un-assign drop event from DOM nodes
* @function
* @param domNodes
*/
unAssignDrop(domNodes) {
if (typeof domNodes.length === 'undefined') {
domNodes = [domNodes];
}
for (let domNode of domNodes) {
domNode.removeEventListener('dragover', this.preventEvent, false);
domNode.removeEventListener('dragenter', this.preventEvent, false);
domNode.removeEventListener('drop', this._onDropBound, false);
}
}
/**
* Returns a boolean indicating whether or not the instance is currently
* uploading anything.
* @function
* @returns {boolean}
*/
isUploading() {
var uploading = false;
each(this.files, function (file) {
if (file.isUploading()) {
uploading = true;
return false;
}
});
return uploading;
}
/**
* should upload next chunk
* @function
* @returns {boolean|number}
*/
_shouldUploadNext() {
var num = 0;
var should = true;
var simultaneousUploads = this.opts.simultaneousUploads;
each(this.files, function (file) {
each(file.chunks, function(chunk) {
if (chunk.status() === 'uploading') {
num++;
if (num >= simultaneousUploads) {
should = false;
return false;
}
}
});
});
// if should is true then return uploading chunks's length
return should && num;
}
/**
* Start or resume uploading.
* @function
*/
async upload() {
// Make sure we don't start too many uploads at once
var ret = this._shouldUploadNext();
if (ret === false) {
return;
}
// Kick off the queue
this.emit('upload-start');
var started = false;
for (var num = 1; num <= this.opts.simultaneousUploads - ret; num++) {
started = await this.uploadNextChunk(true) || started;
}
if (!started) {
this.emit('complete');
}
}
/**
* Resume uploading.
* @return [<Promise>]
* @function
*/
resume() {
return Promise.all(this.files.filter(file => !file.isComplete()).map(file => file.resume()));
}
/**
* Pause uploading.
* @return [<Promise>]
* @function
*/
pause() {
return Promise.all(this.files.map(file => file.pause()));
}
/**
* Cancel upload of all FlowFile objects and remove them from the list.
* @return [<Promise>]
* @function
*/
cancel() {
return Promise.all(this.files.reverse().map(file => file.cancel()));
}
/**
* Returns a number between 0 and 1 indicating the current upload progress
* of all files.
* @function
* @returns {number}
*/
progress() {
var totalDone = 0;
var totalSize = 0;
// Resume all chunks currently being uploaded
each(this.files, function (file) {
totalDone += file.progress() * file.size;
totalSize += file.size;
});
return totalSize > 0 ? totalDone / totalSize : 0;
}
/**
* A generator to yield files and factor the sync part of the filtering logic used in addFiles
*/
*filterFileList(fileList, event) {
// ie10+
var ie10plus = window.navigator.msPointerEnabled;
for (let file of fileList) {
// https://github.com/flowjs/flow.js/issues/55
if ((ie10plus && file.size === 0) || (file.size % 4096 === 0 && (file.name === '.' || file.fileName === '.'))) {
// console.log(`file ${file.name} empty. skipping`);
continue;
}
var uniqueIdentifier = this.generateUniqueIdentifier(file);
if (!this.opts.allowDuplicateUploads && this.getFromUniqueIdentifier(uniqueIdentifier)) {
// console.log(`file ${file.name} non-unique. skipping`);
continue;
}
yield [file, uniqueIdentifier];
}
}
/**
* Add a HTML5 File object to the list of files.
* @function
* @param {File} file
* @param Any other parameters supported by addFiles.
*
* @return (async) An initialized <FlowFile>.
*/
async addFile(file, ...args) {
return (await this.addFiles([file], ...args))[0];
}
/**
* Add a HTML5 File object to the list of files.
* @function
* @param {FileList|Array} fileList
* @param {Event} [event] event is optional
*
* @return Promise{[<FlowFile>,...]} The promise of getting an array of FlowFile.
*/
async addFiles(fileList, event = null, initFileFn = this.opts.initFileFn) {
let item, file, uniqueIdentifier, flowFiles = [];
const iterator = this.filterFileList(fileList, event);
while ((item = iterator.next()) && !item.done) {
[file, uniqueIdentifier] = item.value;
if (! await this.hook('filter-file', file, event)) {
// console.log(`file ${file.name} filtered-out. skipping`);
continue;
}
let flowFile = new FlowFile(this, file, uniqueIdentifier);
await flowFile.bootstrap(event, initFileFn);
await this.hook('file-added', flowFile, event);
if(flowFile && flowFile.file) {
flowFiles.push(flowFile);
}
}
await this.hook('files-added', flowFiles, event);
flowFiles = flowFiles.filter(flowFile => flowFile && flowFile.file);
for (let file of flowFiles) {
if (this.opts.singleFile && this.files.length > 0) {
await this.removeFile(this.files[0]);
}
this.files.push(file);
}
await this.hook('files-submitted', this.files, event);
return flowFiles;
}
/**
* Cancel upload of a specific FlowFile object from the list.
* @function
* @param {FlowFile} file
*/
async removeFile(file) {
for (var i = this.files.length - 1; i >= 0; i--) {
if (this.files[i] === file) {
this.files.splice(i, 1);
await file.abort();
this.emit('file-removed', file);
if (!this.opts.allowDuplicateUploads) {
break;
}
}
}
}
/**
* Look up a FlowFile object by its unique identifier.
* @function
* @param {string} uniqueIdentifier
* @returns {boolean|FlowFile} false if file was not found
*/
getFromUniqueIdentifier(uniqueIdentifier) {
var ret = false;
each(this.files, function (file) {
if (file.uniqueIdentifier === uniqueIdentifier) {
ret = file;
}
});
return ret;
}
/**
* Returns the total size of all files in bytes.
* @function
* @returns {number}
*/
getSize() {
var totalSize = 0;
each(this.files, function (file) {
totalSize += file.size;
});
return totalSize;
}
/**
* Returns the total size uploaded of all files in bytes.
* @function
* @returns {number}
*/
sizeUploaded() {
var size = 0;
each(this.files, function (file) {
size += file.sizeUploaded();
});
return size;
}
/**
* Returns remaining time to upload all files in seconds. Accuracy is based on average speed.
* If speed is zero, time remaining will be equal to positive infinity `Number.POSITIVE_INFINITY`
* @function
* @returns {number}
*/
timeRemaining() {
var sizeDelta = 0;
var averageSpeed = 0;
each(this.files, function (file) {
if (!file.paused && !file.error) {
sizeDelta += file.size - file.sizeUploaded();
averageSpeed += file.averageSpeed;
}
});
if (sizeDelta && !averageSpeed) {
return Number.POSITIVE_INFINITY;
}
if (!sizeDelta && !averageSpeed) {
return 0;
}
return Math.floor(sizeDelta / averageSpeed);
}
};