This repository has been archived by the owner on Nov 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
uploader.basic.api.js
1868 lines (1552 loc) · 70.3 KB
/
uploader.basic.api.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
/*globals qq*/
/**
* Defines the public API for FineUploaderBasic mode.
*/
(function() {
"use strict";
qq.basePublicApi = {
// DEPRECATED - TODO REMOVE IN NEXT MAJOR RELEASE (replaced by addFiles)
addBlobs: function(blobDataOrArray, params, endpoint) {
this.addFiles(blobDataOrArray, params, endpoint);
},
addInitialFiles: function(cannedFileList) {
var self = this;
qq.each(cannedFileList, function(index, cannedFile) {
self._addCannedFile(cannedFile);
});
},
addFiles: function(data, params, endpoint) {
this._maybeHandleIos8SafariWorkaround();
var batchId = this._storedIds.length === 0 ? qq.getUniqueId() : this._currentBatchId,
processBlob = qq.bind(function(blob) {
this._handleNewFile({
blob: blob,
name: this._options.blobs.defaultName
}, batchId, verifiedFiles);
}, this),
processBlobData = qq.bind(function(blobData) {
this._handleNewFile(blobData, batchId, verifiedFiles);
}, this),
processCanvas = qq.bind(function(canvas) {
var blob = qq.canvasToBlob(canvas);
this._handleNewFile({
blob: blob,
name: this._options.blobs.defaultName + ".png"
}, batchId, verifiedFiles);
}, this),
processCanvasData = qq.bind(function(canvasData) {
var normalizedQuality = canvasData.quality && canvasData.quality / 100,
blob = qq.canvasToBlob(canvasData.canvas, canvasData.type, normalizedQuality);
this._handleNewFile({
blob: blob,
name: canvasData.name
}, batchId, verifiedFiles);
}, this),
processFileOrInput = qq.bind(function(fileOrInput) {
if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) {
var files = Array.prototype.slice.call(fileOrInput.files),
self = this;
qq.each(files, function(idx, file) {
self._handleNewFile(file, batchId, verifiedFiles);
});
}
else {
this._handleNewFile(fileOrInput, batchId, verifiedFiles);
}
}, this),
normalizeData = function() {
if (qq.isFileList(data)) {
data = Array.prototype.slice.call(data);
}
data = [].concat(data);
},
self = this,
verifiedFiles = [];
this._currentBatchId = batchId;
if (data) {
normalizeData();
qq.each(data, function(idx, fileContainer) {
if (qq.isFileOrInput(fileContainer)) {
processFileOrInput(fileContainer);
}
else if (qq.isBlob(fileContainer)) {
processBlob(fileContainer);
}
else if (qq.isObject(fileContainer)) {
if (fileContainer.blob && fileContainer.name) {
processBlobData(fileContainer);
}
else if (fileContainer.canvas && fileContainer.name) {
processCanvasData(fileContainer);
}
}
else if (fileContainer.tagName && fileContainer.tagName.toLowerCase() === "canvas") {
processCanvas(fileContainer);
}
else {
self.log(fileContainer + " is not a valid file container! Ignoring!", "warn");
}
});
this.log("Received " + verifiedFiles.length + " files.");
this._prepareItemsForUpload(verifiedFiles, params, endpoint);
}
},
cancel: function(id) {
this._handler.cancel(id);
},
cancelAll: function() {
var storedIdsCopy = [],
self = this;
qq.extend(storedIdsCopy, this._storedIds);
qq.each(storedIdsCopy, function(idx, storedFileId) {
self.cancel(storedFileId);
});
this._handler.cancelAll();
},
clearStoredFiles: function() {
this._storedIds = [];
},
continueUpload: function(id) {
var uploadData = this._uploadData.retrieve({id: id});
if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
return false;
}
if (uploadData.status === qq.status.PAUSED) {
this.log(qq.format("Paused file ID {} ({}) will be continued. Not paused.", id, this.getName(id)));
this._uploadFile(id);
return true;
}
else {
this.log(qq.format("Ignoring continue for file ID {} ({}). Not paused.", id, this.getName(id)), "error");
}
return false;
},
deleteFile: function(id) {
return this._onSubmitDelete(id);
},
// TODO document?
doesExist: function(fileOrBlobId) {
return this._handler.isValid(fileOrBlobId);
},
// Generate a variable size thumbnail on an img or canvas,
// returning a promise that is fulfilled when the attempt completes.
// Thumbnail can either be based off of a URL for an image returned
// by the server in the upload response, or the associated `Blob`.
drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) {
var promiseToReturn = new qq.Promise(),
fileOrUrl, options;
if (this._imageGenerator) {
fileOrUrl = this._thumbnailUrls[fileId];
options = {
customResizeFunction: customResizeFunction,
maxSize: maxSize > 0 ? maxSize : null,
scale: maxSize > 0
};
// If client-side preview generation is possible
// and we are not specifically looking for the image URl returned by the server...
if (!fromServer && qq.supportedFeatures.imagePreviews) {
fileOrUrl = this.getFile(fileId);
}
/* jshint eqeqeq:false,eqnull:true */
if (fileOrUrl == null) {
promiseToReturn.failure({container: imgOrCanvas, error: "File or URL not found."});
}
else {
this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(
function success(modifiedContainer) {
promiseToReturn.success(modifiedContainer);
},
function failure(container, reason) {
promiseToReturn.failure({container: container, error: reason || "Problem generating thumbnail"});
}
);
}
}
else {
promiseToReturn.failure({container: imgOrCanvas, error: "Missing image generator module"});
}
return promiseToReturn;
},
getButton: function(fileId) {
return this._getButton(this._buttonIdsForFileIds[fileId]);
},
getEndpoint: function(fileId) {
return this._endpointStore.get(fileId);
},
getFile: function(fileOrBlobId) {
return this._handler.getFile(fileOrBlobId) || null;
},
getInProgress: function() {
return this._uploadData.retrieve({
status: [
qq.status.UPLOADING,
qq.status.UPLOAD_RETRYING,
qq.status.QUEUED
]
}).length;
},
getName: function(id) {
return this._uploadData.retrieve({id: id}).name;
},
// Parent ID for a specific file, or null if this is the parent, or if it has no parent.
getParentId: function(id) {
var uploadDataEntry = this.getUploads({id: id}),
parentId = null;
if (uploadDataEntry) {
if (uploadDataEntry.parentId !== undefined) {
parentId = uploadDataEntry.parentId;
}
}
return parentId;
},
getResumableFilesData: function() {
return this._handler.getResumableFilesData();
},
getSize: function(id) {
return this._uploadData.retrieve({id: id}).size;
},
getNetUploads: function() {
return this._netUploaded;
},
getRemainingAllowedItems: function() {
var allowedItems = this._currentItemLimit;
if (allowedItems > 0) {
return allowedItems - this._netUploadedOrQueued;
}
return null;
},
getUploads: function(optionalFilter) {
return this._uploadData.retrieve(optionalFilter);
},
getUuid: function(id) {
return this._uploadData.retrieve({id: id}).uuid;
},
log: function(str, level) {
if (this._options.debug && (!level || level === "info")) {
qq.log("[Fine Uploader " + qq.version + "] " + str);
}
else if (level && level !== "info") {
qq.log("[Fine Uploader " + qq.version + "] " + str, level);
}
},
pauseUpload: function(id) {
var uploadData = this._uploadData.retrieve({id: id});
if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
return false;
}
// Pause only really makes sense if the file is uploading or retrying
if (qq.indexOf([qq.status.UPLOADING, qq.status.UPLOAD_RETRYING], uploadData.status) >= 0) {
if (this._handler.pause(id)) {
this._uploadData.setStatus(id, qq.status.PAUSED);
return true;
}
else {
this.log(qq.format("Unable to pause file ID {} ({}).", id, this.getName(id)), "error");
}
}
else {
this.log(qq.format("Ignoring pause for file ID {} ({}). Not in progress.", id, this.getName(id)), "error");
}
return false;
},
removeFileRef: function(id) {
this._handler.expunge(id);
},
reset: function() {
this.log("Resetting uploader...");
this._handler.reset();
this._storedIds = [];
this._autoRetries = [];
this._retryTimeouts = [];
this._preventRetries = [];
this._thumbnailUrls = [];
qq.each(this._buttons, function(idx, button) {
button.reset();
});
this._paramsStore.reset();
this._endpointStore.reset();
this._netUploadedOrQueued = 0;
this._netUploaded = 0;
this._uploadData.reset();
this._buttonIdsForFileIds = [];
this._pasteHandler && this._pasteHandler.reset();
this._options.session.refreshOnReset && this._refreshSessionData();
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
this._totalProgress && this._totalProgress.reset();
},
retry: function(id) {
return this._manualRetry(id);
},
scaleImage: function(id, specs) {
var self = this;
return qq.Scaler.prototype.scaleImage(id, specs, {
log: qq.bind(self.log, self),
getFile: qq.bind(self.getFile, self),
uploadData: self._uploadData
});
},
setCustomHeaders: function(headers, id) {
this._customHeadersStore.set(headers, id);
},
setDeleteFileCustomHeaders: function(headers, id) {
this._deleteFileCustomHeadersStore.set(headers, id);
},
setDeleteFileEndpoint: function(endpoint, id) {
this._deleteFileEndpointStore.set(endpoint, id);
},
setDeleteFileParams: function(params, id) {
this._deleteFileParamsStore.set(params, id);
},
// Re-sets the default endpoint, an endpoint for a specific file, or an endpoint for a specific button
setEndpoint: function(endpoint, id) {
this._endpointStore.set(endpoint, id);
},
setForm: function(elementOrId) {
this._updateFormSupportAndParams(elementOrId);
},
setItemLimit: function(newItemLimit) {
this._currentItemLimit = newItemLimit;
},
setName: function(id, newName) {
this._uploadData.updateName(id, newName);
},
setParams: function(params, id) {
this._paramsStore.set(params, id);
},
setUuid: function(id, newUuid) {
return this._uploadData.uuidChanged(id, newUuid);
},
uploadStoredFiles: function() {
if (this._storedIds.length === 0) {
this._itemError("noFilesError");
}
else {
this._uploadStoredFiles();
}
}
};
/**
* Defines the private (internal) API for FineUploaderBasic mode.
*/
qq.basePrivateApi = {
// Updates internal state with a file record (not backed by a live file). Returns the assigned ID.
_addCannedFile: function(sessionData) {
var id = this._uploadData.addFile({
uuid: sessionData.uuid,
name: sessionData.name,
size: sessionData.size,
status: qq.status.UPLOAD_SUCCESSFUL
});
sessionData.deleteFileEndpoint && this.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id);
sessionData.deleteFileParams && this.setDeleteFileParams(sessionData.deleteFileParams, id);
if (sessionData.thumbnailUrl) {
this._thumbnailUrls[id] = sessionData.thumbnailUrl;
}
this._netUploaded++;
this._netUploadedOrQueued++;
return id;
},
_annotateWithButtonId: function(file, associatedInput) {
if (qq.isFile(file)) {
file.qqButtonId = this._getButtonId(associatedInput);
}
},
_batchError: function(message) {
this._options.callbacks.onError(null, null, message, undefined);
},
_createDeleteHandler: function() {
var self = this;
return new qq.DeleteFileAjaxRequester({
method: this._options.deleteFile.method.toUpperCase(),
maxConnections: this._options.maxConnections,
uuidParamName: this._options.request.uuidName,
customHeaders: this._deleteFileCustomHeadersStore,
paramsStore: this._deleteFileParamsStore,
endpointStore: this._deleteFileEndpointStore,
cors: this._options.cors,
log: qq.bind(self.log, self),
onDelete: function(id) {
self._onDelete(id);
self._options.callbacks.onDelete(id);
},
onDeleteComplete: function(id, xhrOrXdr, isError) {
self._onDeleteComplete(id, xhrOrXdr, isError);
self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError);
}
});
},
_createPasteHandler: function() {
var self = this;
return new qq.PasteSupport({
targetElement: this._options.paste.targetElement,
callbacks: {
log: qq.bind(self.log, self),
pasteReceived: function(blob) {
self._handleCheckedCallback({
name: "onPasteReceived",
callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob),
onSuccess: qq.bind(self._handlePasteSuccess, self, blob),
identifier: "pasted image"
});
}
}
});
},
_createStore: function(initialValue, _readOnlyValues_) {
var store = {},
catchall = initialValue,
perIdReadOnlyValues = {},
readOnlyValues = _readOnlyValues_,
copy = function(orig) {
if (qq.isObject(orig)) {
return qq.extend({}, orig);
}
return orig;
},
getReadOnlyValues = function() {
if (qq.isFunction(readOnlyValues)) {
return readOnlyValues();
}
return readOnlyValues;
},
includeReadOnlyValues = function(id, existing) {
if (readOnlyValues && qq.isObject(existing)) {
qq.extend(existing, getReadOnlyValues());
}
if (perIdReadOnlyValues[id]) {
qq.extend(existing, perIdReadOnlyValues[id]);
}
};
return {
set: function(val, id) {
/*jshint eqeqeq: true, eqnull: true*/
if (id == null) {
store = {};
catchall = copy(val);
}
else {
store[id] = copy(val);
}
},
get: function(id) {
var values;
/*jshint eqeqeq: true, eqnull: true*/
if (id != null && store[id]) {
values = store[id];
}
else {
values = copy(catchall);
}
includeReadOnlyValues(id, values);
return copy(values);
},
addReadOnly: function(id, values) {
// Only applicable to Object stores
if (qq.isObject(store)) {
// If null ID, apply readonly values to all files
if (id === null) {
if (qq.isFunction(values)) {
readOnlyValues = values;
}
else {
readOnlyValues = readOnlyValues || {};
qq.extend(readOnlyValues, values);
}
}
else {
perIdReadOnlyValues[id] = perIdReadOnlyValues[id] || {};
qq.extend(perIdReadOnlyValues[id], values);
}
}
},
remove: function(fileId) {
return delete store[fileId];
},
reset: function() {
store = {};
perIdReadOnlyValues = {};
catchall = initialValue;
}
};
},
_createUploadDataTracker: function() {
var self = this;
return new qq.UploadData({
getName: function(id) {
return self.getName(id);
},
getUuid: function(id) {
return self.getUuid(id);
},
getSize: function(id) {
return self.getSize(id);
},
onStatusChange: function(id, oldStatus, newStatus) {
self._onUploadStatusChange(id, oldStatus, newStatus);
self._options.callbacks.onStatusChange(id, oldStatus, newStatus);
self._maybeAllComplete(id, newStatus);
if (self._totalProgress) {
setTimeout(function() {
self._totalProgress.onStatusChange(id, oldStatus, newStatus);
}, 0);
}
}
});
},
/**
* Generate a tracked upload button.
*
* @param spec Object containing a required `element` property
* along with optional `multiple`, `accept`, and `folders`.
* @returns {qq.UploadButton}
* @private
*/
_createUploadButton: function(spec) {
var self = this,
acceptFiles = spec.accept || this._options.validation.acceptFiles,
allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions,
button;
function allowMultiple() {
if (qq.supportedFeatures.ajaxUploading) {
// Workaround for bug in iOS7+ (see #1039)
if (self._options.workarounds.iosEmptyVideos &&
qq.ios() &&
!qq.ios6() &&
self._isAllowedExtension(allowedExtensions, ".mov")) {
return false;
}
if (spec.multiple === undefined) {
return self._options.multiple;
}
return spec.multiple;
}
return false;
}
button = new qq.UploadButton({
acceptFiles: acceptFiles,
element: spec.element,
focusClass: this._options.classes.buttonFocus,
folders: spec.folders,
hoverClass: this._options.classes.buttonHover,
ios8BrowserCrashWorkaround: this._options.workarounds.ios8BrowserCrash,
multiple: allowMultiple(),
name: this._options.request.inputName,
onChange: function(input) {
self._onInputChange(input);
},
title: spec.title == null ? this._options.text.fileInputTitle : spec.title
});
this._disposeSupport.addDisposer(function() {
button.dispose();
});
self._buttons.push(button);
return button;
},
_createUploadHandler: function(additionalOptions, namespace) {
var self = this,
lastOnProgress = {},
options = {
debug: this._options.debug,
maxConnections: this._options.maxConnections,
cors: this._options.cors,
paramsStore: this._paramsStore,
endpointStore: this._endpointStore,
chunking: this._options.chunking,
resume: this._options.resume,
blobs: this._options.blobs,
log: qq.bind(self.log, self),
preventRetryParam: this._options.retry.preventRetryResponseProperty,
onProgress: function(id, name, loaded, total) {
if (loaded < 0 || total < 0) {
return;
}
if (lastOnProgress[id]) {
if (lastOnProgress[id].loaded !== loaded || lastOnProgress[id].total !== total) {
self._onProgress(id, name, loaded, total);
self._options.callbacks.onProgress(id, name, loaded, total);
}
}
else {
self._onProgress(id, name, loaded, total);
self._options.callbacks.onProgress(id, name, loaded, total);
}
lastOnProgress[id] = {loaded: loaded, total: total};
},
onComplete: function(id, name, result, xhr) {
delete lastOnProgress[id];
var status = self.getUploads({id: id}).status,
retVal;
// This is to deal with some observed cases where the XHR readyStateChange handler is
// invoked by the browser multiple times for the same XHR instance with the same state
// readyState value. Higher level: don't invoke complete-related code if we've already
// done this.
if (status === qq.status.UPLOAD_SUCCESSFUL || status === qq.status.UPLOAD_FAILED) {
return;
}
retVal = self._onComplete(id, name, result, xhr);
// If the internal `_onComplete` handler returns a promise, don't invoke the `onComplete` callback
// until the promise has been fulfilled.
if (retVal instanceof qq.Promise) {
retVal.done(function() {
self._options.callbacks.onComplete(id, name, result, xhr);
});
}
else {
self._options.callbacks.onComplete(id, name, result, xhr);
}
},
onCancel: function(id, name, cancelFinalizationEffort) {
var promise = new qq.Promise();
self._handleCheckedCallback({
name: "onCancel",
callback: qq.bind(self._options.callbacks.onCancel, self, id, name),
onFailure: promise.failure,
onSuccess: function() {
cancelFinalizationEffort.then(function() {
self._onCancel(id, name);
});
promise.success();
},
identifier: id
});
return promise;
},
onUploadPrep: qq.bind(this._onUploadPrep, this),
onUpload: function(id, name) {
self._onUpload(id, name);
self._options.callbacks.onUpload(id, name);
},
onUploadChunk: function(id, name, chunkData) {
self._onUploadChunk(id, chunkData);
self._options.callbacks.onUploadChunk(id, name, chunkData);
},
onUploadChunkSuccess: function(id, chunkData, result, xhr) {
self._options.callbacks.onUploadChunkSuccess.apply(self, arguments);
},
onResume: function(id, name, chunkData) {
return self._options.callbacks.onResume(id, name, chunkData);
},
onAutoRetry: function(id, name, responseJSON, xhr) {
return self._onAutoRetry.apply(self, arguments);
},
onUuidChanged: function(id, newUuid) {
self.log("Server requested UUID change from '" + self.getUuid(id) + "' to '" + newUuid + "'");
self.setUuid(id, newUuid);
},
getName: qq.bind(self.getName, self),
getUuid: qq.bind(self.getUuid, self),
getSize: qq.bind(self.getSize, self),
setSize: qq.bind(self._setSize, self),
getDataByUuid: function(uuid) {
return self.getUploads({uuid: uuid});
},
isQueued: function(id) {
var status = self.getUploads({id: id}).status;
return status === qq.status.QUEUED ||
status === qq.status.SUBMITTED ||
status === qq.status.UPLOAD_RETRYING ||
status === qq.status.PAUSED;
},
getIdsInProxyGroup: self._uploadData.getIdsInProxyGroup,
getIdsInBatch: self._uploadData.getIdsInBatch
};
qq.each(this._options.request, function(prop, val) {
options[prop] = val;
});
options.customHeaders = this._customHeadersStore;
if (additionalOptions) {
qq.each(additionalOptions, function(key, val) {
options[key] = val;
});
}
return new qq.UploadHandlerController(options, namespace);
},
_fileOrBlobRejected: function(id) {
this._netUploadedOrQueued--;
this._uploadData.setStatus(id, qq.status.REJECTED);
},
_formatSize: function(bytes) {
if (bytes === 0) {
return bytes + this._options.text.sizeSymbols[0];
}
var i = -1;
do {
bytes = bytes / 1000;
i++;
} while (bytes > 999);
return Math.max(bytes, 0.1).toFixed(1) + this._options.text.sizeSymbols[i];
},
// Creates an internal object that tracks various properties of each extra button,
// and then actually creates the extra button.
_generateExtraButtonSpecs: function() {
var self = this;
this._extraButtonSpecs = {};
qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) {
var multiple = extraButtonOptionEntry.multiple,
validation = qq.extend({}, self._options.validation, true),
extraButtonSpec = qq.extend({}, extraButtonOptionEntry);
if (multiple === undefined) {
multiple = self._options.multiple;
}
if (extraButtonSpec.validation) {
qq.extend(validation, extraButtonOptionEntry.validation, true);
}
qq.extend(extraButtonSpec, {
multiple: multiple,
validation: validation
}, true);
self._initExtraButton(extraButtonSpec);
});
},
_getButton: function(buttonId) {
var extraButtonsSpec = this._extraButtonSpecs[buttonId];
if (extraButtonsSpec) {
return extraButtonsSpec.element;
}
else if (buttonId === this._defaultButtonId) {
return this._options.button;
}
},
/**
* Gets the internally used tracking ID for a button.
*
* @param buttonOrFileInputOrFile `File`, `<input type="file">`, or a button container element
* @returns {*} The button's ID, or undefined if no ID is recoverable
* @private
*/
_getButtonId: function(buttonOrFileInputOrFile) {
var inputs, fileInput,
fileBlobOrInput = buttonOrFileInputOrFile;
// We want the reference file/blob here if this is a proxy (a file that will be generated on-demand later)
if (fileBlobOrInput instanceof qq.BlobProxy) {
fileBlobOrInput = fileBlobOrInput.referenceBlob;
}
// If the item is a `Blob` it will never be associated with a button or drop zone.
if (fileBlobOrInput && !qq.isBlob(fileBlobOrInput)) {
if (qq.isFile(fileBlobOrInput)) {
return fileBlobOrInput.qqButtonId;
}
else if (fileBlobOrInput.tagName.toLowerCase() === "input" &&
fileBlobOrInput.type.toLowerCase() === "file") {
return fileBlobOrInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
}
inputs = fileBlobOrInput.getElementsByTagName("input");
qq.each(inputs, function(idx, input) {
if (input.getAttribute("type") === "file") {
fileInput = input;
return false;
}
});
if (fileInput) {
return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
}
}
},
_getNotFinished: function() {
return this._uploadData.retrieve({
status: [
qq.status.UPLOADING,
qq.status.UPLOAD_RETRYING,
qq.status.QUEUED,
qq.status.SUBMITTING,
qq.status.SUBMITTED,
qq.status.PAUSED
]
}).length;
},
// Get the validation options for this button. Could be the default validation option
// or a specific one assigned to this particular button.
_getValidationBase: function(buttonId) {
var extraButtonSpec = this._extraButtonSpecs[buttonId];
return extraButtonSpec ? extraButtonSpec.validation : this._options.validation;
},
_getValidationDescriptor: function(fileWrapper) {
if (fileWrapper.file instanceof qq.BlobProxy) {
return {
name: qq.getFilename(fileWrapper.file.referenceBlob),
size: fileWrapper.file.referenceBlob.size
};
}
return {
name: this.getUploads({id: fileWrapper.id}).name,
size: this.getUploads({id: fileWrapper.id}).size
};
},
_getValidationDescriptors: function(fileWrappers) {
var self = this,
fileDescriptors = [];
qq.each(fileWrappers, function(idx, fileWrapper) {
fileDescriptors.push(self._getValidationDescriptor(fileWrapper));
});
return fileDescriptors;
},
// Allows camera access on either the default or an extra button for iOS devices.
_handleCameraAccess: function() {
if (this._options.camera.ios && qq.ios()) {
var acceptIosCamera = "image/*;capture=camera",
button = this._options.camera.button,
buttonId = button ? this._getButtonId(button) : this._defaultButtonId,
optionRoot = this._options;
// If we are not targeting the default button, it is an "extra" button
if (buttonId && buttonId !== this._defaultButtonId) {
optionRoot = this._extraButtonSpecs[buttonId];
}
// Camera access won't work in iOS if the `multiple` attribute is present on the file input
optionRoot.multiple = false;
// update the options
if (optionRoot.validation.acceptFiles === null) {
optionRoot.validation.acceptFiles = acceptIosCamera;
}
else {
optionRoot.validation.acceptFiles += "," + acceptIosCamera;
}
// update the already-created button
qq.each(this._buttons, function(idx, button) {
if (button.getButtonId() === buttonId) {
button.setMultiple(optionRoot.multiple);
button.setAcceptFiles(optionRoot.acceptFiles);
return false;
}
});
}
},
_handleCheckedCallback: function(details) {
var self = this,
callbackRetVal = details.callback();
if (qq.isGenericPromise(callbackRetVal)) {
this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier);
return callbackRetVal.then(
function(successParam) {
self.log(details.name + " promise success for " + details.identifier);
details.onSuccess(successParam);
},
function() {
if (details.onFailure) {
self.log(details.name + " promise failure for " + details.identifier);
details.onFailure();
}
else {
self.log(details.name + " promise failure for " + details.identifier);
}
});
}
if (callbackRetVal !== false) {