Răsfoiți Sursa

HUE-5968 [filebrowser] Unify the file/archive upload and show extract after upload

1. Now there will be only 1 button to upload a file
2. If it's an archive, we select it after upload and the extract button shows up.
krish 8 ani în urmă
părinte
comite
f66d9b1

+ 3 - 8
apps/filebrowser/src/filebrowser/templates/listdir.mako

@@ -103,7 +103,7 @@ ${ fb_components.menubar() }
                 <li><a href="javascript: void(0)" title="${_('Compress selection into a single archive')}" data-bind="click: function() { setCompressArchiveDefault(); confirmCompressFiles();}, visible: showCompressButton">
                   <i class="fa fa-fw fa-file-archive-o"></i> ${_('Compress')}</a>
                 </li>
-                <li><a href="javascript: void(0)" title="${_('Extract selected archive')}" data-bind="visible: selectedFiles().length == 1 && isArchive() && !isS3(), click: confirmExtractArchive">
+                <li><a href="javascript: void(0)" title="${_('Extract selected archive')}" data-bind="visible: selectedFiles().length == 1 && isArchive(selectedFile().name) && !isS3(), click: confirmExtractArchive">
                   <i class="fa fa-fw fa-file-archive-o"></i> ${_('Extract')}</a>
                 </li>
               % endif
@@ -134,7 +134,7 @@ ${ fb_components.menubar() }
             </button>
             % if ENABLE_EXTRACT_UPLOADED_ARCHIVE.get():
               <button class="btn extractArchiveBtn" title="${_('Extract')}"
-                data-bind="visible: selectedFiles().length == 1 && isArchive() && !isS3(), click: confirmExtractArchive">
+                data-bind="visible: selectedFiles().length == 1 && isArchive(selectedFile().name) && !isS3(), click: confirmExtractArchive">
                 <i class="fa fa-fw fa-file-archive-o"></i> ${_('Extract')}
               </button>
             % endif
@@ -157,14 +157,9 @@ ${ fb_components.menubar() }
           <!-- /ko -->
           <!-- ko ifnot: isS3 -->
           <div id="upload-dropdown" class="btn-group" style="vertical-align: middle">
-            <a href="javascript: void(0)" class="btn upload-link dropdown-toggle" title="${_('Upload')}" data-toggle="dropdown" data-bind="visible: !inTrash(), css: {'disabled': isS3() && isS3Root()}">
+            <a href="javascript: void(0)" class="btn upload-link dropdown-toggle" title="${_('Upload')}" data-bind="click: uploadFile, visible: !inTrash(), css: {'disabled': isS3() && isS3Root()}">
               <i class="fa fa-arrow-circle-o-up"></i> ${_('Upload')}
-              <span class="caret"></span>
             </a>
-            <ul class="dropdown-menu">
-              <li><a href="javascript: void(0)" class="upload-link" title="${_('Files')}" data-bind="click: uploadFile"><i class="fa fa-file-o"></i> ${_('Files')}</a></li>
-              <li><a href="javascript: void(0)" class="upload-link" title="${_('Archive')}" data-bind="click: uploadArchive"><i class="fa fa-gift"></i> ${_('Zip/Tgz/Bz2 file')}</a></li>
-            </ul>
           </div>
           <!-- /ko -->
           % endif

+ 6 - 111
apps/filebrowser/src/filebrowser/templates/listdir_components.mako

@@ -449,22 +449,6 @@ from filebrowser.conf import ENABLE_EXTRACT_UPLOADED_ARCHIVE
     <div class="modal-footer"></div>
   </div>
 
-  <!-- upload archive modal -->
-  <div id="uploadArchiveModal" class="modal hide fade">
-    <div class="modal-header">
-      <button type="button" class="close" data-dismiss="modal" aria-label="${ _('Close') }"><span aria-hidden="true">&times;</span></button>
-      <h2 class="modal-title">${_('Upload and extract in')} <span data-bind="text: currentPath"></span></h2>
-    </div>
-    <div class="modal-body form-inline">
-      <div id="archiveUploader" class="uploader">
-        <noscript>
-          <p>${_('Enable JavaScript to use the file uploader.')}</p>
-        </noscript>
-      </div>
-    </div>
-    <div class="modal-footer"></div>
-  </div>
-
   <!-- new directory modal -->
   <form id="createDirectoryForm" data-bind="submit: createDirectory" method="POST" enctype="multipart/form-data" class="form-inline form-padding-fix">
     ${ csrf_token(request) | n,unicode }
@@ -622,8 +606,8 @@ from filebrowser.conf import ENABLE_EXTRACT_UPLOADED_ARCHIVE
         <a href="javascript: void(0)" title="${_('Compress selection into a single archive')}" data-bind="click: function() { if(showCompressButton) { setCompressArchiveDefault(); confirmCompressFiles();}}">
         <i class="fa fa-fw fa-file-archive-o"></i> ${_('Compress')}</a>
       </li>
-      <li data-bind="css: {'disabled': selectedFiles().length != 1 || !isArchive() || isS3()}">
-        <a href="javascript: void(0)" title="${_('Extract selected archive')}" data-bind="click: (selectedFiles().length == 1 && isArchive() && !isS3()) ? confirmExtractArchive : void(0)">
+      <li data-bind="css: {'disabled': selectedFiles().length != 1 || !isArchive(selectedFile().name) || isS3()}">
+        <a href="javascript: void(0)" title="${_('Extract selected archive')}" data-bind="click: (selectedFiles().length == 1 && isArchive(selectedFile().name) && !isS3()) ? confirmExtractArchive : void(0)">
         <i class="fa fa-fw fa-file-archive-o"></i> ${_('Extract')}</a>
       </li>
     % endif
@@ -858,7 +842,7 @@ from filebrowser.conf import ENABLE_EXTRACT_UPLOADED_ARCHIVE
         isBucket: ko.pureComputed(function(){
           return file.path.toLowerCase().indexOf('s3a://') == 0 && file.path.substr(5).indexOf('/') == -1
         }),
-        selected: ko.observable(false),
+        selected: ko.observable(file.highlighted && viewModel.isArchive(file.name) || false),
         highlighted: ko.observable(file.highlighted || false),
         deleted: ko.observable(file.deleted || false),
         handleSelect: function (row, e) {
@@ -955,12 +939,6 @@ from filebrowser.conf import ENABLE_EXTRACT_UPLOADED_ARCHIVE
               $('#uploadFileModal').data('modal').$backdrop.off('click');
             }
           }
-          if ($('#uploadArchiveModal').data('modal')) {
-            $('#uploadArchiveModal').data('modal').$element.off('keyup.dismiss.modal');
-            if ($('#uploadArchiveModal').data('modal').$backdrop) {
-              $('#uploadArchiveModal').data('modal').$backdrop.off('click');
-            }
-          }
         }
       });
       self.filesToHighlight = ko.observableArray([]);
@@ -1640,8 +1618,7 @@ from filebrowser.conf import ENABLE_EXTRACT_UPLOADED_ARCHIVE
         % endif
       };
 
-      self.isArchive = function() {
-        var fileName = self.selectedFile().name;
+      self.isArchive = function(fileName) {
         return fileName.endsWith('.zip') || fileName.endsWith('.tar.gz') || fileName.endsWith('.tgz') || fileName.endsWith('.bz2') || fileName.endsWith('.bzip2');
       };
 
@@ -1659,7 +1636,7 @@ from filebrowser.conf import ENABLE_EXTRACT_UPLOADED_ARCHIVE
         if (fileNames.indexOf('.') !== -1) {
           return false;
         }
-        return !self.isS3() && (self.selectedFiles().length > 1 || !(self.selectedFiles().length === 1 && self.isArchive()));
+        return !self.isS3() && (self.selectedFiles().length > 1 || !(self.selectedFiles().length === 1 && self.isArchive(self.selectedFile().name)));
       });
 
       self.setCompressArchiveDefault = function() {
@@ -1921,76 +1898,6 @@ from filebrowser.conf import ENABLE_EXTRACT_UPLOADED_ARCHIVE
         };
       })();
 
-      self.uploadArchive = (function () {
-        self.pendingUploads(0);
-        var uploader = new qq.FileUploader({
-          element: document.getElementById("archiveUploader"),
-          action: "/filebrowser/upload/archive",
-          template: '<div class="qq-uploader" style="margin-left: 10px">' +
-          '<div class="qq-upload-drop-area"><span>${_('Drop the archives here to upload and extract them')}</span></div>' +
-          '<div class="qq-upload-button">${_('Select ZIP, TGZ or BZ2 files')}</div> &nbsp; <span class="muted">or drag and drop them here</span>' +
-          '<ul class="qq-upload-list qq-upload-archives unstyled" style="margin-right: 0;"></ul>' +
-          '</div>',
-          fileTemplate: '<li><span class="qq-upload-file-extended" style="display:none"></span><span class="qq-upload-spinner hide" style="display:none"></span>' +
-          '<div class="progress-row dz-processing">' +
-          '<span class="break-word qq-upload-file"></span>' +
-          '<div class="pull-right">' +
-          '<span class="muted qq-upload-size"></span>&nbsp;&nbsp;' +
-          '<a href="#" title="${_('Cancel')}" class="complex-layout"><i class="fa fa-fw fa-times qq-upload-cancel"></i></a>' +
-          '<span class="qq-upload-done" style="display:none"><i class="fa fa-fw fa-check muted"></i></span>' +
-          '<span class="qq-upload-failed-text">${_('Failed')}</span>' +
-          '</div>' +
-          '<div class="progress-row-bar" style="width: 0%;"></div>' +
-          '</div></li>',
-          params: {
-            dest: self.currentPath(),
-            fileFieldLabel: "archive"
-          },
-          onProgress: function (id, fileName, loaded, total) {
-            $('.qq-upload-archives').find('li').each(function(){
-              var listItem = $(this);
-              if (listItem.find('.qq-upload-file-extended').text() == fileName){
-                listItem.find('.progress-row-bar').css('width', (loaded/total)*100 + '%');
-              }
-            });
-          },
-          onComplete: function (id, fileName, response) {
-            self.pendingUploads(self.pendingUploads() - 1);
-            if (response.status != 0) {
-              $(document).trigger('error', "${ _('Error: ') }" + response.data);
-            }
-            else {
-              $(document).trigger('info', response.path + "${ _(' uploaded successfully.') }");
-              self.filesToHighlight.push(response.path);
-            }
-            if (self.pendingUploads() == 0) {
-              $('#uploadArchiveModal').modal('hide');
-              self.retrieveData(true);
-            }
-          },
-          onSubmit: function (id, fileName, responseJSON) {
-            self.pendingUploads(self.pendingUploads() + 1);
-          },
-          onCancel: function (id, fileName) {
-            self.pendingUploads(self.pendingUploads() - 1);
-          },
-          debug: false
-        });
-
-        $("#archiveUploader").on('fb:updatePath', function (e, options) {
-          uploader.setParams({
-            dest: options.dest,
-            fileFieldLabel: "archive"
-          });
-        });
-
-        return function () {
-          $("#uploadArchiveModal").modal({
-            show: true
-          });
-        };
-      })();
-
       // Place all values into hidden fields under parent element.
       // Looks for managed hidden fields and handles sizing appropriately.
       var hiddenFields = function (parentEl, name, values) {
@@ -2082,7 +1989,7 @@ from filebrowser.conf import ENABLE_EXTRACT_UPLOADED_ARCHIVE
         $('.filebrowser').on('dragenter', function (e) {
           e.preventDefault();
 
-          if (_isExternalFile && !($("#uploadFileModal").is(":visible")) && !($("#uploadArchiveModal").is(":visible")) && (!viewModel.isS3() || (viewModel.isS3() && !viewModel.isS3Root()))) {
+          if (_isExternalFile && !($("#uploadFileModal").is(":visible")) && (!viewModel.isS3() || (viewModel.isS3() && !viewModel.isS3Root()))) {
             showHoverMsg("${_('Drop files here to upload')}");
           }
         });
@@ -2542,18 +2449,6 @@ from filebrowser.conf import ENABLE_EXTRACT_UPLOADED_ARCHIVE
         $(".qq-upload-list").empty();
         $(".qq-upload-drop-area").hide();
       });
-      $("#uploadArchiveModal").on("shown", function () {
-        if (typeof _dropzone != "undefined") {
-          _dropzone.disable();
-        }
-      });
-      $("#uploadArchiveModal").on("hidden", function () {
-        if (typeof _dropzone != "undefined") {
-          _dropzone.enable();
-        }
-        $(".qq-upload-list").empty();
-        $(".qq-upload-drop-area").hide();
-      });
     });
   </script>
 </%def>

+ 0 - 1
apps/filebrowser/src/filebrowser/urls.py

@@ -37,7 +37,6 @@ urlpatterns = patterns('filebrowser.views',
   # POST operations
   url(r'^save$', 'save_file'),
   url(r'^upload/file$', 'upload_file', name='upload_file'),
-  url(r'^upload/archive$', 'upload_archive', name='upload_archive'),
   url(r'^extract_archive', 'extract_archive_using_batch_job', name='extract_archive_using_batch_job'),
   url(r'^compress_files', 'compress_files_using_batch_job', name='compress_files_using_batch_job'),
   url(r'^trash/restore$', 'trash_restore', name='trash_restore'),

+ 0 - 92
apps/filebrowser/src/filebrowser/views.py

@@ -1297,98 +1297,6 @@ def _upload_file(request):
         raise PopupException(_("Error in upload form: %s") % (form.errors,))
 
 
-@require_http_methods(["POST"])
-def upload_archive(request):
-    """
-    A wrapper around the actual upload view function to clean up the temporary file afterwards.
-
-    Returns JSON.
-    e.g. {'status' 0/1, data:'message'...}
-    """
-    response = {'status': -1, 'data': ''}
-
-    try:
-        try:
-            resp = _upload_archive(request)
-            response.update(resp)
-        except Exception, ex:
-            response['data'] = str(ex)
-    finally:
-        hdfs_file = request.FILES.get('hdfs_file')
-        if hdfs_file:
-            hdfs_file.remove()
-
-    return JsonResponse(response)
-
-
-def _upload_archive(request):
-    """
-    Handles archive upload.
-    The uploaded file is stored in memory.
-    We need to extract it and rename it.
-    """
-    form = UploadArchiveForm(request.POST, request.FILES)
-    response = {'status': -1, 'data': ''}
-
-    if form.is_valid():
-        uploaded_file = request.FILES['archive']
-
-        # Always a dir
-        if request.fs.isdir(form.cleaned_data['dest']) and posixpath.sep in uploaded_file.name:
-            raise PopupException(_('No "%(sep)s" allowed in the filename %(name)s.' % {'sep': posixpath.sep, 'name': uploaded_file.name}))
-
-        dest = request.fs.join(form.cleaned_data['dest'], uploaded_file.name)
-        try:
-            # Extract if necessary
-            # Make sure dest path is without the extension
-            if dest.lower().endswith('.zip'):
-                temp_path = archive_factory(uploaded_file, 'zip').extract()
-                if not temp_path:
-                    raise PopupException(_('Could not extract contents of file.'))
-                # Move the file to where it belongs
-                dest = dest[:-4]
-            elif dest.lower().endswith('.tar.gz') or dest.lower().endswith('.tgz'):
-                temp_path = archive_factory(uploaded_file, 'tgz').extract()
-                if not temp_path:
-                    raise PopupException(_('Could not extract contents of file.'))
-                # Move the file to where it belongs
-                dest = dest[:-7] if dest.lower().endswith('.tar.gz') else dest[:-4]
-            elif dest.lower().endswith('.bz2') or dest.lower().endswith('.bzip2'):
-              temp_path = archive_factory(uploaded_file, 'bz2').extract()
-              if not temp_path:
-                  raise PopupException(_('Could not extract contents of file.'))
-                # Move the file to where it belongs
-              dest = dest[:-6] if dest.lower().endswith('.bzip2') else dest[:-4]
-            else:
-                raise PopupException(_('Could not interpret archive type.'))
-
-            request.fs.copyFromLocal(temp_path, dest)
-            shutil.rmtree(temp_path)
-            response['status'] = 0
-
-        except IOError, ex:
-            already_exists = False
-            try:
-                already_exists = request.fs.exists(dest)
-            except Exception:
-              pass
-            if already_exists:
-                msg = _('Destination %(name)s already exists.') % {'name': dest}
-            else:
-                msg = _('Copy to %(name)s failed: %(error)s') % {'name': dest, 'error': ex}
-            raise PopupException(msg)
-
-        response.update({
-          'path': dest,
-          'result': _massage_stats(request, request.fs.stats(dest)),
-          'next': request.GET.get("next")
-        })
-
-        return response
-    else:
-        raise PopupException(_("Error in upload form: %s") % (form.errors,))
-
-
 @require_http_methods(["POST"])
 def extract_archive_using_batch_job(request):