-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtusuploader.js
8039 lines (7142 loc) · 226 KB
/
tusuploader.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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var TusUploader = (function () {
'use strict';
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
}
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var tus = createCommonjsModule(function (module, exports) {
(function(f){{module.exports=f();}})(function(){return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof commonjsRequire=="function"&&commonjsRequire;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r);}return n[o].exports}var i=typeof commonjsRequire=="function"&&commonjsRequire;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = fingerprint;
var _isReactNative = _dereq_("./isReactNative");
var _isReactNative2 = _interopRequireDefault(_isReactNative);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Generate a fingerprint for a file which will be used the store the endpoint
*
* @param {File} file
* @param {Object} options
* @param {Function} callback
*/
function fingerprint(file, options, callback) {
if ((0, _isReactNative2.default)()) {
return callback(null, reactNativeFingerprint(file, options));
}
return callback(null, ["tus-br", file.name, file.type, file.size, file.lastModified, options.endpoint].join("-"));
}
function reactNativeFingerprint(file, options) {
var exifHash = file.exif ? hashCode(JSON.stringify(file.exif)) : "noexif";
return ["tus-rn", file.name || "noname", file.size || "nosize", exifHash, options.endpoint].join("/");
}
function hashCode(str) {
// from https://stackoverflow.com/a/8831937/151666
var hash = 0;
if (str.length === 0) {
return hash;
}
for (var i = 0; i < str.length; i++) {
var char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
},{"./isReactNative":3}],2:[function(_dereq_,module,exports){
Object.defineProperty(exports, "__esModule", {
value: true
});
var isCordova = function isCordova() {
return typeof window != "undefined" && (typeof window.PhoneGap != "undefined" || typeof window.Cordova != "undefined" || typeof window.cordova != "undefined");
};
exports.default = isCordova;
},{}],3:[function(_dereq_,module,exports){
Object.defineProperty(exports, "__esModule", {
value: true
});
var isReactNative = function isReactNative() {
return typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
};
exports.default = isReactNative;
},{}],4:[function(_dereq_,module,exports){
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* readAsByteArray converts a File object to a Uint8Array.
* This function is only used on the Apache Cordova platform.
* See https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html#read-a-file
*/
function readAsByteArray(chunk, callback) {
var reader = new FileReader();
reader.onload = function () {
callback(null, new Uint8Array(reader.result));
};
reader.onerror = function (err) {
callback(err);
};
reader.readAsArrayBuffer(chunk);
}
exports.default = readAsByteArray;
},{}],5:[function(_dereq_,module,exports){
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newRequest = newRequest;
exports.resolveUrl = resolveUrl;
var _urlParse = _dereq_("url-parse");
var _urlParse2 = _interopRequireDefault(_urlParse);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function newRequest() {
return new window.XMLHttpRequest();
} /* global window */
function resolveUrl(origin, link) {
return new _urlParse2.default(link, origin).toString();
}
},{"url-parse":16}],6:[function(_dereq_,module,exports){
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.getSource = getSource;
var _isReactNative = _dereq_("./isReactNative");
var _isReactNative2 = _interopRequireDefault(_isReactNative);
var _uriToBlob = _dereq_("./uriToBlob");
var _uriToBlob2 = _interopRequireDefault(_uriToBlob);
var _isCordova = _dereq_("./isCordova");
var _isCordova2 = _interopRequireDefault(_isCordova);
var _readAsByteArray = _dereq_("./readAsByteArray");
var _readAsByteArray2 = _interopRequireDefault(_readAsByteArray);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var FileSource = function () {
function FileSource(file) {
_classCallCheck(this, FileSource);
this._file = file;
this.size = file.size;
}
_createClass(FileSource, [{
key: "slice",
value: function slice(start, end, callback) {
// In Apache Cordova applications, a File must be resolved using
// FileReader instances, see
// https://cordova.apache.org/docs/en/8.x/reference/cordova-plugin-file/index.html#read-a-file
if ((0, _isCordova2.default)()) {
(0, _readAsByteArray2.default)(this._file.slice(start, end), function (err, chunk) {
if (err) return callback(err);
callback(null, chunk);
});
return;
}
callback(null, this._file.slice(start, end));
}
}, {
key: "close",
value: function close() {}
}]);
return FileSource;
}();
var StreamSource = function () {
function StreamSource(reader, chunkSize) {
_classCallCheck(this, StreamSource);
this._chunkSize = chunkSize;
this._buffer = undefined;
this._bufferOffset = 0;
this._reader = reader;
this._done = false;
}
_createClass(StreamSource, [{
key: "slice",
value: function slice(start, end, callback) {
if (start < this._bufferOffset) {
callback(new Error("Requested data is before the reader's current offset"));
return;
}
return this._readUntilEnoughDataOrDone(start, end, callback);
}
}, {
key: "_readUntilEnoughDataOrDone",
value: function _readUntilEnoughDataOrDone(start, end, callback) {
var _this = this;
var hasEnoughData = end <= this._bufferOffset + len(this._buffer);
if (this._done || hasEnoughData) {
var value = this._getDataFromBuffer(start, end);
callback(null, value, value == null ? this._done : false);
return;
}
this._reader.read().then(function (_ref) {
var value = _ref.value,
done = _ref.done;
if (done) {
_this._done = true;
} else if (_this._buffer === undefined) {
_this._buffer = value;
} else {
_this._buffer = concat(_this._buffer, value);
}
_this._readUntilEnoughDataOrDone(start, end, callback);
}).catch(function (err) {
callback(new Error("Error during read: " + err));
});
}
}, {
key: "_getDataFromBuffer",
value: function _getDataFromBuffer(start, end) {
// Remove data from buffer before `start`.
// Data might be reread from the buffer if an upload fails, so we can only
// safely delete data when it comes *before* what is currently being read.
if (start > this._bufferOffset) {
this._buffer = this._buffer.slice(start - this._bufferOffset);
this._bufferOffset = start;
}
// If the buffer is empty after removing old data, all data has been read.
var hasAllDataBeenRead = len(this._buffer) === 0;
if (this._done && hasAllDataBeenRead) {
return null;
}
// We already removed data before `start`, so we just return the first
// chunk from the buffer.
return this._buffer.slice(0, end - start);
}
}, {
key: "close",
value: function close() {
if (this._reader.cancel) {
this._reader.cancel();
}
}
}]);
return StreamSource;
}();
function len(blobOrArray) {
if (blobOrArray === undefined) return 0;
if (blobOrArray.size !== undefined) return blobOrArray.size;
return blobOrArray.length;
}
/*
Typed arrays and blobs don't have a concat method.
This function helps StreamSource accumulate data to reach chunkSize.
*/
function concat(a, b) {
if (a.concat) {
// Is `a` an Array?
return a.concat(b);
}
if (a instanceof Blob) {
return new Blob([a, b], { type: a.type });
}
if (a.set) {
// Is `a` a typed array?
var c = new a.constructor(a.length + b.length);
c.set(a);
c.set(b, a.length);
return c;
}
throw new Error("Unknown data type");
}
function getSource(input, chunkSize, callback) {
// In React Native, when user selects a file, instead of a File or Blob,
// you usually get a file object {} with a uri property that contains
// a local path to the file. We use XMLHttpRequest to fetch
// the file blob, before uploading with tus.
if ((0, _isReactNative2.default)() && input && typeof input.uri !== "undefined") {
(0, _uriToBlob2.default)(input.uri, function (err, blob) {
if (err) {
return callback(new Error("tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. " + err));
}
callback(null, new FileSource(blob));
});
return;
}
// Since we emulate the Blob type in our tests (not all target browsers
// support it), we cannot use `instanceof` for testing whether the input value
// can be handled. Instead, we simply check is the slice() function and the
// size property are available.
if (typeof input.slice === "function" && typeof input.size !== "undefined") {
callback(null, new FileSource(input));
return;
}
if (typeof input.read === "function") {
chunkSize = +chunkSize;
if (!isFinite(chunkSize)) {
callback(new Error("cannot create source for stream without a finite value for the `chunkSize` option"));
return;
}
callback(null, new StreamSource(input, chunkSize));
return;
}
callback(new Error("source object may only be an instance of File, Blob, or Reader in this environment"));
}
},{"./isCordova":2,"./isReactNative":3,"./readAsByteArray":4,"./uriToBlob":8}],7:[function(_dereq_,module,exports){
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.getStorage = getStorage;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/* global window, localStorage */
var hasStorage = false;
try {
hasStorage = "localStorage" in window;
// Attempt to store and read entries from the local storage to detect Private
// Mode on Safari on iOS (see #49)
var key = "tusSupport";
localStorage.setItem(key, localStorage.getItem(key));
} catch (e) {
// If we try to access localStorage inside a sandboxed iframe, a SecurityError
// is thrown. When in private mode on iOS Safari, a QuotaExceededError is
// thrown (see #49)
if (e.code === e.SECURITY_ERR || e.code === e.QUOTA_EXCEEDED_ERR) {
hasStorage = false;
} else {
throw e;
}
}
var canStoreURLs = exports.canStoreURLs = hasStorage;
var LocalStorage = function () {
function LocalStorage() {
_classCallCheck(this, LocalStorage);
}
_createClass(LocalStorage, [{
key: "setItem",
value: function setItem(key, value, cb) {
cb(null, localStorage.setItem(key, value));
}
}, {
key: "getItem",
value: function getItem(key, cb) {
cb(null, localStorage.getItem(key));
}
}, {
key: "removeItem",
value: function removeItem(key, cb) {
cb(null, localStorage.removeItem(key));
}
}]);
return LocalStorage;
}();
function getStorage() {
return hasStorage ? new LocalStorage() : null;
}
},{}],8:[function(_dereq_,module,exports){
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* uriToBlob resolves a URI to a Blob object. This is used for
* React Native to retrieve a file (identified by a file://
* URI) as a blob.
*/
function uriToBlob(uri, done) {
var xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.onload = function () {
var blob = xhr.response;
done(null, blob);
};
xhr.onerror = function (err) {
done(err);
};
xhr.open("GET", uri);
xhr.send();
}
exports.default = uriToBlob;
},{}],9:[function(_dereq_,module,exports){
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var DetailedError = function (_Error) {
_inherits(DetailedError, _Error);
function DetailedError(error) {
var causingErr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var xhr = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
_classCallCheck(this, DetailedError);
var _this = _possibleConstructorReturn(this, (DetailedError.__proto__ || Object.getPrototypeOf(DetailedError)).call(this, error.message));
_this.originalRequest = xhr;
_this.causingError = causingErr;
var message = error.message;
if (causingErr != null) {
message += ", caused by " + causingErr.toString();
}
if (xhr != null) {
message += ", originated from request (response code: " + xhr.status + ", response text: " + xhr.responseText + ")";
}
_this.message = message;
return _this;
}
return DetailedError;
}(Error);
exports.default = DetailedError;
},{}],10:[function(_dereq_,module,exports){
var _upload = _dereq_("./upload");
var _upload2 = _interopRequireDefault(_upload);
var _storage = _dereq_("./node/storage");
var storage = _interopRequireWildcard(_storage);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* global window */
var defaultOptions = _upload2.default.defaultOptions;
var moduleExport = {
Upload: _upload2.default,
canStoreURLs: storage.canStoreURLs,
defaultOptions: defaultOptions
};
if (typeof window !== "undefined") {
// Browser environment using XMLHttpRequest
var _window = window,
XMLHttpRequest = _window.XMLHttpRequest,
Blob = _window.Blob;
moduleExport.isSupported = XMLHttpRequest && Blob && typeof Blob.prototype.slice === "function";
} else {
// Node.js environment using http module
moduleExport.isSupported = true;
// make FileStorage module available as it will not be set by default.
moduleExport.FileStorage = storage.FileStorage;
}
// The usage of the commonjs exporting syntax instead of the new ECMAScript
// one is actually inteded and prevents weird behaviour if we are trying to
// import this module in another module using Babel.
module.exports = moduleExport;
},{"./node/storage":7,"./upload":11}],11:[function(_dereq_,module,exports){
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* global window */
// We import the files used inside the Node environment which are rewritten
// for browsers using the rules defined in the package.json
var _error = _dereq_("./error");
var _error2 = _interopRequireDefault(_error);
var _extend = _dereq_("extend");
var _extend2 = _interopRequireDefault(_extend);
var _jsBase = _dereq_("js-base64");
var _request = _dereq_("./node/request");
var _source = _dereq_("./node/source");
var _storage = _dereq_("./node/storage");
var _fingerprint = _dereq_("./node/fingerprint");
var _fingerprint2 = _interopRequireDefault(_fingerprint);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var defaultOptions = {
endpoint: null,
fingerprint: _fingerprint2.default,
resume: true,
onProgress: null,
onChunkComplete: null,
onSuccess: null,
onError: null,
headers: {},
chunkSize: Infinity,
withCredentials: false,
uploadUrl: null,
uploadSize: null,
overridePatchMethod: false,
retryDelays: null,
removeFingerprintOnSuccess: false,
uploadLengthDeferred: false,
urlStorage: null,
fileReader: null,
uploadDataDuringCreation: false
};
var Upload = function () {
function Upload(file, options) {
_classCallCheck(this, Upload);
this.options = (0, _extend2.default)(true, {}, defaultOptions, options);
// The storage module used to store URLs
this._storage = this.options.urlStorage;
// The underlying File/Blob object
this.file = file;
// The URL against which the file will be uploaded
this.url = null;
// The underlying XHR object for the current PATCH request
this._xhr = null;
// The fingerpinrt for the current file (set after start())
this._fingerprint = null;
// The offset used in the current PATCH request
this._offset = null;
// True if the current PATCH request has been aborted
this._aborted = false;
// The file's size in bytes
this._size = null;
// The Source object which will wrap around the given file and provides us
// with a unified interface for getting its size and slice chunks from its
// content allowing us to easily handle Files, Blobs, Buffers and Streams.
this._source = null;
// The current count of attempts which have been made. Null indicates none.
this._retryAttempt = 0;
// The timeout's ID which is used to delay the next retry
this._retryTimeout = null;
// The offset of the remote upload before the latest attempt was started.
this._offsetBeforeRetry = 0;
}
_createClass(Upload, [{
key: "start",
value: function start() {
var _this = this;
var file = this.file;
if (!file) {
this._emitError(new Error("tus: no file or stream to upload provided"));
return;
}
if (!this.options.endpoint && !this.options.uploadUrl) {
this._emitError(new Error("tus: neither an endpoint or an upload URL is provided"));
return;
}
if (this.options.resume && this._storage == null) {
this._storage = (0, _storage.getStorage)();
}
if (this._source) {
this._start(this._source);
} else {
var fileReader = this.options.fileReader || _source.getSource;
fileReader(file, this.options.chunkSize, function (err, source) {
if (err) {
_this._emitError(err);
return;
}
_this._source = source;
_this._start(source);
});
}
}
}, {
key: "_start",
value: function _start(source) {
var _this2 = this;
var file = this.file;
// First, we look at the uploadLengthDeferred option.
// Next, we check if the caller has supplied a manual upload size.
// Finally, we try to use the calculated size from the source object.
if (this.options.uploadLengthDeferred) {
this._size = null;
} else if (this.options.uploadSize != null) {
this._size = +this.options.uploadSize;
if (isNaN(this._size)) {
this._emitError(new Error("tus: cannot convert `uploadSize` option into a number"));
return;
}
} else {
this._size = source.size;
if (this._size == null) {
this._emitError(new Error("tus: cannot automatically derive upload's size from input and must be specified manually using the `uploadSize` option"));
return;
}
}
var retryDelays = this.options.retryDelays;
if (retryDelays != null) {
if (Object.prototype.toString.call(retryDelays) !== "[object Array]") {
this._emitError(new Error("tus: the `retryDelays` option must either be an array or null"));
return;
} else {
var errorCallback = this.options.onError;
this.options.onError = function (err) {
// Restore the original error callback which may have been set.
_this2.options.onError = errorCallback;
// We will reset the attempt counter if
// - we were already able to connect to the server (offset != null) and
// - we were able to upload a small chunk of data to the server
var shouldResetDelays = _this2._offset != null && _this2._offset > _this2._offsetBeforeRetry;
if (shouldResetDelays) {
_this2._retryAttempt = 0;
}
var isOnline = true;
if (typeof window !== "undefined" && "navigator" in window && window.navigator.onLine === false) {
isOnline = false;
}
// We only attempt a retry if
// - we didn't exceed the maxium number of retries, yet, and
// - this error was caused by a request or it's response and
// - the error is server error (i.e. no a status 4xx or a 409 or 423) and
// - the browser does not indicate that we are offline
var status = err.originalRequest ? err.originalRequest.status : 0;
var isServerError = !inStatusCategory(status, 400) || status === 409 || status === 423;
var shouldRetry = _this2._retryAttempt < retryDelays.length && err.originalRequest != null && isServerError && isOnline;
if (!shouldRetry) {
_this2._emitError(err);
return;
}
var delay = retryDelays[_this2._retryAttempt++];
_this2._offsetBeforeRetry = _this2._offset;
_this2.options.uploadUrl = _this2.url;
_this2._retryTimeout = setTimeout(function () {
_this2.start();
}, delay);
};
}
}
// Reset the aborted flag when the upload is started or else the
// _startUpload will stop before sending a request if the upload has been
// aborted previously.
this._aborted = false;
// The upload had been started previously and we should reuse this URL.
if (this.url != null) {
this._resumeUpload();
return;
}
// A URL has manually been specified, so we try to resume
if (this.options.uploadUrl != null) {
this.url = this.options.uploadUrl;
this._resumeUpload();
return;
}
// Try to find the endpoint for the file in the storage
if (this._hasStorage()) {
this.options.fingerprint(file, this.options, function (err, fingerprintValue) {
if (err) {
_this2._emitError(err);
return;
}
_this2._fingerprint = fingerprintValue;
_this2._storage.getItem(_this2._fingerprint, function (err, resumedUrl) {
if (err) {
_this2._emitError(err);
return;
}
if (resumedUrl != null) {
_this2.url = resumedUrl;
_this2._resumeUpload();
} else {
_this2._createUpload();
}
});
});
} else {
// An upload has not started for the file yet, so we start a new one
this._createUpload();
}
}
}, {
key: "abort",
value: function abort(shouldTerminate, cb) {
var _this3 = this;
if (this._xhr !== null) {
this._xhr.abort();
this._source.close();
}
this._aborted = true;
if (this._retryTimeout != null) {
clearTimeout(this._retryTimeout);
this._retryTimeout = null;
}
cb = cb || function () {};
if (shouldTerminate) {
Upload.terminate(this.url, this.options, function (err, xhr) {
if (err) {
return cb(err, xhr);
}
_this3._hasStorage() ? _this3._storage.removeItem(_this3._fingerprint, cb) : cb();
});
} else {
cb();
}
}
}, {
key: "_hasStorage",
value: function _hasStorage() {
return this.options.resume && this._storage;
}
}, {
key: "_emitXhrError",
value: function _emitXhrError(xhr, err, causingErr) {
this._emitError(new _error2.default(err, causingErr, xhr));
}
}, {
key: "_emitError",
value: function _emitError(err) {
if (typeof this.options.onError === "function") {
this.options.onError(err);
} else {
throw err;
}
}
}, {
key: "_emitSuccess",
value: function _emitSuccess() {
if (typeof this.options.onSuccess === "function") {
this.options.onSuccess();
}
}
/**
* Publishes notification when data has been sent to the server. This
* data may not have been accepted by the server yet.
* @param {number} bytesSent Number of bytes sent to the server.
* @param {number} bytesTotal Total number of bytes to be sent to the server.
*/
}, {
key: "_emitProgress",
value: function _emitProgress(bytesSent, bytesTotal) {
if (typeof this.options.onProgress === "function") {
this.options.onProgress(bytesSent, bytesTotal);
}
}
/**
* Publishes notification when a chunk of data has been sent to the server
* and accepted by the server.
* @param {number} chunkSize Size of the chunk that was accepted by the
* server.
* @param {number} bytesAccepted Total number of bytes that have been
* accepted by the server.
* @param {number} bytesTotal Total number of bytes to be sent to the server.
*/
}, {
key: "_emitChunkComplete",
value: function _emitChunkComplete(chunkSize, bytesAccepted, bytesTotal) {
if (typeof this.options.onChunkComplete === "function") {
this.options.onChunkComplete(chunkSize, bytesAccepted, bytesTotal);
}
}
/**
* Set the headers used in the request and the withCredentials property
* as defined in the options
*
* @param {XMLHttpRequest} xhr
*/
}, {
key: "_setupXHR",
value: function _setupXHR(xhr) {
this._xhr = xhr;
setupXHR(xhr, this.options);
}
/**
* Create a new upload using the creation extension by sending a POST
* request to the endpoint. After successful creation the file will be
* uploaded
*
* @api private
*/
}, {
key: "_createUpload",
value: function _createUpload() {
var _this4 = this;
if (!this.options.endpoint) {
this._emitError(new Error("tus: unable to create upload because no endpoint is provided"));
return;
}
var xhr = (0, _request.newRequest)();
xhr.open("POST", this.options.endpoint, true);
xhr.onload = function () {
if (!inStatusCategory(xhr.status, 200)) {
_this4._emitXhrError(xhr, new Error("tus: unexpected response while creating upload"));
return;
}
var location = xhr.getResponseHeader("Location");
if (location == null) {
_this4._emitXhrError(xhr, new Error("tus: invalid or missing Location header"));
return;
}
_this4.url = (0, _request.resolveUrl)(_this4.options.endpoint, location);
if (_this4._size === 0) {
// Nothing to upload and file was successfully created
_this4._emitSuccess();
_this4._source.close();
return;
}
if (_this4._hasStorage()) {
_this4._storage.setItem(_this4._fingerprint, _this4.url, function (err) {
if (err) {
_this4._emitError(err);
}
});
}
if (_this4.options.uploadDataDuringCreation) {
_this4._handleUploadResponse(xhr);
} else {
_this4._offset = 0;
_this4._startUpload();
}
};
xhr.onerror = function (err) {
_this4._emitXhrError(xhr, new Error("tus: failed to create upload"), err);
};
this._setupXHR(xhr);
if (this.options.uploadLengthDeferred) {
xhr.setRequestHeader("Upload-Defer-Length", 1);
} else {
xhr.setRequestHeader("Upload-Length", this._size);
}
// Add metadata if values have been added
var metadata = encodeMetadata(this.options.metadata);
if (metadata !== "") {
xhr.setRequestHeader("Upload-Metadata", metadata);
}
if (this.options.uploadDataDuringCreation && !this.options.uploadLengthDeferred) {
this._offset = 0;
this._addChunkToRequest(xhr);
} else {
xhr.send(null);
}
}
/*
* Try to resume an existing upload. First a HEAD request will be sent
* to retrieve the offset. If the request fails a new upload will be
* created. In the case of a successful response the file will be uploaded.
*
* @api private
*/
}, {
key: "_resumeUpload",
value: function _resumeUpload() {
var _this5 = this;
var xhr = (0, _request.newRequest)();
xhr.open("HEAD", this.url, true);
xhr.onload = function () {
if (!inStatusCategory(xhr.status, 200)) {
if (_this5._hasStorage() && inStatusCategory(xhr.status, 400)) {
// Remove stored fingerprint and corresponding endpoint,
// on client errors since the file can not be found
_this5._storage.removeItem(_this5._fingerprint, function (err) {
if (err) {
_this5._emitError(err);
}
});
}
// If the upload is locked (indicated by the 423 Locked status code), we
// emit an error instead of directly starting a new upload. This way the
// retry logic can catch the error and will retry the upload. An upload
// is usually locked for a short period of time and will be available
// afterwards.
if (xhr.status === 423) {
_this5._emitXhrError(xhr, new Error("tus: upload is currently locked; retry later"));
return;
}