neofiles 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (32) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +1 -0
  3. data/README.md +417 -0
  4. data/Rakefile +40 -0
  5. data/app/assets/images/neofiles/loading.gif +0 -0
  6. data/app/assets/images/neofiles/swf-thumb-100x100.png +0 -0
  7. data/app/assets/images/neofiles/watermark.png +0 -0
  8. data/app/assets/javascripts/neofiles/index.js.coffee +3 -0
  9. data/app/assets/javascripts/neofiles/jquery.fileupload.js +1128 -0
  10. data/app/assets/javascripts/neofiles/jquery.iframe-transport.js +172 -0
  11. data/app/assets/javascripts/neofiles/jquery.neofiles.js.coffee +191 -0
  12. data/app/assets/stylesheets/neofiles/index.css.scss +3 -0
  13. data/app/assets/stylesheets/neofiles/neofiles.css.scss +149 -0
  14. data/app/controllers/concerns/neofiles/not_found.rb +21 -0
  15. data/app/controllers/neofiles/admin_controller.rb +228 -0
  16. data/app/controllers/neofiles/admin_test_controller.rb +5 -0
  17. data/app/controllers/neofiles/files_controller.rb +28 -0
  18. data/app/controllers/neofiles/images_controller.rb +130 -0
  19. data/app/helpers/neofiles/neofiles_helper.rb +188 -0
  20. data/app/models/neofiles/file.rb +319 -0
  21. data/app/models/neofiles/file_chunk.rb +18 -0
  22. data/app/models/neofiles/image.rb +119 -0
  23. data/app/models/neofiles/swf.rb +45 -0
  24. data/app/views/neofiles/admin/_file_compact.html.haml +85 -0
  25. data/app/views/neofiles/admin/file_compact.html.haml +1 -0
  26. data/app/views/neofiles/admin_test/file_compact.erb +7 -0
  27. data/config/locales/ru.yml +21 -0
  28. data/config/routes.rb +1 -0
  29. data/lib/neofiles.rb +94 -0
  30. data/lib/neofiles/engine.rb +33 -0
  31. data/lib/neofiles/version.rb +3 -0
  32. metadata +131 -0
@@ -0,0 +1,3 @@
1
+ #= require ./jquery.iframe-transport
2
+ #= require ./jquery.fileupload
3
+ #= require ./jquery.neofiles
@@ -0,0 +1,1128 @@
1
+ /*
2
+ * jQuery File Upload Plugin 5.18
3
+ * https://github.com/blueimp/jQuery-File-Upload
4
+ *
5
+ * Copyright 2010, Sebastian Tschan
6
+ * https://blueimp.net
7
+ *
8
+ * Licensed under the MIT license:
9
+ * http://www.opensource.org/licenses/MIT
10
+ */
11
+
12
+ /*jslint nomen: true, unparam: true, regexp: true */
13
+ /*global define, window, document, Blob, FormData, location */
14
+
15
+ (function (factory) {
16
+ 'use strict';
17
+ // Browser globals:
18
+ factory(window.jQuery);
19
+ }(function ($) {
20
+ 'use strict';
21
+
22
+ // The FileReader API is not actually used, but works as feature detection,
23
+ // as e.g. Safari supports XHR file uploads via the FormData API,
24
+ // but not non-multipart XHR file uploads:
25
+ $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader);
26
+ $.support.xhrFormDataFileUpload = !!window.FormData;
27
+
28
+ // The fileupload widget listens for change events on file input fields defined
29
+ // via fileInput setting and paste or drop events of the given dropZone.
30
+ // In addition to the default jQuery Widget methods, the fileupload widget
31
+ // exposes the "add" and "send" methods, to add or directly send files using
32
+ // the fileupload API.
33
+ // By default, files added via file input selection, paste, drag & drop or
34
+ // "add" method are uploaded immediately, but it is possible to override
35
+ // the "add" callback option to queue file uploads.
36
+ $.widget('blueimp.fileupload', {
37
+
38
+ options: {
39
+ // The namespace used for event handler binding on the fileInput,
40
+ // dropZone and pasteZone document nodes.
41
+ // If not set, the name of the widget ("fileupload") is used.
42
+ namespace: undefined,
43
+ // The drop target element(s), by the default the complete document.
44
+ // Set to null to disable drag & drop support:
45
+ dropZone: $(document),
46
+ // The paste target element(s), by the default the complete document.
47
+ // Set to null to disable paste support:
48
+ pasteZone: $(document),
49
+ // The file input field(s), that are listened to for change events.
50
+ // If undefined, it is set to the file input fields inside
51
+ // of the widget element on plugin initialization.
52
+ // Set to null to disable the change listener.
53
+ fileInput: undefined,
54
+ // By default, the file input field is replaced with a clone after
55
+ // each input field change event. This is required for iframe transport
56
+ // queues and allows change events to be fired for the same file
57
+ // selection, but can be disabled by setting the following option to false:
58
+ replaceFileInput: true,
59
+ // The parameter name for the file form data (the request argument name).
60
+ // If undefined or empty, the name property of the file input field is
61
+ // used, or "files[]" if the file input name property is also empty,
62
+ // can be a string or an array of strings:
63
+ paramName: undefined,
64
+ // By default, each file of a selection is uploaded using an individual
65
+ // request for XHR type uploads. Set to false to upload file
66
+ // selections in one request each:
67
+ singleFileUploads: true,
68
+ // To limit the number of files uploaded with one XHR request,
69
+ // set the following option to an integer greater than 0:
70
+ limitMultiFileUploads: undefined,
71
+ // Set the following option to true to issue all file upload requests
72
+ // in a sequential order:
73
+ sequentialUploads: false,
74
+ // To limit the number of concurrent uploads,
75
+ // set the following option to an integer greater than 0:
76
+ limitConcurrentUploads: undefined,
77
+ // Set the following option to true to force iframe transport uploads:
78
+ forceIframeTransport: false,
79
+ // Set the following option to the location of a redirect url on the
80
+ // origin server, for cross-domain iframe transport uploads:
81
+ redirect: undefined,
82
+ // The parameter name for the redirect url, sent as part of the form
83
+ // data and set to 'redirect' if this option is empty:
84
+ redirectParamName: undefined,
85
+ // Set the following option to the location of a postMessage window,
86
+ // to enable postMessage transport uploads:
87
+ postMessage: undefined,
88
+ // By default, XHR file uploads are sent as multipart/form-data.
89
+ // The iframe transport is always using multipart/form-data.
90
+ // Set to false to enable non-multipart XHR uploads:
91
+ multipart: true,
92
+ // To upload large files in smaller chunks, set the following option
93
+ // to a preferred maximum chunk size. If set to 0, null or undefined,
94
+ // or the browser does not support the required Blob API, files will
95
+ // be uploaded as a whole.
96
+ maxChunkSize: undefined,
97
+ // When a non-multipart upload or a chunked multipart upload has been
98
+ // aborted, this option can be used to resume the upload by setting
99
+ // it to the size of the already uploaded bytes. This option is most
100
+ // useful when modifying the options object inside of the "add" or
101
+ // "send" callbacks, as the options are cloned for each file upload.
102
+ uploadedBytes: undefined,
103
+ // By default, failed (abort or error) file uploads are removed from the
104
+ // global progress calculation. Set the following option to false to
105
+ // prevent recalculating the global progress data:
106
+ recalculateProgress: true,
107
+ // Interval in milliseconds to calculate and trigger progress events:
108
+ progressInterval: 100,
109
+ // Interval in milliseconds to calculate progress bitrate:
110
+ bitrateInterval: 500,
111
+
112
+ // Additional form data to be sent along with the file uploads can be set
113
+ // using this option, which accepts an array of objects with name and
114
+ // value properties, a function returning such an array, a FormData
115
+ // object (for XHR file uploads), or a simple object.
116
+ // The form of the first fileInput is given as parameter to the function:
117
+ formData: function (form) {
118
+ return form.serializeArray();
119
+ },
120
+
121
+ // The add callback is invoked as soon as files are added to the fileupload
122
+ // widget (via file input selection, drag & drop, paste or add API call).
123
+ // If the singleFileUploads option is enabled, this callback will be
124
+ // called once for each file in the selection for XHR file uplaods, else
125
+ // once for each file selection.
126
+ // The upload starts when the submit method is invoked on the data parameter.
127
+ // The data object contains a files property holding the added files
128
+ // and allows to override plugin options as well as define ajax settings.
129
+ // Listeners for this callback can also be bound the following way:
130
+ // .bind('fileuploadadd', func);
131
+ // data.submit() returns a Promise object and allows to attach additional
132
+ // handlers using jQuery's Deferred callbacks:
133
+ // data.submit().done(func).fail(func).always(func);
134
+ add: function (e, data) {
135
+ data.submit();
136
+ },
137
+
138
+ // Other callbacks:
139
+ // Callback for the submit event of each file upload:
140
+ // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
141
+ // Callback for the start of each file upload request:
142
+ // send: function (e, data) {}, // .bind('fileuploadsend', func);
143
+ // Callback for successful uploads:
144
+ // done: function (e, data) {}, // .bind('fileuploaddone', func);
145
+ // Callback for failed (abort or error) uploads:
146
+ // fail: function (e, data) {}, // .bind('fileuploadfail', func);
147
+ // Callback for completed (success, abort or error) requests:
148
+ // always: function (e, data) {}, // .bind('fileuploadalways', func);
149
+ // Callback for upload progress events:
150
+ // progress: function (e, data) {}, // .bind('fileuploadprogress', func);
151
+ // Callback for global upload progress events:
152
+ // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
153
+ // Callback for uploads start, equivalent to the global ajaxStart event:
154
+ // start: function (e) {}, // .bind('fileuploadstart', func);
155
+ // Callback for uploads stop, equivalent to the global ajaxStop event:
156
+ // stop: function (e) {}, // .bind('fileuploadstop', func);
157
+ // Callback for change events of the fileInput(s):
158
+ // change: function (e, data) {}, // .bind('fileuploadchange', func);
159
+ // Callback for paste events to the pasteZone(s):
160
+ // paste: function (e, data) {}, // .bind('fileuploadpaste', func);
161
+ // Callback for drop events of the dropZone(s):
162
+ // drop: function (e, data) {}, // .bind('fileuploaddrop', func);
163
+ // Callback for dragover events of the dropZone(s):
164
+ // dragover: function (e) {}, // .bind('fileuploaddragover', func);
165
+
166
+ // The plugin options are used as settings object for the ajax calls.
167
+ // The following are jQuery ajax settings required for the file uploads:
168
+ processData: false,
169
+ contentType: false,
170
+ cache: false
171
+ },
172
+
173
+ // A list of options that require a refresh after assigning a new value:
174
+ _refreshOptionsList: [
175
+ 'namespace',
176
+ 'fileInput',
177
+ 'dropZone',
178
+ 'pasteZone',
179
+ 'multipart',
180
+ 'forceIframeTransport'
181
+ ],
182
+
183
+ _BitrateTimer: function () {
184
+ this.timestamp = +(new Date());
185
+ this.loaded = 0;
186
+ this.bitrate = 0;
187
+ this.getBitrate = function (now, loaded, interval) {
188
+ var timeDiff = now - this.timestamp;
189
+ if (!this.bitrate || !interval || timeDiff > interval) {
190
+ this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
191
+ this.loaded = loaded;
192
+ this.timestamp = now;
193
+ }
194
+ return this.bitrate;
195
+ };
196
+ },
197
+
198
+ _isXHRUpload: function (options) {
199
+ return !options.forceIframeTransport &&
200
+ ((!options.multipart && $.support.xhrFileUpload) ||
201
+ $.support.xhrFormDataFileUpload);
202
+ },
203
+
204
+ _getFormData: function (options) {
205
+ var formData;
206
+ if (typeof options.formData === 'function') {
207
+ return options.formData(options.form);
208
+ }
209
+ if ($.isArray(options.formData)) {
210
+ return options.formData;
211
+ }
212
+ if (options.formData) {
213
+ formData = [];
214
+ $.each(options.formData, function (name, value) {
215
+ formData.push({name: name, value: value});
216
+ });
217
+ return formData;
218
+ }
219
+ return [];
220
+ },
221
+
222
+ _getTotal: function (files) {
223
+ var total = 0;
224
+ $.each(files, function (index, file) {
225
+ total += file.size || 1;
226
+ });
227
+ return total;
228
+ },
229
+
230
+ _onProgress: function (e, data) {
231
+ if (e.lengthComputable) {
232
+ var now = +(new Date()),
233
+ total,
234
+ loaded;
235
+ if (data._time && data.progressInterval &&
236
+ (now - data._time < data.progressInterval) &&
237
+ e.loaded !== e.total) {
238
+ return;
239
+ }
240
+ data._time = now;
241
+ total = data.total || this._getTotal(data.files);
242
+ loaded = parseInt(
243
+ e.loaded / e.total * (data.chunkSize || total),
244
+ 10
245
+ ) + (data.uploadedBytes || 0);
246
+ this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
247
+ data.lengthComputable = true;
248
+ data.loaded = loaded;
249
+ data.total = total;
250
+ data.bitrate = data._bitrateTimer.getBitrate(
251
+ now,
252
+ loaded,
253
+ data.bitrateInterval
254
+ );
255
+ // Trigger a custom progress event with a total data property set
256
+ // to the file size(s) of the current upload and a loaded data
257
+ // property calculated accordingly:
258
+ this._trigger('progress', e, data);
259
+ // Trigger a global progress event for all current file uploads,
260
+ // including ajax calls queued for sequential file uploads:
261
+ this._trigger('progressall', e, {
262
+ lengthComputable: true,
263
+ loaded: this._loaded,
264
+ total: this._total,
265
+ bitrate: this._bitrateTimer.getBitrate(
266
+ now,
267
+ this._loaded,
268
+ data.bitrateInterval
269
+ )
270
+ });
271
+ }
272
+ },
273
+
274
+ _initProgressListener: function (options) {
275
+ var that = this,
276
+ xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
277
+ // Accesss to the native XHR object is required to add event listeners
278
+ // for the upload progress event:
279
+ if (xhr.upload) {
280
+ $(xhr.upload).bind('progress', function (e) {
281
+ var oe = e.originalEvent;
282
+ // Make sure the progress event properties get copied over:
283
+ e.lengthComputable = oe.lengthComputable;
284
+ e.loaded = oe.loaded;
285
+ e.total = oe.total;
286
+ that._onProgress(e, options);
287
+ });
288
+ options.xhr = function () {
289
+ return xhr;
290
+ };
291
+ }
292
+ },
293
+
294
+ _initXHRData: function (options) {
295
+ var formData,
296
+ file = options.files[0],
297
+ // Ignore non-multipart setting if not supported:
298
+ multipart = options.multipart || !$.support.xhrFileUpload,
299
+ paramName = options.paramName[0];
300
+ options.headers = options.headers || {};
301
+ if (options.contentRange) {
302
+ options.headers['Content-Range'] = options.contentRange;
303
+ }
304
+ if (!multipart) {
305
+ // For cross domain requests, the X-File-Name header
306
+ // must be allowed via Access-Control-Allow-Headers
307
+ // or removed using the beforeSend callback:
308
+ options.headers['X-File-Name'] = file.name;
309
+ options.contentType = file.type;
310
+ options.data = options.blob || file;
311
+ } else if ($.support.xhrFormDataFileUpload) {
312
+ if (options.postMessage) {
313
+ // window.postMessage does not allow sending FormData
314
+ // objects, so we just add the File/Blob objects to
315
+ // the formData array and let the postMessage window
316
+ // create the FormData object out of this array:
317
+ formData = this._getFormData(options);
318
+ if (options.blob) {
319
+ formData.push({
320
+ name: paramName,
321
+ value: options.blob
322
+ });
323
+ } else {
324
+ $.each(options.files, function (index, file) {
325
+ formData.push({
326
+ name: options.paramName[index] || paramName,
327
+ value: file
328
+ });
329
+ });
330
+ }
331
+ } else {
332
+ if (options.formData instanceof FormData) {
333
+ formData = options.formData;
334
+ } else {
335
+ formData = new FormData();
336
+ $.each(this._getFormData(options), function (index, field) {
337
+ formData.append(field.name, field.value);
338
+ });
339
+ }
340
+ if (options.blob) {
341
+ // For cross domain requests, the X-File-* headers
342
+ // must be allowed via Access-Control-Allow-Headers
343
+ // or removed using the beforeSend callback:
344
+ options.headers['X-File-Name'] = file.name;
345
+ options.headers['X-File-Type'] = file.type;
346
+ formData.append(paramName, options.blob, file.name);
347
+ } else {
348
+ $.each(options.files, function (index, file) {
349
+ // File objects are also Blob instances.
350
+ // This check allows the tests to run with
351
+ // dummy objects:
352
+ if (file instanceof Blob) {
353
+ formData.append(
354
+ options.paramName[index] || paramName,
355
+ file,
356
+ file.name
357
+ );
358
+ }
359
+ });
360
+ }
361
+ }
362
+ options.data = formData;
363
+ }
364
+ // Blob reference is not needed anymore, free memory:
365
+ options.blob = null;
366
+ },
367
+
368
+ _initIframeSettings: function (options) {
369
+ // Setting the dataType to iframe enables the iframe transport:
370
+ options.dataType = 'iframe ' + (options.dataType || '');
371
+ // The iframe transport accepts a serialized array as form data:
372
+ options.formData = this._getFormData(options);
373
+ // Add redirect url to form data on cross-domain uploads:
374
+ if (options.redirect && $('<a></a>').prop('href', options.url)
375
+ .prop('host') !== location.host) {
376
+ options.formData.push({
377
+ name: options.redirectParamName || 'redirect',
378
+ value: options.redirect
379
+ });
380
+ }
381
+ },
382
+
383
+ _initDataSettings: function (options) {
384
+ if (this._isXHRUpload(options)) {
385
+ if (!this._chunkedUpload(options, true)) {
386
+ if (!options.data) {
387
+ this._initXHRData(options);
388
+ }
389
+ this._initProgressListener(options);
390
+ }
391
+ if (options.postMessage) {
392
+ // Setting the dataType to postmessage enables the
393
+ // postMessage transport:
394
+ options.dataType = 'postmessage ' + (options.dataType || '');
395
+ }
396
+ } else {
397
+ this._initIframeSettings(options, 'iframe');
398
+ }
399
+ },
400
+
401
+ _getParamName: function (options) {
402
+ var fileInput = $(options.fileInput),
403
+ paramName = options.paramName;
404
+ if (!paramName) {
405
+ paramName = [];
406
+ fileInput.each(function () {
407
+ var input = $(this),
408
+ name = input.prop('name') || 'files[]',
409
+ i = (input.prop('files') || [1]).length;
410
+ while (i) {
411
+ paramName.push(name);
412
+ i -= 1;
413
+ }
414
+ });
415
+ if (!paramName.length) {
416
+ paramName = [fileInput.prop('name') || 'files[]'];
417
+ }
418
+ } else if (!$.isArray(paramName)) {
419
+ paramName = [paramName];
420
+ }
421
+ return paramName;
422
+ },
423
+
424
+ _initFormSettings: function (options) {
425
+ // Retrieve missing options from the input field and the
426
+ // associated form, if available:
427
+ if (!options.form || !options.form.length) {
428
+ options.form = $(options.fileInput.prop('form'));
429
+ // If the given file input doesn't have an associated form,
430
+ // use the default widget file input's form:
431
+ if (!options.form.length) {
432
+ options.form = $(this.options.fileInput.prop('form'));
433
+ }
434
+ }
435
+ options.paramName = this._getParamName(options);
436
+ if (!options.url) {
437
+ options.url = options.form.prop('action') || location.href;
438
+ }
439
+ // The HTTP request method must be "POST" or "PUT":
440
+ options.type = (options.type || options.form.prop('method') || '')
441
+ .toUpperCase();
442
+ if (options.type !== 'POST' && options.type !== 'PUT') {
443
+ options.type = 'POST';
444
+ }
445
+ if (!options.formAcceptCharset) {
446
+ options.formAcceptCharset = options.form.attr('accept-charset');
447
+ }
448
+ },
449
+
450
+ _getAJAXSettings: function (data) {
451
+ var options = $.extend({}, this.options, data);
452
+ this._initFormSettings(options);
453
+ this._initDataSettings(options);
454
+ return options;
455
+ },
456
+
457
+ // Maps jqXHR callbacks to the equivalent
458
+ // methods of the given Promise object:
459
+ _enhancePromise: function (promise) {
460
+ promise.success = promise.done;
461
+ promise.error = promise.fail;
462
+ promise.complete = promise.always;
463
+ return promise;
464
+ },
465
+
466
+ // Creates and returns a Promise object enhanced with
467
+ // the jqXHR methods abort, success, error and complete:
468
+ _getXHRPromise: function (resolveOrReject, context, args) {
469
+ var dfd = $.Deferred(),
470
+ promise = dfd.promise();
471
+ context = context || this.options.context || promise;
472
+ if (resolveOrReject === true) {
473
+ dfd.resolveWith(context, args);
474
+ } else if (resolveOrReject === false) {
475
+ dfd.rejectWith(context, args);
476
+ }
477
+ promise.abort = dfd.promise;
478
+ return this._enhancePromise(promise);
479
+ },
480
+
481
+ // Parses the Range header from the server response
482
+ // and returns the uploaded bytes:
483
+ _getUploadedBytes: function (jqXHR) {
484
+ var range = jqXHR.getResponseHeader('Range'),
485
+ parts = range && range.split('-'),
486
+ upperBytesPos = parts && parts.length > 1 &&
487
+ parseInt(parts[1], 10);
488
+ return upperBytesPos && upperBytesPos + 1;
489
+ },
490
+
491
+ // Uploads a file in multiple, sequential requests
492
+ // by splitting the file up in multiple blob chunks.
493
+ // If the second parameter is true, only tests if the file
494
+ // should be uploaded in chunks, but does not invoke any
495
+ // upload requests:
496
+ _chunkedUpload: function (options, testOnly) {
497
+ var that = this,
498
+ file = options.files[0],
499
+ fs = file.size,
500
+ ub = options.uploadedBytes = options.uploadedBytes || 0,
501
+ mcs = options.maxChunkSize || fs,
502
+ slice = file.slice || file.webkitSlice || file.mozSlice,
503
+ dfd = $.Deferred(),
504
+ promise = dfd.promise(),
505
+ jqXHR,
506
+ upload;
507
+ if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
508
+ options.data) {
509
+ return false;
510
+ }
511
+ if (testOnly) {
512
+ return true;
513
+ }
514
+ if (ub >= fs) {
515
+ file.error = 'Uploaded bytes exceed file size';
516
+ return this._getXHRPromise(
517
+ false,
518
+ options.context,
519
+ [null, 'error', file.error]
520
+ );
521
+ }
522
+ // The chunk upload method:
523
+ upload = function (i) {
524
+ // Clone the options object for each chunk upload:
525
+ var o = $.extend({}, options);
526
+ o.blob = slice.call(
527
+ file,
528
+ ub,
529
+ ub + mcs
530
+ );
531
+ // Store the current chunk size, as the blob itself
532
+ // will be dereferenced after data processing:
533
+ o.chunkSize = o.blob.size;
534
+ // Expose the chunk bytes position range:
535
+ o.contentRange = 'bytes ' + ub + '-' +
536
+ (ub + o.chunkSize - 1) + '/' + fs;
537
+ // Process the upload data (the blob and potential form data):
538
+ that._initXHRData(o);
539
+ // Add progress listeners for this chunk upload:
540
+ that._initProgressListener(o);
541
+ jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
542
+ .done(function (result, textStatus, jqXHR) {
543
+ ub = that._getUploadedBytes(jqXHR) ||
544
+ (ub + o.chunkSize);
545
+ // Create a progress event if upload is done and
546
+ // no progress event has been invoked for this chunk:
547
+ if (!o.loaded) {
548
+ that._onProgress($.Event('progress', {
549
+ lengthComputable: true,
550
+ loaded: ub - o.uploadedBytes,
551
+ total: ub - o.uploadedBytes
552
+ }), o);
553
+ }
554
+ options.uploadedBytes = o.uploadedBytes = ub;
555
+ if (ub < fs) {
556
+ // File upload not yet complete,
557
+ // continue with the next chunk:
558
+ upload();
559
+ } else {
560
+ dfd.resolveWith(
561
+ o.context,
562
+ [result, textStatus, jqXHR]
563
+ );
564
+ }
565
+ })
566
+ .fail(function (jqXHR, textStatus, errorThrown) {
567
+ dfd.rejectWith(
568
+ o.context,
569
+ [jqXHR, textStatus, errorThrown]
570
+ );
571
+ });
572
+ };
573
+ this._enhancePromise(promise);
574
+ promise.abort = function () {
575
+ return jqXHR.abort();
576
+ };
577
+ upload();
578
+ return promise;
579
+ },
580
+
581
+ _beforeSend: function (e, data) {
582
+ if (this._active === 0) {
583
+ // the start callback is triggered when an upload starts
584
+ // and no other uploads are currently running,
585
+ // equivalent to the global ajaxStart event:
586
+ this._trigger('start');
587
+ // Set timer for global bitrate progress calculation:
588
+ this._bitrateTimer = new this._BitrateTimer();
589
+ }
590
+ this._active += 1;
591
+ // Initialize the global progress values:
592
+ this._loaded += data.uploadedBytes || 0;
593
+ this._total += this._getTotal(data.files);
594
+ },
595
+
596
+ _onDone: function (result, textStatus, jqXHR, options) {
597
+ if (!this._isXHRUpload(options)) {
598
+ // Create a progress event for each iframe load:
599
+ this._onProgress($.Event('progress', {
600
+ lengthComputable: true,
601
+ loaded: 1,
602
+ total: 1
603
+ }), options);
604
+ }
605
+ options.result = result;
606
+ options.textStatus = textStatus;
607
+ options.jqXHR = jqXHR;
608
+ this._trigger('done', null, options);
609
+ },
610
+
611
+ _onFail: function (jqXHR, textStatus, errorThrown, options) {
612
+ options.jqXHR = jqXHR;
613
+ options.textStatus = textStatus;
614
+ options.errorThrown = errorThrown;
615
+ this._trigger('fail', null, options);
616
+ if (options.recalculateProgress) {
617
+ // Remove the failed (error or abort) file upload from
618
+ // the global progress calculation:
619
+ this._loaded -= options.loaded || options.uploadedBytes || 0;
620
+ this._total -= options.total || this._getTotal(options.files);
621
+ }
622
+ },
623
+
624
+ _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
625
+ this._active -= 1;
626
+ options.textStatus = textStatus;
627
+ if (jqXHRorError && jqXHRorError.always) {
628
+ options.jqXHR = jqXHRorError;
629
+ options.result = jqXHRorResult;
630
+ } else {
631
+ options.jqXHR = jqXHRorResult;
632
+ options.errorThrown = jqXHRorError;
633
+ }
634
+ this._trigger('always', null, options);
635
+ if (this._active === 0) {
636
+ // The stop callback is triggered when all uploads have
637
+ // been completed, equivalent to the global ajaxStop event:
638
+ this._trigger('stop');
639
+ // Reset the global progress values:
640
+ this._loaded = this._total = 0;
641
+ this._bitrateTimer = null;
642
+ }
643
+ },
644
+
645
+ _onSend: function (e, data) {
646
+ var that = this,
647
+ jqXHR,
648
+ slot,
649
+ pipe,
650
+ options = that._getAJAXSettings(data),
651
+ send = function (resolve, args) {
652
+ that._sending += 1;
653
+ // Set timer for bitrate progress calculation:
654
+ options._bitrateTimer = new that._BitrateTimer();
655
+ jqXHR = jqXHR || (
656
+ (resolve !== false &&
657
+ that._trigger('send', e, options) !== false &&
658
+ (that._chunkedUpload(options) || $.ajax(options))) ||
659
+ that._getXHRPromise(false, options.context, args)
660
+ ).done(function (result, textStatus, jqXHR) {
661
+ that._onDone(result, textStatus, jqXHR, options);
662
+ }).fail(function (jqXHR, textStatus, errorThrown) {
663
+ that._onFail(jqXHR, textStatus, errorThrown, options);
664
+ }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
665
+ that._sending -= 1;
666
+ that._onAlways(
667
+ jqXHRorResult,
668
+ textStatus,
669
+ jqXHRorError,
670
+ options
671
+ );
672
+ if (options.limitConcurrentUploads &&
673
+ options.limitConcurrentUploads > that._sending) {
674
+ // Start the next queued upload,
675
+ // that has not been aborted:
676
+ var nextSlot = that._slots.shift(),
677
+ isPending;
678
+ while (nextSlot) {
679
+ // jQuery 1.6 doesn't provide .state(),
680
+ // while jQuery 1.8+ removed .isRejected():
681
+ isPending = nextSlot.state ?
682
+ nextSlot.state() === 'pending' :
683
+ !nextSlot.isRejected();
684
+ if (isPending) {
685
+ nextSlot.resolve();
686
+ break;
687
+ }
688
+ nextSlot = that._slots.shift();
689
+ }
690
+ }
691
+ });
692
+ return jqXHR;
693
+ };
694
+ this._beforeSend(e, options);
695
+ if (this.options.sequentialUploads ||
696
+ (this.options.limitConcurrentUploads &&
697
+ this.options.limitConcurrentUploads <= this._sending)) {
698
+ if (this.options.limitConcurrentUploads > 1) {
699
+ slot = $.Deferred();
700
+ this._slots.push(slot);
701
+ pipe = slot.pipe(send);
702
+ } else {
703
+ pipe = (this._sequence = this._sequence.pipe(send, send));
704
+ }
705
+ // Return the piped Promise object, enhanced with an abort method,
706
+ // which is delegated to the jqXHR object of the current upload,
707
+ // and jqXHR callbacks mapped to the equivalent Promise methods:
708
+ pipe.abort = function () {
709
+ var args = [undefined, 'abort', 'abort'];
710
+ if (!jqXHR) {
711
+ if (slot) {
712
+ slot.rejectWith(pipe, args);
713
+ }
714
+ return send(false, args);
715
+ }
716
+ return jqXHR.abort();
717
+ };
718
+ return this._enhancePromise(pipe);
719
+ }
720
+ return send();
721
+ },
722
+
723
+ _onAdd: function (e, data) {
724
+ var that = this,
725
+ result = true,
726
+ options = $.extend({}, this.options, data),
727
+ limit = options.limitMultiFileUploads,
728
+ paramName = this._getParamName(options),
729
+ paramNameSet,
730
+ paramNameSlice,
731
+ fileSet,
732
+ i;
733
+ if (!(options.singleFileUploads || limit) ||
734
+ !this._isXHRUpload(options)) {
735
+ fileSet = [data.files];
736
+ paramNameSet = [paramName];
737
+ } else if (!options.singleFileUploads && limit) {
738
+ fileSet = [];
739
+ paramNameSet = [];
740
+ for (i = 0; i < data.files.length; i += limit) {
741
+ fileSet.push(data.files.slice(i, i + limit));
742
+ paramNameSlice = paramName.slice(i, i + limit);
743
+ if (!paramNameSlice.length) {
744
+ paramNameSlice = paramName;
745
+ }
746
+ paramNameSet.push(paramNameSlice);
747
+ }
748
+ } else {
749
+ paramNameSet = paramName;
750
+ }
751
+ data.originalFiles = data.files;
752
+ $.each(fileSet || data.files, function (index, element) {
753
+ var newData = $.extend({}, data);
754
+ newData.files = fileSet ? element : [element];
755
+ newData.paramName = paramNameSet[index];
756
+ newData.submit = function () {
757
+ newData.jqXHR = this.jqXHR =
758
+ (that._trigger('submit', e, this) !== false) &&
759
+ that._onSend(e, this);
760
+ return this.jqXHR;
761
+ };
762
+ return (result = that._trigger('add', e, newData));
763
+ });
764
+ return result;
765
+ },
766
+
767
+ _replaceFileInput: function (input) {
768
+ var inputClone = input.clone(true);
769
+ $('<form></form>').append(inputClone)[0].reset();
770
+ // Detaching allows to insert the fileInput on another form
771
+ // without loosing the file input value:
772
+ input.after(inputClone).detach();
773
+ // Avoid memory leaks with the detached file input:
774
+ $.cleanData(input.unbind('remove'));
775
+ // Replace the original file input element in the fileInput
776
+ // elements set with the clone, which has been copied including
777
+ // event handlers:
778
+ this.options.fileInput = this.options.fileInput.map(function (i, el) {
779
+ if (el === input[0]) {
780
+ return inputClone[0];
781
+ }
782
+ return el;
783
+ });
784
+ // If the widget has been initialized on the file input itself,
785
+ // override this.element with the file input clone:
786
+ if (input[0] === this.element[0]) {
787
+ this.element = inputClone;
788
+ }
789
+ },
790
+
791
+ _handleFileTreeEntry: function (entry, path) {
792
+ var that = this,
793
+ dfd = $.Deferred(),
794
+ errorHandler = function (e) {
795
+ if (e && !e.entry) {
796
+ e.entry = entry;
797
+ }
798
+ // Since $.when returns immediately if one
799
+ // Deferred is rejected, we use resolve instead.
800
+ // This allows valid files and invalid items
801
+ // to be returned together in one set:
802
+ dfd.resolve([e]);
803
+ },
804
+ dirReader;
805
+ path = path || '';
806
+ if (entry.isFile) {
807
+ if (entry._file) {
808
+ // Workaround for Chrome bug #149735
809
+ entry._file.relativePath = path;
810
+ dfd.resolve(entry._file);
811
+ } else {
812
+ entry.file(function (file) {
813
+ file.relativePath = path;
814
+ dfd.resolve(file);
815
+ }, errorHandler);
816
+ }
817
+ } else if (entry.isDirectory) {
818
+ dirReader = entry.createReader();
819
+ dirReader.readEntries(function (entries) {
820
+ that._handleFileTreeEntries(
821
+ entries,
822
+ path + entry.name + '/'
823
+ ).done(function (files) {
824
+ dfd.resolve(files);
825
+ }).fail(errorHandler);
826
+ }, errorHandler);
827
+ } else {
828
+ // Return an empy list for file system items
829
+ // other than files or directories:
830
+ dfd.resolve([]);
831
+ }
832
+ return dfd.promise();
833
+ },
834
+
835
+ _handleFileTreeEntries: function (entries, path) {
836
+ var that = this;
837
+ return $.when.apply(
838
+ $,
839
+ $.map(entries, function (entry) {
840
+ return that._handleFileTreeEntry(entry, path);
841
+ })
842
+ ).pipe(function () {
843
+ return Array.prototype.concat.apply(
844
+ [],
845
+ arguments
846
+ );
847
+ });
848
+ },
849
+
850
+ _getDroppedFiles: function (dataTransfer) {
851
+ dataTransfer = dataTransfer || {};
852
+ var items = dataTransfer.items;
853
+ if (items && items.length && (items[0].webkitGetAsEntry ||
854
+ items[0].getAsEntry)) {
855
+ return this._handleFileTreeEntries(
856
+ $.map(items, function (item) {
857
+ var entry;
858
+ if (item.webkitGetAsEntry) {
859
+ entry = item.webkitGetAsEntry();
860
+ if (entry) {
861
+ // Workaround for Chrome bug #149735:
862
+ entry._file = item.getAsFile();
863
+ }
864
+ return entry;
865
+ }
866
+ return item.getAsEntry();
867
+ })
868
+ );
869
+ }
870
+ return $.Deferred().resolve(
871
+ $.makeArray(dataTransfer.files)
872
+ ).promise();
873
+ },
874
+
875
+ _getSingleFileInputFiles: function (fileInput) {
876
+ fileInput = $(fileInput);
877
+ var entries = fileInput.prop('webkitEntries') ||
878
+ fileInput.prop('entries'),
879
+ files,
880
+ value;
881
+ if (entries && entries.length) {
882
+ return this._handleFileTreeEntries(entries);
883
+ }
884
+ files = $.makeArray(fileInput.prop('files'));
885
+ if (!files.length) {
886
+ value = fileInput.prop('value');
887
+ if (!value) {
888
+ return $.Deferred().resolve([]).promise();
889
+ }
890
+ // If the files property is not available, the browser does not
891
+ // support the File API and we add a pseudo File object with
892
+ // the input value as name with path information removed:
893
+ files = [{name: value.replace(/^.*\\/, '')}];
894
+ }
895
+ return $.Deferred().resolve(files).promise();
896
+ },
897
+
898
+ _getFileInputFiles: function (fileInput) {
899
+ if (!(fileInput instanceof $) || fileInput.length === 1) {
900
+ return this._getSingleFileInputFiles(fileInput);
901
+ }
902
+ return $.when.apply(
903
+ $,
904
+ $.map(fileInput, this._getSingleFileInputFiles)
905
+ ).pipe(function () {
906
+ return Array.prototype.concat.apply(
907
+ [],
908
+ arguments
909
+ );
910
+ });
911
+ },
912
+
913
+ _onChange: function (e) {
914
+ var that = e.data.fileupload,
915
+ data = {
916
+ fileInput: $(e.target),
917
+ form: $(e.target.form)
918
+ };
919
+ that._getFileInputFiles(data.fileInput).always(function (files) {
920
+ data.files = files;
921
+ if (that.options.replaceFileInput) {
922
+ that._replaceFileInput(data.fileInput);
923
+ }
924
+ if (that._trigger('change', e, data) !== false) {
925
+ that._onAdd(e, data);
926
+ }
927
+ });
928
+ },
929
+
930
+ _onPaste: function (e) {
931
+ var that = e.data.fileupload,
932
+ cbd = e.originalEvent.clipboardData,
933
+ items = (cbd && cbd.items) || [],
934
+ data = {files: []};
935
+ $.each(items, function (index, item) {
936
+ var file = item.getAsFile && item.getAsFile();
937
+ if (file) {
938
+ data.files.push(file);
939
+ }
940
+ });
941
+ if (that._trigger('paste', e, data) === false ||
942
+ that._onAdd(e, data) === false) {
943
+ return false;
944
+ }
945
+ },
946
+
947
+ _onDrop: function (e) {
948
+ e.preventDefault();
949
+ var that = e.data.fileupload,
950
+ dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
951
+ data = {};
952
+ that._getDroppedFiles(dataTransfer).always(function (files) {
953
+ data.files = files;
954
+ if (that._trigger('drop', e, data) !== false) {
955
+ that._onAdd(e, data);
956
+ }
957
+ });
958
+ },
959
+
960
+ _onDragOver: function (e) {
961
+ var that = e.data.fileupload,
962
+ dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
963
+ if (that._trigger('dragover', e) === false) {
964
+ return false;
965
+ }
966
+ if (dataTransfer) {
967
+ dataTransfer.dropEffect = 'copy';
968
+ }
969
+ e.preventDefault();
970
+ },
971
+
972
+ _initEventHandlers: function () {
973
+ var ns = this.options.namespace;
974
+ if (this._isXHRUpload(this.options)) {
975
+ this.options.dropZone
976
+ .bind('dragover.' + ns, {fileupload: this}, this._onDragOver)
977
+ .bind('drop.' + ns, {fileupload: this}, this._onDrop);
978
+ this.options.pasteZone
979
+ .bind('paste.' + ns, {fileupload: this}, this._onPaste);
980
+ }
981
+ this.options.fileInput
982
+ .bind('change.' + ns, {fileupload: this}, this._onChange);
983
+ },
984
+
985
+ _destroyEventHandlers: function () {
986
+ var ns = this.options.namespace;
987
+ this.options.dropZone
988
+ .unbind('dragover.' + ns, this._onDragOver)
989
+ .unbind('drop.' + ns, this._onDrop);
990
+ this.options.pasteZone
991
+ .unbind('paste.' + ns, this._onPaste);
992
+ this.options.fileInput
993
+ .unbind('change.' + ns, this._onChange);
994
+ },
995
+
996
+ _setOption: function (key, value) {
997
+ var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
998
+ if (refresh) {
999
+ this._destroyEventHandlers();
1000
+ }
1001
+ $.Widget.prototype._setOption.call(this, key, value);
1002
+ if (refresh) {
1003
+ this._initSpecialOptions();
1004
+ this._initEventHandlers();
1005
+ }
1006
+ },
1007
+
1008
+ _initSpecialOptions: function () {
1009
+ var options = this.options;
1010
+ if (options.fileInput === undefined) {
1011
+ options.fileInput = this.element.is('input[type="file"]') ?
1012
+ this.element : this.element.find('input[type="file"]');
1013
+ } else if (!(options.fileInput instanceof $)) {
1014
+ options.fileInput = $(options.fileInput);
1015
+ }
1016
+ if (!(options.dropZone instanceof $)) {
1017
+ options.dropZone = $(options.dropZone);
1018
+ }
1019
+ if (!(options.pasteZone instanceof $)) {
1020
+ options.pasteZone = $(options.pasteZone);
1021
+ }
1022
+ },
1023
+
1024
+ _create: function () {
1025
+ var options = this.options;
1026
+ // Initialize options set via HTML5 data-attributes:
1027
+ $.extend(options, $(this.element[0].cloneNode(false)).data());
1028
+ options.namespace = options.namespace || this.widgetName;
1029
+ this._initSpecialOptions();
1030
+ this._slots = [];
1031
+ this._sequence = this._getXHRPromise(true);
1032
+ this._sending = this._active = this._loaded = this._total = 0;
1033
+ this._initEventHandlers();
1034
+ },
1035
+
1036
+ destroy: function () {
1037
+ this._destroyEventHandlers();
1038
+ $.Widget.prototype.destroy.call(this);
1039
+ },
1040
+
1041
+ enable: function () {
1042
+ var wasDisabled = false;
1043
+ if (this.options.disabled) {
1044
+ wasDisabled = true;
1045
+ }
1046
+ $.Widget.prototype.enable.call(this);
1047
+ if (wasDisabled) {
1048
+ this._initEventHandlers();
1049
+ }
1050
+ },
1051
+
1052
+ disable: function () {
1053
+ if (!this.options.disabled) {
1054
+ this._destroyEventHandlers();
1055
+ }
1056
+ $.Widget.prototype.disable.call(this);
1057
+ },
1058
+
1059
+ // This method is exposed to the widget API and allows adding files
1060
+ // using the fileupload API. The data parameter accepts an object which
1061
+ // must have a files property and can contain additional options:
1062
+ // .fileupload('add', {files: filesList});
1063
+ add: function (data) {
1064
+ var that = this;
1065
+ if (!data || this.options.disabled) {
1066
+ return;
1067
+ }
1068
+ if (data.fileInput && !data.files) {
1069
+ this._getFileInputFiles(data.fileInput).always(function (files) {
1070
+ data.files = files;
1071
+ that._onAdd(null, data);
1072
+ });
1073
+ } else {
1074
+ data.files = $.makeArray(data.files);
1075
+ this._onAdd(null, data);
1076
+ }
1077
+ },
1078
+
1079
+ // This method is exposed to the widget API and allows sending files
1080
+ // using the fileupload API. The data parameter accepts an object which
1081
+ // must have a files or fileInput property and can contain additional options:
1082
+ // .fileupload('send', {files: filesList});
1083
+ // The method returns a Promise object for the file upload call.
1084
+ send: function (data) {
1085
+ if (data && !this.options.disabled) {
1086
+ if (data.fileInput && !data.files) {
1087
+ var that = this,
1088
+ dfd = $.Deferred(),
1089
+ promise = dfd.promise(),
1090
+ jqXHR,
1091
+ aborted;
1092
+ promise.abort = function () {
1093
+ aborted = true;
1094
+ if (jqXHR) {
1095
+ return jqXHR.abort();
1096
+ }
1097
+ dfd.reject(null, 'abort', 'abort');
1098
+ return promise;
1099
+ };
1100
+ this._getFileInputFiles(data.fileInput).always(
1101
+ function (files) {
1102
+ if (aborted) {
1103
+ return;
1104
+ }
1105
+ data.files = files;
1106
+ jqXHR = that._onSend(null, data).then(
1107
+ function (result, textStatus, jqXHR) {
1108
+ dfd.resolve(result, textStatus, jqXHR);
1109
+ },
1110
+ function (jqXHR, textStatus, errorThrown) {
1111
+ dfd.reject(jqXHR, textStatus, errorThrown);
1112
+ }
1113
+ );
1114
+ }
1115
+ );
1116
+ return this._enhancePromise(promise);
1117
+ }
1118
+ data.files = $.makeArray(data.files);
1119
+ if (data.files.length) {
1120
+ return this._onSend(null, data);
1121
+ }
1122
+ }
1123
+ return this._getXHRPromise(false, data && data.context);
1124
+ }
1125
+
1126
+ });
1127
+
1128
+ }));