diff --git a/media/scripts/app/views/dir.js b/media/scripts/app/views/dir.js index 4eea860071..9faf47ae40 100644 --- a/media/scripts/app/views/dir.js +++ b/media/scripts/app/views/dir.js @@ -5,11 +5,12 @@ define([ 'backbone', 'common', 'file-tree', + 'jquery.fileupload-ui', 'app/collections/dirents', 'app/views/dirent', 'text!' + app.config._tmplRoot + 'dir-op-bar.html', 'text!' + app.config._tmplRoot + 'path-bar.html', - ], function($, simplemodal, _, Backbone, Common, FileTree, DirentCollection, DirentView, + ], function($, simplemodal, _, Backbone, Common, FileTree, FileUpload, DirentCollection, DirentView, DirOpBarTemplate, PathBarTemplate) { 'use strict'; @@ -19,6 +20,7 @@ define([ dir_op_bar_template: _.template(DirOpBarTemplate), newDirTemplate: _.template($("#add-new-dir-form-template").html()), newFileTemplate: _.template($("#add-new-file-form-template").html()), + //uploadFileDialogTemplate: _.template($("#upload-file-dialog-template").html()), initialize: function(options) { this.$dirent_list = this.$('.repo-file-list tbody'); @@ -62,6 +64,297 @@ define([ } }); + $(function() { + window.locale = { + "fileupload": { + "errors": { + "maxFileSize": gettext("File is too big"), + "minFileSize": gettext("File is too small"), + "acceptFileTypes": gettext("Filetype not allowed"), + "maxNumberOfFiles": gettext("Max number of files exceeded"), + "uploadedBytes": gettext("Uploaded bytes exceed file size"), + "emptyResult": gettext("Empty file upload result") + }, + "error": gettext("Error"), + "uploaded": gettext("uploaded"), + "canceled": gettext("canceled"), + "start": gettext("Start"), + "cancel": gettext("Cancel"), + "destroy": gettext("Delete") + } + }; + + var dirents = _this.dir; + var libview = _this; + //var popup = $(libview.uploadFileDialogTemplate()).addClass('fixed-upload-file-dialog'); + var popup = $('#upload-file-dialog').addClass('fixed-upload-file-dialog'); + var popup_height = '200px'; + popup.css({'height': popup_height}).data('height', popup_height); + var fu_status = $('.status', popup), + total_progress = $('.total-progress', popup), + cancel_all_btn = $('.fileupload-buttonbar .cancel', popup), + close_icon = $('.close', popup), + saving_tip = $('.saving-tip', popup); + var fu_status_ = { + 'uploading': gettext("File Uploading..."), + 'complete': gettext("File Upload complete"), + 'canceled': gettext("File Upload canceled"), + 'failed': gettext("File Upload failed") + }; + + var uploaded_files = []; + + var enable_upload_folder = app.pageOptions.enable_upload_folder; + var new_dir_names = []; + var dirs_to_update = []; + + popup.fileupload({ + paramName: 'file', + // customize it for 'done' + getFilesFromResponse: function (data) { + if (data.result) { + return data.result; + } + }, + autoUpload:true, + maxNumberOfFiles: 500, + sequentialUploads: true + }) + .bind('fileuploadadd', function(e, data) { + // for drag & drop + if (!libview.$el.is(':visible')) { + return false; + } + if (dirents.user_perm && dirents.user_perm != 'rw') { + return false; + } + popup.removeClass('hide'); + cancel_all_btn.removeClass('hide'); + close_icon.addClass('hide'); + var path = dirents.path; + popup.fileupload('option', 'formData', { + 'parent_dir': path == '/' ? path : path + '/' + }); + + if (!enable_upload_folder) { + return; + } + // hide the upload menu + var menu = libview.$('#upload-menu'); + if (!menu.hasClass('hide')) { + menu.find('.item').removeAttr('style') + .end().addClass('hide'); + } + + // when add folder, a subdirectory will be shown as '.'. rm it. + var file = data.files[0]; + if (file.name == '.') { + data.files.shift(); + } + if (file.webkitRelativePath) { // for 'upload folder' + file.relative_path = file.webkitRelativePath; + } + if (file.relativePath) { // for 'folder drag & drop' + file.relative_path = file.relativePath + file.name; + } + }) + .bind('fileuploadstart', function() { + fu_status.html(fu_status_.uploading); + }) + .bind('fileuploadsubmit', function(e, data) { + var file = data.files[0]; + // get url(token) for every file + if (!file.error) { + $.ajax({ + url: Common.getUrl({name:'get_file_op_url', repo_id:dirents.repo_id}) + '?op_type=upload', + cache: false, + dataType: 'json', + success: function(ret) { + if (enable_upload_folder) { + var file_path = file.relative_path, + r_path; + if (file_path) { // 'add folder' + r_path = file_path.substring(0, file_path.lastIndexOf('/') + 1); + } + var formData = popup.fileupload('option', 'formData'); + formData.relative_path = r_path || ''; + popup.fileupload('option', 'formData', formData); + } + data.url = ret['url']; + data.jqXHR = popup.fileupload('send', data); + }, + error: function() { + file.error = gettext("Failed to get upload url"); + } + }); + return false; + } + }) + .bind('fileuploadprogressall', function (e, data) { + total_progress.html(parseInt(data.loaded / data.total * 100, 10) + '% ' + '(' + $(this).data('blueimp-fileupload')._formatBitrate(data.bitrate) + ')').removeClass('hide'); + if (data.loaded > 0 && data.loaded == data.total) { + saving_tip.show(); + } + }) + .bind('fileuploaddone', function(e, data) { + if (data.textStatus != 'success') { + return; + } + var file = data.files[0]; + var file_path = file.relative_path; + var file_uploaded = data.result[0]; // 'id', 'name', 'size' + // for 'template_download' render + file_uploaded.uploaded = true; + if (file_path) { + file_uploaded.relative_path = file_path.substring(0, file_path.lastIndexOf('/') + 1) + file_uploaded.name; + } + var path = dirents.path; + path = path == '/' ? path : path + '/'; + if (data.formData.parent_dir != path) { + return; + } + if (!file_path) { + uploaded_files.push(file_uploaded); + return; + } + if (!enable_upload_folder) { + return; + } + // for 'add folder' + var dir_name = file_path.substring(0, file_path.indexOf('/')); + var dir = dirents.where({'is_dir': true, 'obj_name': dir_name}); + if (dir.length > 0) { // 0 or 1 + if (dirs_to_update.indexOf(dir_name) == -1) { + dirs_to_update.push(dir_name); + } + } else { + if (new_dir_names.indexOf(dir_name) == -1) { + new_dir_names.push(dir_name); + } + } + }) + .bind('fileuploadstop', function () { + cancel_all_btn.addClass('hide'); + close_icon.removeClass('hide'); + var path = dirents.path; + path = path == '/' ? path : path + '/'; + if (popup.fileupload('option','formData').parent_dir != path) { + return; + } + var now = parseInt(new Date().getTime()/1000); + if (uploaded_files.length > 0) { + $(uploaded_files).each(function(index, file) { + var new_dirent = dirents.add({ + 'is_file': true, + 'obj_name': file.name, + 'last_modified': now, + 'file_size': Common.fileSizeFormat(file.size, 1), + 'obj_id': file.id, + 'file_icon': 'file.png', + 'last_update': gettext("Just now"), + 'starred': false, + 'sharelink': '', + 'sharetoken': '' + }, {silent: true}); + libview.addNewFile(new_dirent); + }); + uploaded_files = []; + } + if (new_dir_names.length > 0) { + $(new_dir_names).each(function(index, new_name) { + var new_dirent = dirents.add({ + 'is_dir': true, + 'obj_name': new_name, + 'last_modified': now, + 'last_update': gettext("Just now"), + 'p_dpath': path + new_name, + 'sharelink': '', + 'sharetoken': '', + 'uploadlink': '', + 'uploadtoken': '' + }, {silent: true}); + var view = new DirentView({model: new_dirent, dirView: libview}); + libview.$dirent_list.prepend(view.render().el); // put the new dir as the first one + }); + new_dir_names = []; + } + if (dirs_to_update.length > 0) { + $(dirs_to_update).each(function(index, dir_name) { + var dir = dirents.where({'is_dir':true, 'obj_name':dir_name}); + dir[0].set({ + 'last_modified': now, + 'last_update': gettext("Just now") + }); + }); + dirs_to_update = []; + } + }) + // after tpl has rendered + .bind('fileuploadcompleted', function() { // 'done' + if ($('.files .cancel', popup).length == 0) { + saving_tip.hide(); + total_progress.addClass('hide'); + fu_status.html(fu_status_.complete); + } + }) + .bind('fileuploadfailed', function(e, data) { // 'fail' + if ($('.files .cancel', popup).length == 0) { + cancel_all_btn.addClass('hide'); + close_icon.removeClass('hide'); + total_progress.addClass('hide'); + saving_tip.hide(); + if (data.errorThrown == 'abort') { // 'cancel' + fu_status.html(fu_status_.canceled); + } else { // 'error' + fu_status.html(fu_status_.failed); + } + } + }); + + var max_upload_file_size = app.pageOptions.max_upload_file_size; + if (max_upload_file_size) { + popup.fileupload( + 'option', + 'maxFileSize', + max_upload_file_size); + } + + // Enable iframe cross-domain access via redirect option: + popup.fileupload( + 'option', + 'redirect', + window.location.href.replace(/\/repo\/[-a-z0-9]{36}\/.*/, app.config.mediaUrl + 'cors/result.html?%s') + ); + + // fold/unfold the dialog + $('.fold-switch', popup).click(function() { + var full_ht = parseInt(popup.data('height')); + var main_con = $('.fileupload-buttonbar, .table', popup); + if (popup.height() == full_ht) { + popup.height($('.hd', popup).outerHeight(true)); + main_con.addClass('hide'); + } else { + popup.height(full_ht); + main_con.removeClass('hide'); + } + }); + $('.close', popup).click(function() { + popup.addClass('hide'); + $('.files', popup).empty(); + }); + + $(document).click(function(e) { + var target = e.target || event.srcElement; + var closePopup = function(popup, popup_switch) { + if (!popup.hasClass('hide') && !popup.is(target) && !popup.find('*').is(target) && !popup_switch.is(target) && !popup_switch.find('*').is(target) ) { + popup.addClass('hide'); + } + }; + var libview = _this; + closePopup(libview.$('#upload-menu'), libview.$('#upload-file')); + }); + }); + }, showDir: function(category, repo_id, path) { @@ -99,6 +392,46 @@ define([ this.dir.each(this.addOne, this); this.renderPath(); this.renderDirOpBar(); + + var dir = this.dir; + var upload_popup = $('#upload-file-dialog'); + if (dir.user_perm && dir.user_perm == 'rw') { + upload_popup.fileupload( + 'option', + 'fileInput', + this.$('#upload-file input')); + } + if (!app.pageOptions.enable_upload_folder) { + return; + } + var upload_btn = this.$('#upload-file'), + upload_menu = this.$('#upload-menu'); + if (dir.user_perm && dir.user_perm == 'rw' && + 'webkitdirectory' in $('input[type="file"]', upload_btn)[0]) { + upload_btn.find('input').remove().end().addClass('cspt'); + $('.item', upload_menu).click(function() { + upload_popup.fileupload( + 'option', + 'fileInput', + $('input[type="file"]', $(this))); + }) + .hover( + function() { + $(this).css({'background':'#f3f3f3'}); + }, + function() { + $(this).css({'background':'transparent'}); + } + ); + this.$('.repo-op').css({'position': 'relative'}); + upload_menu.css({ + 'left': upload_btn.position().left, + 'top': parseInt(this.$('.repo-op').css('padding-top')) + upload_btn.outerHeight(true) + }); + upload_btn.click(function () { + upload_menu.toggleClass('hide'); + }); + } }, renderPath: function() { @@ -125,7 +458,7 @@ define([ encrypted: dir.encrypted, path: dir.path, repo_id: dir.repo_id, - enable_upload_folder: app.globalState.enable_upload_folder + enable_upload_folder: app.pageOptions.enable_upload_folder }))); }, @@ -242,20 +575,7 @@ define([ 'sharelink': '', 'sharetoken': '' }, {silent: true}); - var view = new DirentView({model: new_dirent, dirView: dirView}); - var new_file = view.render().el; - // put the new file as the first file - if ($('tr', dirView.$dirent_list).length == 0) { - dirView.$dirent_list.append(new_file); - } else { - var dirs = dir.where({'is_dir':true}); - if (dirs.length == 0) { - dirView.$dirent_list.prepend(new_file); - } else { - // put the new file after the last dir - $($('tr', dirView.$dirent_list)[dirs.length - 1]).after(new_file); - } - } + dirView.addNewFile(new_dirent); }; Common.ajaxPost({ @@ -270,6 +590,25 @@ define([ }); }, + addNewFile: function(new_dirent) { + var dirView = this, + dir = this.dir; + var view = new DirentView({model: new_dirent, dirView: dirView}); + var new_file = view.render().el; + // put the new file as the first file + if ($('tr', dirView.$dirent_list).length == 0) { + dirView.$dirent_list.append(new_file); + } else { + var dirs = dir.where({'is_dir':true}); + if (dirs.length == 0) { + dirView.$dirent_list.prepend(new_file); + } else { + // put the new file after the last dir + $($('tr', dirView.$dirent_list)[dirs.length - 1]).after(new_file); + } + } + }, + sortByName: function() { var dirents = this.dir; var el = $('#by-name'); @@ -290,7 +629,6 @@ define([ }, sortByTime: function () { - console.log("sortByTime: " + this.dir.repo_id + " " + this.dir.path); var dirents = this.dir; var el = $('#by-time'); dirents.comparator = function(a, b) { diff --git a/media/scripts/common.js b/media/scripts/common.js index 2cb9fbc0b6..73e8c0e035 100644 --- a/media/scripts/common.js +++ b/media/scripts/common.js @@ -22,9 +22,16 @@ require.config({ }, paths: { jquery: 'lib/jquery', + 'jquery.ui.widget': 'lib/jquery.ui.widget.1.11.1', + 'tmpl': 'lib/tmpl.min', + 'jquery.iframe-transport': 'lib/jquery.iframe-transport.1.4', + 'jquery.fileupload': 'lib/jquery.fileupload.5.42.1', + 'jquery.fileupload-process': 'lib/jquery.fileupload.file-processing.1.3.0', + 'jquery.fileupload-validate': 'lib/jquery.fileupload.validation.1.1.2', + 'jquery.fileupload-ui': 'lib/jquery.fileupload.ui.9.6.0', + simplemodal: 'lib/jquery.simplemodal.1.4.4.min', jstree: 'lib/jstree.1.0', - underscore: 'lib/underscore', backbone: 'lib/backbone', text: 'lib/text' diff --git a/media/scripts/lib/jquery.fileupload.5.42.1.js b/media/scripts/lib/jquery.fileupload.5.42.1.js new file mode 100644 index 0000000000..4399123a82 --- /dev/null +++ b/media/scripts/lib/jquery.fileupload.5.42.1.js @@ -0,0 +1,11 @@ +/* + * jQuery File Upload Plugin 5.42.1 + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2010, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/MIT + */ +(function(factory){if(typeof define==="function"&&define.amd){define(["jquery","jquery.ui.widget"],factory);}else{factory(window.jQuery);}}(function($){$.support.fileInput=!(new RegExp("(Android (1\\.[0156]|2\\.[01]))|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)|(w(eb)?OSBrowser)|(webOS)|(Kindle/(1\\.0|2\\.[05]|3\\.0))").test(window.navigator.userAgent)||$('').prop("disabled"));$.support.xhrFileUpload=!!(window.ProgressEvent&&window.FileReader);$.support.xhrFormDataFileUpload=!!window.FormData;$.support.blobSlice=window.Blob&&(Blob.prototype.slice||Blob.prototype.webkitSlice||Blob.prototype.mozSlice);function getDragHandler(type){var isDragOver=type==="dragover";return function(e){e.dataTransfer=e.originalEvent&&e.originalEvent.dataTransfer;var dataTransfer=e.dataTransfer;if(dataTransfer&&$.inArray("Files",dataTransfer.types)!==-1&&this._trigger(type,$.Event(type,{delegatedEvent:e}))!==false){e.preventDefault();if(isDragOver){dataTransfer.dropEffect="copy";}}};}$.widget("blueimp.fileupload",{options:{dropZone:$(document),pasteZone:undefined,fileInput:undefined,replaceFileInput:true,paramName:undefined,singleFileUploads:true,limitMultiFileUploads:undefined,limitMultiFileUploadSize:undefined,limitMultiFileUploadSizeOverhead:512,sequentialUploads:false,limitConcurrentUploads:undefined,forceIframeTransport:false,redirect:undefined,redirectParamName:undefined,postMessage:undefined,multipart:true,maxChunkSize:undefined,uploadedBytes:undefined,recalculateProgress:true,progressInterval:100,bitrateInterval:500,autoUpload:true,messages:{uploadedBytes:"Uploaded bytes exceed file size"},i18n:function(message,context){message=this.messages[message]||message.toString();if(context){$.each(context,function(key,value){message=message.replace("{"+key+"}",value);});}return message;},formData:function(form){return form.serializeArray();},add:function(e,data){if(e.isDefaultPrevented()){return false;}if(data.autoUpload||(data.autoUpload!==false&&$(this).fileupload("option","autoUpload"))){data.process().done(function(){data.submit();});}},processData:false,contentType:false,cache:false},_specialOptions:["fileInput","dropZone","pasteZone","multipart","forceIframeTransport"],_blobSlice:$.support.blobSlice&&function(){var slice=this.slice||this.webkitSlice||this.mozSlice;return slice.apply(this,arguments);},_BitrateTimer:function(){this.timestamp=((Date.now)?Date.now():(new Date()).getTime());this.loaded=0;this.bitrate=0;this.getBitrate=function(now,loaded,interval){var timeDiff=now-this.timestamp;if(!this.bitrate||!interval||timeDiff>interval){this.bitrate=(loaded-this.loaded)*(1000/timeDiff)*8;this.loaded=loaded;this.timestamp=now;}return this.bitrate;};},_isXHRUpload:function(options){return !options.forceIframeTransport&&((!options.multipart&&$.support.xhrFileUpload)||$.support.xhrFormDataFileUpload);},_getFormData:function(options){var formData;if($.type(options.formData)==="function"){return options.formData(options.form);}if($.isArray(options.formData)){return options.formData;}if($.type(options.formData)==="object"){formData=[];$.each(options.formData,function(name,value){formData.push({name:name,value:value});});return formData;}return[];},_getTotal:function(files){var total=0;$.each(files,function(index,file){total+=file.size||1;});return total;},_initProgressObject:function(obj){var progress={loaded:0,total:0,bitrate:0};if(obj._progress){$.extend(obj._progress,progress);}else{obj._progress=progress;}},_initResponseObject:function(obj){var prop;if(obj._response){for(prop in obj._response){if(obj._response.hasOwnProperty(prop)){delete obj._response[prop];}}}else{obj._response={};}},_onProgress:function(e,data){if(e.lengthComputable){var now=((Date.now)?Date.now():(new Date()).getTime()),loaded;if(data._time&&data.progressInterval&&(now-data._time").prop("href",options.url).prop("host");options.dataType="iframe "+(options.dataType||"");options.formData=this._getFormData(options);if(options.redirect&&targetHost&&targetHost!==location.host){options.formData.push({name:options.redirectParamName||"redirect",value:options.redirect});}},_initDataSettings:function(options){if(this._isXHRUpload(options)){if(!this._chunkedUpload(options,true)){if(!options.data){this._initXHRData(options);}this._initProgressListener(options);}if(options.postMessage){options.dataType="postmessage "+(options.dataType||"");}}else{this._initIframeSettings(options);}},_getParamName:function(options){var fileInput=$(options.fileInput),paramName=options.paramName;if(!paramName){paramName=[];fileInput.each(function(){var input=$(this),name=input.prop("name")||"files[]",i=(input.prop("files")||[1]).length;while(i){paramName.push(name);i-=1;}});if(!paramName.length){paramName=[fileInput.prop("name")||"files[]"];}}else{if(!$.isArray(paramName)){paramName=[paramName];}}return paramName;},_initFormSettings:function(options){if(!options.form||!options.form.length){options.form=$(options.fileInput.prop("form"));if(!options.form.length){options.form=$(this.options.fileInput.prop("form"));}}options.paramName=this._getParamName(options);if(!options.url){options.url=options.form.prop("action")||location.href;}options.type=(options.type||($.type(options.form.prop("method"))==="string"&&options.form.prop("method"))||"").toUpperCase();if(options.type!=="POST"&&options.type!=="PUT"&&options.type!=="PATCH"){options.type="POST";}if(!options.formAcceptCharset){options.formAcceptCharset=options.form.attr("accept-charset");}},_getAJAXSettings:function(data){var options=$.extend({},this.options,data);this._initFormSettings(options);this._initDataSettings(options);return options;},_getDeferredState:function(deferred){if(deferred.state){return deferred.state();}if(deferred.isResolved()){return"resolved";}if(deferred.isRejected()){return"rejected";}return"pending";},_enhancePromise:function(promise){promise.success=promise.done;promise.error=promise.fail;promise.complete=promise.always;return promise;},_getXHRPromise:function(resolveOrReject,context,args){var dfd=$.Deferred(),promise=dfd.promise();context=context||this.options.context||promise;if(resolveOrReject===true){dfd.resolveWith(context,args);}else{if(resolveOrReject===false){dfd.rejectWith(context,args);}}promise.abort=dfd.promise;return this._enhancePromise(promise);},_addConvenienceMethods:function(e,data){var that=this,getPromise=function(args){return $.Deferred().resolveWith(that,args).promise();};data.process=function(resolveFunc,rejectFunc){if(resolveFunc||rejectFunc){data._processQueue=this._processQueue=(this._processQueue||getPromise([this])).pipe(function(){if(data.errorThrown){return $.Deferred().rejectWith(that,[data]).promise();}return getPromise(arguments);}).pipe(resolveFunc,rejectFunc);}return this._processQueue||getPromise([this]);};data.submit=function(){if(this.state()!=="pending"){data.jqXHR=this.jqXHR=(that._trigger("submit",$.Event("submit",{delegatedEvent:e}),this)!==false)&&that._onSend(e,this);}return this.jqXHR||that._getXHRPromise();};data.abort=function(){if(this.jqXHR){return this.jqXHR.abort();}this.errorThrown="abort";that._trigger("fail",null,this);return that._getXHRPromise(false);};data.state=function(){if(this.jqXHR){return that._getDeferredState(this.jqXHR);}if(this._processQueue){return that._getDeferredState(this._processQueue);}};data.processing=function(){return !this.jqXHR&&this._processQueue&&that._getDeferredState(this._processQueue)==="pending";};data.progress=function(){return this._progress;};data.response=function(){return this._response;};},_getUploadedBytes:function(jqXHR){var range=jqXHR.getResponseHeader("Range"),parts=range&&range.split("-"),upperBytesPos=parts&&parts.length>1&&parseInt(parts[1],10);return upperBytesPos&&upperBytesPos+1;},_chunkedUpload:function(options,testOnly){options.uploadedBytes=options.uploadedBytes||0;var that=this,file=options.files[0],fs=file.size,ub=options.uploadedBytes,mcs=options.maxChunkSize||fs,slice=this._blobSlice,dfd=$.Deferred(),promise=dfd.promise(),jqXHR,upload;if(!(this._isXHRUpload(options)&&slice&&(ub||mcs=fs){file.error=options.i18n("uploadedBytes");return this._getXHRPromise(false,options.context,[null,"error",file.error]);}upload=function(){var o=$.extend({},options),currentLoaded=o._progress.loaded;o.blob=slice.call(file,ub,ub+mcs,file.type);o.chunkSize=o.blob.size;o.contentRange="bytes "+ub+"-"+(ub+o.chunkSize-1)+"/"+fs;that._initXHRData(o);that._initProgressListener(o);jqXHR=((that._trigger("chunksend",null,o)!==false&&$.ajax(o))||that._getXHRPromise(false,o.context)).done(function(result,textStatus,jqXHR){ub=that._getUploadedBytes(jqXHR)||(ub+o.chunkSize);if(currentLoaded+o.chunkSize-o._progress.loaded){that._onProgress($.Event("progress",{lengthComputable:true,loaded:ub-o.uploadedBytes,total:ub-o.uploadedBytes}),o);}options.uploadedBytes=o.uploadedBytes=ub;o.result=result;o.textStatus=textStatus;o.jqXHR=jqXHR;that._trigger("chunkdone",null,o);that._trigger("chunkalways",null,o);if(ubthat._sending){var nextSlot=that._slots.shift();while(nextSlot){if(that._getDeferredState(nextSlot)==="pending"){nextSlot.resolve();break;}nextSlot=that._slots.shift();}}if(that._active===0){that._trigger("stop");}});return jqXHR;};this._beforeSend(e,options);if(this.options.sequentialUploads||(this.options.limitConcurrentUploads&&this.options.limitConcurrentUploads<=this._sending)){if(this.options.limitConcurrentUploads>1){slot=$.Deferred();this._slots.push(slot);pipe=slot.pipe(send);}else{this._sequence=this._sequence.pipe(send,send);pipe=this._sequence;}pipe.abort=function(){aborted=[undefined,"abort","abort"];if(!jqXHR){if(slot){slot.rejectWith(options.context,aborted);}return send();}return jqXHR.abort();};return this._enhancePromise(pipe);}return send();},_onAdd:function(e,data){var that=this,result=true,options=$.extend({},this.options,data),files=data.files,filesLength=files.length,limit=options.limitMultiFileUploads,limitSize=options.limitMultiFileUploadSize,overhead=options.limitMultiFileUploadSizeOverhead,batchSize=0,paramName=this._getParamName(options),paramNameSet,paramNameSlice,fileSet,i,j=0;if(limitSize&&(!filesLength||files[0].size===undefined)){limitSize=undefined;}if(!(options.singleFileUploads||limit||limitSize)||!this._isXHRUpload(options)){fileSet=[files];paramNameSet=[paramName];}else{if(!(options.singleFileUploads||limitSize)&&limit){fileSet=[];paramNameSet=[];for(i=0;ilimitSize)||(limit&&i+1-j>=limit)){fileSet.push(files.slice(j,i+1));paramNameSlice=paramName.slice(j,i+1);if(!paramNameSlice.length){paramNameSlice=paramName;}paramNameSet.push(paramNameSlice);j=i+1;batchSize=0;}}}else{paramNameSet=paramName;}}}data.originalFiles=files;$.each(fileSet||files,function(index,element){var newData=$.extend({},data);newData.files=fileSet?element:[element];newData.paramName=paramNameSet[index];that._initResponseObject(newData);that._initProgressObject(newData);that._addConvenienceMethods(e,newData);result=that._trigger("add",$.Event("add",{delegatedEvent:e}),newData);return result;});return result;},_replaceFileInput:function(data){var input=data.fileInput,inputClone=input.clone(true);data.fileInputClone=inputClone;$("
").append(inputClone)[0].reset();input.after(inputClone).detach();$.cleanData(input.unbind("remove"));this.options.fileInput=this.options.fileInput.map(function(i,el){if(el===input[0]){return inputClone[0];}return el;});if(input[0]===this.element[0]){this.element=inputClone;}},_handleFileTreeEntry:function(entry,path){var that=this,dfd=$.Deferred(),errorHandler=function(e){if(e&&!e.entry){e.entry=entry;}dfd.resolve([e]);},successHandler=function(entries){that._handleFileTreeEntries(entries,path+entry.name+"/").done(function(files){dfd.resolve(files);}).fail(errorHandler);},readEntries=function(){dirReader.readEntries(function(results){if(!results.length){successHandler(entries);}else{entries=entries.concat(results);readEntries();}},errorHandler);},dirReader,entries=[];path=path||"";if(entry.isFile){if(entry._file){entry._file.relativePath=path;dfd.resolve(entry._file);}else{entry.file(function(file){file.relativePath=path;dfd.resolve(file);},errorHandler);}}else{if(entry.isDirectory){dirReader=entry.createReader();readEntries();}else{dfd.resolve([]);}}return dfd.promise();},_handleFileTreeEntries:function(entries,path){var that=this;return $.when.apply($,$.map(entries,function(entry){return that._handleFileTreeEntry(entry,path);})).pipe(function(){return Array.prototype.concat.apply([],arguments);});},_getDroppedFiles:function(dataTransfer){dataTransfer=dataTransfer||{};var items=dataTransfer.items;if(items&&items.length&&(items[0].webkitGetAsEntry||items[0].getAsEntry)){return this._handleFileTreeEntries($.map(items,function(item){var entry;if(item.webkitGetAsEntry){entry=item.webkitGetAsEntry();if(entry){entry._file=item.getAsFile();}return entry;}return item.getAsEntry();}));}return $.Deferred().resolve($.makeArray(dataTransfer.files)).promise();},_getSingleFileInputFiles:function(fileInput){fileInput=$(fileInput);var entries=fileInput.prop("webkitEntries")||fileInput.prop("entries"),files,value;if(entries&&entries.length){return this._handleFileTreeEntries(entries);}files=$.makeArray(fileInput.prop("files"));if(!files.length){value=fileInput.prop("value");if(!value){return $.Deferred().resolve([]).promise();}files=[{name:value.replace(/^.*\\/,"")}];}else{if(files[0].name===undefined&&files[0].fileName){$.each(files,function(index,file){file.name=file.fileName;file.size=file.fileSize;});}}return $.Deferred().resolve(files).promise();},_getFileInputFiles:function(fileInput){if(!(fileInput instanceof $)||fileInput.length===1){return this._getSingleFileInputFiles(fileInput);}return $.when.apply($,$.map(fileInput,this._getSingleFileInputFiles)).pipe(function(){return Array.prototype.concat.apply([],arguments);});},_onChange:function(e){var that=this,data={fileInput:$(e.target),form:$(e.target.form)};this._getFileInputFiles(data.fileInput).always(function(files){data.files=files;if(that.options.replaceFileInput){that._replaceFileInput(data);}if(that._trigger("change",$.Event("change",{delegatedEvent:e}),data)!==false){that._onAdd(e,data);}});},_onPaste:function(e){var items=e.originalEvent&&e.originalEvent.clipboardData&&e.originalEvent.clipboardData.items,data={files:[]};if(items&&items.length){$.each(items,function(index,item){var file=item.getAsFile&&item.getAsFile();if(file){data.files.push(file);}});if(this._trigger("paste",$.Event("paste",{delegatedEvent:e}),data)!==false){this._onAdd(e,data);}}},_onDrop:function(e){e.dataTransfer=e.originalEvent&&e.originalEvent.dataTransfer;var that=this,dataTransfer=e.dataTransfer,data={};if(dataTransfer&&dataTransfer.files&&dataTransfer.files.length){e.preventDefault();this._getDroppedFiles(dataTransfer).always(function(files){data.files=files;if(that._trigger("drop",$.Event("drop",{delegatedEvent:e}),data)!==false){that._onAdd(e,data);}});}},_onDragOver:getDragHandler("dragover"),_onDragEnter:getDragHandler("dragenter"),_onDragLeave:getDragHandler("dragleave"),_initEventHandlers:function(){if(this._isXHRUpload(this.options)){this._on(this.options.dropZone,{dragover:this._onDragOver,drop:this._onDrop,dragenter:this._onDragEnter,dragleave:this._onDragLeave});this._on(this.options.pasteZone,{paste:this._onPaste});}if($.support.fileInput){this._on(this.options.fileInput,{change:this._onChange});}},_destroyEventHandlers:function(){this._off(this.options.dropZone,"dragenter dragleave dragover drop");this._off(this.options.pasteZone,"paste");this._off(this.options.fileInput,"change");},_setOption:function(key,value){var reinit=$.inArray(key,this._specialOptions)!==-1;if(reinit){this._destroyEventHandlers();}this._super(key,value);if(reinit){this._initSpecialOptions();this._initEventHandlers();}},_initSpecialOptions:function(){var options=this.options;if(options.fileInput===undefined){options.fileInput=this.element.is('input[type="file"]')?this.element:this.element.find('input[type="file"]');}else{if(!(options.fileInput instanceof $)){options.fileInput=$(options.fileInput);}}if(!(options.dropZone instanceof $)){options.dropZone=$(options.dropZone);}if(!(options.pasteZone instanceof $)){options.pasteZone=$(options.pasteZone);}},_getRegExp:function(str){var parts=str.split("/"),modifiers=parts.pop();parts.shift();return new RegExp(parts.join("/"),modifiers);},_isRegExpOption:function(key,value){return key!=="url"&&$.type(value)==="string"&&/^\/.*\/[igm]{0,3}$/.test(value);},_initDataAttributes:function(){var that=this,options=this.options,clone=$(this.element[0].cloneNode(false)),data=clone.data();clone.remove();$.each(data,function(key,value){var dataAttributeName="data-"+key.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();if(clone.attr(dataAttributeName)){if(that._isRegExpOption(key,value)){value=that._getRegExp(value);}options[key]=value;}});},_create:function(){this._initDataAttributes();this._initSpecialOptions();this._slots=[];this._sequence=this._getXHRPromise(true);this._sending=this._active=0;this._initProgressObject(this);this._initEventHandlers();},active:function(){return this._active;},progress:function(){return this._progress;},add:function(data){var that=this;if(!data||this.options.disabled){return;}if(data.fileInput&&!data.files){this._getFileInputFiles(data.fileInput).always(function(files){data.files=files;that._onAdd(null,data);});}else{data.files=$.makeArray(data.files);this._onAdd(null,data);}},send:function(data){if(data&&!this.options.disabled){if(data.fileInput&&!data.files){var that=this,dfd=$.Deferred(),promise=dfd.promise(),jqXHR,aborted;promise.abort=function(){aborted=true;if(jqXHR){return jqXHR.abort();}dfd.reject(null,"abort","abort");return promise;};this._getFileInputFiles(data.fileInput).always(function(files){if(aborted){return;}if(!files.length){dfd.reject();return;}data.files=files;jqXHR=that._onSend(null,data);jqXHR.then(function(result,textStatus,jqXHR){dfd.resolve(result,textStatus,jqXHR);},function(jqXHR,textStatus,errorThrown){dfd.reject(jqXHR,textStatus,errorThrown);});});return this._enhancePromise(promise);}data.files=$.makeArray(data.files);if(data.files.length){return this._onSend(null,data);}}return this._getXHRPromise(false,data&&data.context);}});})); diff --git a/media/scripts/lib/jquery.fileupload.file-processing.1.3.0.js b/media/scripts/lib/jquery.fileupload.file-processing.1.3.0.js new file mode 100644 index 0000000000..8c7253f83f --- /dev/null +++ b/media/scripts/lib/jquery.fileupload.file-processing.1.3.0.js @@ -0,0 +1,11 @@ +/* + * jQuery File Upload File Processing Plugin 1.3.0 + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2012, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/MIT + */ +(function(factory){if(typeof define==="function"&&define.amd){define(["jquery","jquery.fileupload"],factory);}else{factory(window.jQuery);}}(function($){var originalAdd=$.blueimp.fileupload.prototype.options.add;$.widget("blueimp.fileupload",$.blueimp.fileupload,{options:{processQueue:[],add:function(e,data){var $this=$(this);data.process(function(){return $this.fileupload("process",data);});originalAdd.call(this,e,data);}},processActions:{},_processFile:function(data,originalData){var that=this,dfd=$.Deferred().resolveWith(that,[data]),chain=dfd.promise();this._trigger("process",null,data);$.each(data.processQueue,function(i,settings){var func=function(data){if(originalData.errorThrown){return $.Deferred().rejectWith(that,[originalData]).promise();}return that.processActions[settings.action].call(that,data,settings);};chain=chain.pipe(func,settings.always&&func);});chain.done(function(){that._trigger("processdone",null,data);that._trigger("processalways",null,data);}).fail(function(){that._trigger("processfail",null,data);that._trigger("processalways",null,data);});return chain;},_transformProcessQueue:function(options){var processQueue=[];$.each(options.processQueue,function(){var settings={},action=this.action,prefix=this.prefix===true?action:this.prefix;$.each(this,function(key,value){if($.type(value)==="string"&&value.charAt(0)==="@"){settings[key]=options[value.slice(1)||(prefix?prefix+key.charAt(0).toUpperCase()+key.slice(1):key)];}else{settings[key]=value;}});processQueue.push(settings);});options.processQueue=processQueue;},processing:function(){return this._processing;},process:function(data){var that=this,options=$.extend({},this.options,data);if(options.processQueue&&options.processQueue.length){this._transformProcessQueue(options);if(this._processing===0){this._trigger("processstart");}$.each(data.files,function(index){var opts=index?$.extend({},options):options,func=function(){if(data.errorThrown){return $.Deferred().rejectWith(that,[data]).promise();}return that._processFile(opts,data);};opts.index=index;that._processing+=1;that._processingQueue=that._processingQueue.pipe(func,func).always(function(){that._processing-=1;if(that._processing===0){that._trigger("processstop");}});});}return this._processingQueue;},_create:function(){this._super();this._processing=0;this._processingQueue=$.Deferred().resolveWith(this).promise();}});})); diff --git a/media/scripts/lib/jquery.fileupload.ui.9.6.0.js b/media/scripts/lib/jquery.fileupload.ui.9.6.0.js new file mode 100644 index 0000000000..b1a169ca27 --- /dev/null +++ b/media/scripts/lib/jquery.fileupload.ui.9.6.0.js @@ -0,0 +1,15 @@ +/* + * jQuery File Upload User Interface Plugin 9.6.0 + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2010, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/MIT + */ +(function(factory){if(typeof define==="function"&&define.amd){define(["jquery","tmpl","jquery.iframe-transport","jquery.fileupload-validate"],factory);}else{factory(window.jQuery,window.tmpl);}}(function($,tmpl){$.blueimp.fileupload.prototype._specialOptions.push("filesContainer","uploadTemplateId","downloadTemplateId");$.widget("blueimp.fileupload",$.blueimp.fileupload,{options:{autoUpload:false,uploadTemplateId:"template-upload",downloadTemplateId:"template-download",filesContainer:undefined,prependFiles:false,dataType:"json",messages:{unknownError:"Unknown error"},getNumberOfFiles:function(){return this.filesContainer.children().not(".processing").length;},getFilesFromResponse:function(data){if(data.result&&$.isArray(data.result.files)){return data.result.files;}return[];},add:function(e,data){if(e.isDefaultPrevented()){return false;}var $this=$(this),that=$this.data("blueimp-fileupload")||$this.data("fileupload"),options=that.options;data.context=that._renderUpload(data.files).data("data",data).addClass("processing");options.filesContainer[options.prependFiles?"prepend":"append"](data.context);that._forceReflow(data.context);that._transition(data.context);data.process(function(){return $this.fileupload("process",data);}).always(function(){data.context.each(function(index){$(this).find(".size").text(that._formatFileSize(data.files[index].size));}).removeClass("processing");that._renderPreviews(data);}).done(function(){data.context.find(".start").prop("disabled",false);if((that._trigger("added",e,data)!==false)&&(options.autoUpload||data.autoUpload)&&data.autoUpload!==false){data.submit();}}).fail(function(){if(data.files.error){data.context.each(function(index){var error=data.files[index].error;if(error){$(this).find(".error").text(error);}});}});},send:function(e,data){if(e.isDefaultPrevented()){return false;}var that=$(this).data("blueimp-fileupload")||$(this).data("fileupload");if(data.context&&data.dataType&&data.dataType.substr(0,6)==="iframe"){data.context.find(".progress").addClass(!$.support.transition&&"progress-animated").attr("aria-valuenow",100).children().first().css("width","100%");}return that._trigger("sent",e,data);},done:function(e,data){if(e.isDefaultPrevented()){return false;}var that=$(this).data("blueimp-fileupload")||$(this).data("fileupload"),getFilesFromResponse=data.getFilesFromResponse||that.options.getFilesFromResponse,files=getFilesFromResponse(data),template,deferred;if(data.context){data.context.each(function(index){var file=files[index]||{error:"Empty file upload result"};deferred=that._addFinishedDeferreds();that._transition($(this)).done(function(){var node=$(this);template=that._renderDownload([file]).replaceAll(node);that._forceReflow(template);that._transition(template).done(function(){data.context=$(this);that._trigger("completed",e,data);that._trigger("finished",e,data);deferred.resolve();});});});}else{template=that._renderDownload(files)[that.options.prependFiles?"prependTo":"appendTo"](that.options.filesContainer);that._forceReflow(template);deferred=that._addFinishedDeferreds();that._transition(template).done(function(){data.context=$(this);that._trigger("completed",e,data);that._trigger("finished",e,data);deferred.resolve();});}}, + // modified 'abort/cancel', by lj. Mon Dec 15 15:44:04 CST 2014 + fail:function(e,data){if(e.isDefaultPrevented()){return false;}var that=$(this).data("blueimp-fileupload")||$(this).data("fileupload"),template,deferred;if(data.context){data.context.each(function(index){ + var file=data.files[index];if(data.errorThrown!=="abort"){file.error=file.error||data.errorThrown||data.i18n("unknownError");}else{file.canceled=true;} + deferred=that._addFinishedDeferreds();that._transition($(this)).done(function(){var node=$(this);template=that._renderDownload([file]).replaceAll(node);that._forceReflow(template);that._transition(template).done(function(){data.context=$(this);that._trigger("failed",e,data);that._trigger("finished",e,data);deferred.resolve();});});});}else{if(data.errorThrown!=="abort"){data.context=that._renderUpload(data.files)[that.options.prependFiles?"prependTo":"appendTo"](that.options.filesContainer).data("data",data);that._forceReflow(data.context);deferred=that._addFinishedDeferreds();that._transition(data.context).done(function(){data.context=$(this);that._trigger("failed",e,data);that._trigger("finished",e,data);deferred.resolve();});}else{that._trigger("failed",e,data);that._trigger("finished",e,data);that._addFinishedDeferreds().resolve();}}},progress:function(e,data){if(e.isDefaultPrevented()){return false;}var progress=Math.floor(data.loaded/data.total*100);if(data.context){data.context.each(function(){$(this).find(".progress").attr("aria-valuenow",progress).children().first().css("width",progress+"%");});}},progressall:function(e,data){if(e.isDefaultPrevented()){return false;}var $this=$(this),progress=Math.floor(data.loaded/data.total*100),globalProgressNode=$this.find(".fileupload-progress"),extendedProgressNode=globalProgressNode.find(".progress-extended");if(extendedProgressNode.length){extendedProgressNode.html(($this.data("blueimp-fileupload")||$this.data("fileupload"))._renderExtendedProgress(data));}globalProgressNode.find(".progress").attr("aria-valuenow",progress).children().first().css("width",progress+"%");},start:function(e){if(e.isDefaultPrevented()){return false;}var that=$(this).data("blueimp-fileupload")||$(this).data("fileupload");that._resetFinishedDeferreds();that._transition($(this).find(".fileupload-progress")).done(function(){that._trigger("started",e);});},stop:function(e){if(e.isDefaultPrevented()){return false;}var that=$(this).data("blueimp-fileupload")||$(this).data("fileupload"),deferred=that._addFinishedDeferreds();$.when.apply($,that._getFinishedDeferreds()).done(function(){that._trigger("stopped",e);});that._transition($(this).find(".fileupload-progress")).done(function(){$(this).find(".progress").attr("aria-valuenow","0").children().first().css("width","0%");$(this).find(".progress-extended").html(" ");deferred.resolve();});},processstart:function(e){if(e.isDefaultPrevented()){return false;}$(this).addClass("fileupload-processing");},processstop:function(e){if(e.isDefaultPrevented()){return false;}$(this).removeClass("fileupload-processing");},destroy:function(e,data){if(e.isDefaultPrevented()){return false;}var that=$(this).data("blueimp-fileupload")||$(this).data("fileupload"),removeNode=function(){that._transition(data.context).done(function(){$(this).remove();that._trigger("destroyed",e,data);});};if(data.url){data.dataType=data.dataType||that.options.dataType;$.ajax(data).done(removeNode).fail(function(){that._trigger("destroyfailed",e,data);});}else{removeNode();}}},_resetFinishedDeferreds:function(){this._finishedUploads=[];},_addFinishedDeferreds:function(deferred){if(!deferred){deferred=$.Deferred();}this._finishedUploads.push(deferred);return deferred;},_getFinishedDeferreds:function(){return this._finishedUploads;},_enableDragToDesktop:function(){var link=$(this),url=link.prop("href"),name=link.prop("download"),type="application/octet-stream";link.bind("dragstart",function(e){try{e.originalEvent.dataTransfer.setData("DownloadURL",[type,name,url].join(":"));}catch(ignore){}});},_formatFileSize:function(bytes){if(typeof bytes!=="number"){return"";}if(bytes>=1000000000){return(bytes/1000000000).toFixed(2)+" GB";}if(bytes>=1000000){return(bytes/1000000).toFixed(2)+" MB";}return(bytes/1000).toFixed(2)+" KB";},_formatBitrate:function(bits){if(typeof bits!=="number"){return"";}bits = bits/8;if(bits>=1000000000){return(bits/1000000000).toFixed(2)+" GB/s";}if(bits>=1000000){return(bits/1000000).toFixed(2)+" MB/s";}if(bits>=1000){return(bits/1000).toFixed(2)+" KB/s";}return bits.toFixed(2)+" B/s";},_formatTime:function(seconds){var date=new Date(seconds*1000),days=Math.floor(seconds/86400);days=days?days+"d ":"";return days+("0"+date.getUTCHours()).slice(-2)+":"+("0"+date.getUTCMinutes()).slice(-2)+":"+("0"+date.getUTCSeconds()).slice(-2);},_formatPercentage:function(floatValue){return(floatValue*100).toFixed(2)+" %";},_renderExtendedProgress:function(data){return this._formatBitrate(data.bitrate)+" | "+this._formatTime((data.total-data.loaded)*8/data.bitrate)+" | "+this._formatPercentage(data.loaded/data.total)+" | "+this._formatFileSize(data.loaded)+" / "+this._formatFileSize(data.total);},_renderTemplate:function(func,files){if(!func){return $();}var result=func({files:files,formatFileSize:this._formatFileSize,options:this.options});if(result instanceof $){return result;}return $(this.options.templatesContainer).html(result).children();},_renderPreviews:function(data){data.context.find(".preview").each(function(index,elm){$(elm).append(data.files[index].preview);});},_renderUpload:function(files){return this._renderTemplate(this.options.uploadTemplate,files);},_renderDownload:function(files){return this._renderTemplate(this.options.downloadTemplate,files).find("a[download]").each(this._enableDragToDesktop).end();},_startHandler:function(e){e.preventDefault();var button=$(e.currentTarget),template=button.closest(".template-upload"),data=template.data("data");button.prop("disabled",true);if(data&&data.submit){data.submit();}},_cancelHandler:function(e){e.preventDefault();var template=$(e.currentTarget).closest(".template-upload,.template-download"),data=template.data("data")||{};data.context=data.context||template;if(data.abort){data.abort();}else{data.errorThrown="abort";this._trigger("fail",e,data);}},_deleteHandler:function(e){e.preventDefault();var button=$(e.currentTarget);this._trigger("destroy",e,$.extend({context:button.closest(".template-download"),type:"DELETE"},button.data()));},_forceReflow:function(node){return $.support.transition&&node.length&&node[0].offsetWidth;},_transition:function(node){var dfd=$.Deferred();if($.support.transition&&node.hasClass("fade")&&node.is(":visible")){node.bind($.support.transition.end,function(e){if(e.target===node[0]){node.unbind($.support.transition.end);dfd.resolveWith(node);}}).toggleClass("in");}else{node.toggleClass("in");dfd.resolveWith(node);}return dfd;},_initButtonBarEventHandlers:function(){var fileUploadButtonBar=this.element.find(".fileupload-buttonbar"),filesList=this.options.filesContainer;this._on(fileUploadButtonBar.find(".start"),{click:function(e){e.preventDefault();filesList.find(".start").click();}});this._on(fileUploadButtonBar.find(".cancel"),{click:function(e){e.preventDefault();filesList.find(".cancel").click();}});this._on(fileUploadButtonBar.find(".delete"),{click:function(e){e.preventDefault();filesList.find(".toggle:checked").closest(".template-download").find(".delete").click();fileUploadButtonBar.find(".toggle").prop("checked",false);}});this._on(fileUploadButtonBar.find(".toggle"),{change:function(e){filesList.find(".toggle").prop("checked",$(e.currentTarget).is(":checked"));}});},_destroyButtonBarEventHandlers:function(){this._off(this.element.find(".fileupload-buttonbar").find(".start, .cancel, .delete"),"click");this._off(this.element.find(".fileupload-buttonbar .toggle"),"change.");},_initEventHandlers:function(){this._super();this._on(this.options.filesContainer,{"click .start":this._startHandler,"click .cancel":this._cancelHandler,"click .delete":this._deleteHandler});this._initButtonBarEventHandlers();},_destroyEventHandlers:function(){this._destroyButtonBarEventHandlers();this._off(this.options.filesContainer,"click");this._super();},_enableFileInputButton:function(){this.element.find(".fileinput-button input").prop("disabled",false).parent().removeClass("disabled");},_disableFileInputButton:function(){this.element.find(".fileinput-button input").prop("disabled",true).parent().addClass("disabled");},_initTemplates:function(){var options=this.options;options.templatesContainer=this.document[0].createElement(options.filesContainer.prop("nodeName"));if(tmpl){if(options.uploadTemplateId){options.uploadTemplate=tmpl(options.uploadTemplateId);}if(options.downloadTemplateId){options.downloadTemplate=tmpl(options.downloadTemplateId);}}},_initFilesContainer:function(){var options=this.options;if(options.filesContainer===undefined){options.filesContainer=this.element.find(".files");}else{if(!(options.filesContainer instanceof $)){options.filesContainer=$(options.filesContainer);}}},_initSpecialOptions:function(){this._super();this._initFilesContainer();this._initTemplates();},_create:function(){this._super();this._resetFinishedDeferreds();if(!$.support.fileInput){this._disableFileInputButton();}},enable:function(){var wasDisabled=false;if(this.options.disabled){wasDisabled=true;}this._super();if(wasDisabled){this.element.find("input, button").prop("disabled",false);this._enableFileInputButton();}},disable:function(){if(!this.options.disabled){this.element.find("input, button").prop("disabled",true);this._disableFileInputButton();}this._super();}});})); diff --git a/media/scripts/lib/jquery.fileupload.validation.1.1.2.js b/media/scripts/lib/jquery.fileupload.validation.1.1.2.js new file mode 100644 index 0000000000..40599748ab --- /dev/null +++ b/media/scripts/lib/jquery.fileupload.validation.1.1.2.js @@ -0,0 +1,13 @@ +/* + * jQuery File Upload Validation Plugin 1.1.2 + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2013, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/MIT + */ + +/* global define, window */ +(function(factory){if(typeof define==="function"&&define.amd){define(["jquery","jquery.fileupload-process"],factory);}else{factory(window.jQuery);}}(function($){$.blueimp.fileupload.prototype.options.processQueue.push({action:"validate",always:true,acceptFileTypes:"@",maxFileSize:"@",minFileSize:"@",maxNumberOfFiles:"@",disabled:"@disableValidation"});$.widget("blueimp.fileupload",$.blueimp.fileupload,{options:{getNumberOfFiles:$.noop,messages:{maxNumberOfFiles:"Maximum number of files exceeded",acceptFileTypes:"File type not allowed",maxFileSize:"File is too large",minFileSize:"File is too small"}},processActions:{validate:function(data,options){if(options.disabled){return data;}var dfd=$.Deferred(),settings=this.options,file=data.files[data.index],fileSize;if(options.minFileSize||options.maxFileSize){fileSize=file.size;}if($.type(options.maxNumberOfFiles)==="number"&&(settings.getNumberOfFiles()||0)+data.files.length>options.maxNumberOfFiles){file.error=settings.i18n("maxNumberOfFiles");}else{if(options.acceptFileTypes&&!(options.acceptFileTypes.test(file.type)||options.acceptFileTypes.test(file.name))){file.error=settings.i18n("acceptFileTypes");}else{if(fileSize>options.maxFileSize){file.error=settings.i18n("maxFileSize");}else{if($.type(fileSize)==="number"&&fileSize');iframe=$('').bind("load",function(){var fileInputClones,paramNames=$.isArray(options.paramName)?options.paramName:[options.paramName];iframe.unbind("load").bind("load",function(){var response;try{response=iframe.contents();if(!response.length||!response[0].firstChild){throw new Error();}}catch(e){response=undefined;}completeCallback(200,"success",{"iframe":response});$('').appendTo(form);form.remove();});form.prop("target",iframe.prop("name")).prop("action",options.url).prop("method",options.type);if(options.formData){$.each(options.formData,function(index,field){$('').prop("name",field.name).val(field.value).appendTo(form);});}if(options.fileInput&&options.fileInput.length&&options.type==="POST"){fileInputClones=options.fileInput.clone();options.fileInput.after(function(index){return fileInputClones[index];});if(options.paramName){options.fileInput.each(function(index){$(this).prop("name",paramNames[index]||options.paramName);});}form.append(options.fileInput).prop("enctype","multipart/form-data").prop("encoding","multipart/form-data");}form.submit();if(fileInputClones&&fileInputClones.length){options.fileInput.each(function(index,input){var clone=$(fileInputClones[index]);$(input).prop("name",clone.prop("name"));clone.replaceWith(input);});}});form.append(iframe).appendTo(document.body);},abort:function(){if(iframe){iframe.unbind("load").prop("src","javascript".concat(":false;"));}if(form){form.remove();}}};}});$.ajaxSetup({converters:{"iframe text":function(iframe){return $(iframe[0].body).text();},"iframe json":function(iframe){return $.parseJSON($(iframe[0].body).text());},"iframe html":function(iframe){return $(iframe[0].body).html();},"iframe script":function(iframe){return $.globalEval($(iframe[0].body).text());}}});})); diff --git a/media/scripts/lib/jquery.ui.widget.1.11.1.js b/media/scripts/lib/jquery.ui.widget.1.11.1.js new file mode 100644 index 0000000000..b011fc6cd4 --- /dev/null +++ b/media/scripts/lib/jquery.ui.widget.1.11.1.js @@ -0,0 +1,16 @@ +/*! jQuery UI - v1.11.1 - 2014-09-17 +* http://jqueryui.com +* Includes: widget.js +* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ +(function(factory){if(typeof define==="function"&&define.amd){define(["jquery"],factory);}else{factory(jQuery);}}(function($){ +/*! + * jQuery UI Widget 1.11.1 + * http://jqueryui.com + * + * Copyright 2014 jQuery Foundation and other contributors + * Released under the MIT license. + * http://jquery.org/license + * + * http://api.jqueryui.com/jQuery.widget/ + */ +var widget_uuid=0,widget_slice=Array.prototype.slice;$.cleanData=(function(orig){return function(elems){var events,elem,i;for(i=0;(elem=elems[i])!=null;i++){try{events=$._data(elem,"events");if(events&&events.remove){$(elem).triggerHandler("remove");}}catch(e){}}orig(elems);};})($.cleanData);$.widget=function(name,base,prototype){var fullName,existingConstructor,constructor,basePrototype,proxiedPrototype={},namespace=name.split(".")[0];name=name.split(".")[1];fullName=namespace+"-"+name;if(!prototype){prototype=base;base=$.Widget;}$.expr[":"][fullName.toLowerCase()]=function(elem){return !!$.data(elem,fullName);};$[namespace]=$[namespace]||{};existingConstructor=$[namespace][name];constructor=$[namespace][name]=function(options,element){if(!this._createWidget){return new constructor(options,element);}if(arguments.length){this._createWidget(options,element);}};$.extend(constructor,existingConstructor,{version:prototype.version,_proto:$.extend({},prototype),_childConstructors:[]});basePrototype=new base();basePrototype.options=$.widget.extend({},basePrototype.options);$.each(prototype,function(prop,value){if(!$.isFunction(value)){proxiedPrototype[prop]=value;return;}proxiedPrototype[prop]=(function(){var _super=function(){return base.prototype[prop].apply(this,arguments);},_superApply=function(args){return base.prototype[prop].apply(this,args);};return function(){var __super=this._super,__superApply=this._superApply,returnValue;this._super=_super;this._superApply=_superApply;returnValue=value.apply(this,arguments);this._super=__super;this._superApply=__superApply;return returnValue;};})();});constructor.prototype=$.widget.extend(basePrototype,{widgetEventPrefix:existingConstructor?(basePrototype.widgetEventPrefix||name):name},proxiedPrototype,{constructor:constructor,namespace:namespace,widgetName:name,widgetFullName:fullName});if(existingConstructor){$.each(existingConstructor._childConstructors,function(i,child){var childPrototype=child.prototype;$.widget(childPrototype.namespace+"."+childPrototype.widgetName,constructor,child._proto);});delete existingConstructor._childConstructors;}else{base._childConstructors.push(constructor);}$.widget.bridge(name,constructor);return constructor;};$.widget.extend=function(target){var input=widget_slice.call(arguments,1),inputIndex=0,inputLength=input.length,key,value;for(;inputIndex",options:{disabled:false,create:null},_createWidget:function(options,element){element=$(element||this.defaultElement||this)[0];this.element=$(element);this.uuid=widget_uuid++;this.eventNamespace="."+this.widgetName+this.uuid;this.options=$.widget.extend({},this.options,this._getCreateOptions(),options);this.bindings=$();this.hoverable=$();this.focusable=$();if(element!==this){$.data(element,this.widgetFullName,this);this._on(true,this.element,{remove:function(event){if(event.target===element){this.destroy();}}});this.document=$(element.style?element.ownerDocument:element.document||element);this.window=$(this.document[0].defaultView||this.document[0].parentWindow);}this._create();this._trigger("create",null,this._getCreateEventData());this._init();},_getCreateOptions:$.noop,_getCreateEventData:$.noop,_create:$.noop,_init:$.noop,destroy:function(){this._destroy();this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData($.camelCase(this.widgetFullName));this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled ui-state-disabled");this.bindings.unbind(this.eventNamespace);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus");},_destroy:$.noop,widget:function(){return this.element;},option:function(key,value){var options=key,parts,curOption,i;if(arguments.length===0){return $.widget.extend({},this.options);}if(typeof key==="string"){options={};parts=key.split(".");key=parts.shift();if(parts.length){curOption=options[key]=$.widget.extend({},this.options[key]);for(i=0;i&"'\x00]/g,b.encMap={"<":"<",">":">","&":"&",'"':""","'":"'"},b.encode=function(a){return String(a||"").replace(b.encReg,function(a){return b.encMap[a]||""})},b.arg="o",b.helper=",print=function(s,e){_s+=e&&(s||'')||_e(s);},include=function(s,d){_s+=tmpl(s,d);}",typeof define=="function"&&define.amd?define(function(){return b}):a.tmpl=b})(this); diff --git a/seahub/templates/js/lib-op-popups.html b/seahub/templates/js/lib-op-popups.html index b61659e2d3..566b1af532 100644 --- a/seahub/templates/js/lib-op-popups.html +++ b/seahub/templates/js/lib-op-popups.html @@ -1,4 +1,4 @@ -{% load i18n %} +{% load i18n upload_tags %} + {% upload_js %} + +

{% trans "File Upload" %}

@@ -98,6 +101,7 @@
+

{% trans "Update %(file_name)s" %}

diff --git a/seahub/templates/myhome.html b/seahub/templates/myhome.html index d70bd0c2f9..70e122c3ca 100644 --- a/seahub/templates/myhome.html +++ b/seahub/templates/myhome.html @@ -224,10 +224,9 @@ app["pageOptions"] = { base_url: "{{ SITE_ROOT }}" + "home/my/", csrfToken: "{{ csrf_token }}", - reposUrl: "{% url 'api2-repos' %}" -}; -app.globalState = { - enable_upload_folder: {% if enable_upload_folder %} true {% else %} false {% endif %} + reposUrl: "{% url 'api2-repos' %}", + enable_upload_folder: {% if enable_upload_folder %} true {% else %} false {% endif %}, + max_upload_file_size: {% if max_upload_file_size %} {{ max_upload_file_size }} {% else %} '' {% endif %} }; {% if debug %} diff --git a/seahub/views/__init__.py b/seahub/views/__init__.py index 6c33d39e11..f2b4cad857 100644 --- a/seahub/views/__init__.py +++ b/seahub/views/__init__.py @@ -53,7 +53,8 @@ from seahub.utils import render_permission_error, render_error, list_to_string, gen_file_get_url, string2list, MAX_INT, IS_EMAIL_CONFIGURED, \ EVENTS_ENABLED, get_user_events, get_org_user_events, show_delete_days, \ TRAFFIC_STATS_ENABLED, get_user_traffic_stat, new_merge_with_no_conflict, \ - user_traffic_over_limit, send_perm_audit_msg, get_origin_repo_info + user_traffic_over_limit, send_perm_audit_msg, get_origin_repo_info, \ + is_org_context, get_max_upload_file_size from seahub.utils.paginator import get_page_range from seahub.utils.star import get_dir_starred_files from seahub.utils.timeutils import utc_to_local @@ -1166,6 +1167,8 @@ def myhome(request): repo_create_url = reverse("repo_create") + max_upload_file_size = get_max_upload_file_size() + return render_to_response('myhome.html', { "owned_repos": owned_repos, "create_shared_repo": False, @@ -1176,6 +1179,7 @@ def myhome(request): "sub_repos": sub_repos, "repo_create_url": repo_create_url, 'enable_upload_folder': settings.ENABLE_UPLOAD_FOLDER, + 'max_upload_file_size': max_upload_file_size, }, context_instance=RequestContext(request)) @login_required