Browse Source

HUE-3290 [doc2] Improve import JSON document UX

Jenny Kim 9 years ago
parent
commit
38b19d8
2 changed files with 52 additions and 12 deletions
  1. 35 8
      desktop/core/src/desktop/api2.py
  2. 17 4
      desktop/core/src/desktop/models.py

+ 35 - 8
desktop/core/src/desktop/api2.py

@@ -21,6 +21,8 @@ import tempfile
 import StringIO
 import StringIO
 import zipfile
 import zipfile
 
 
+from datetime import datetime
+
 from django.contrib.auth.models import Group, User
 from django.contrib.auth.models import Group, User
 from django.core import management
 from django.core import management
 
 
@@ -33,7 +35,7 @@ from desktop.lib.django_util import JsonResponse
 from desktop.lib.exceptions_renderable import PopupException
 from desktop.lib.exceptions_renderable import PopupException
 from desktop.lib.export_csvxls import make_response
 from desktop.lib.export_csvxls import make_response
 from desktop.lib.i18n import smart_str, force_unicode
 from desktop.lib.i18n import smart_str, force_unicode
-from desktop.models import Document2, Document, Directory, DocumentTag, FilesystemException
+from desktop.models import Document2, Document, Directory, DocumentTag, FilesystemException, uuid_default
 
 
 
 
 LOG = logging.getLogger(__name__)
 LOG = logging.getLogger(__name__)
@@ -346,20 +348,45 @@ def import_documents(request):
   documents = json.loads(documents)
   documents = json.loads(documents)
   docs = []
   docs = []
 
 
+  home_dir = Directory.objects.get_home_directory(request.user)
+
   for doc in documents:
   for doc in documents:
-    if not request.user.is_superuser:
+    # If doc is not owned by current user, make a copy of the document
+    if doc['fields']['owner'][0] != request.user.username:
       doc['fields']['owner'] = [request.user.username]
       doc['fields']['owner'] = [request.user.username]
-    owner = doc['fields']['owner'][0]
-
-    # TODO: Check if this should be replaced by get_by_uuid
-    if Document2.objects.filter(uuid=doc['fields']['uuid'], owner__username=owner).exists():
-      doc['pk'] = Document2.objects.get(uuid=doc['fields']['uuid'], owner__username=owner).pk
-    else:
       doc['pk'] = None
       doc['pk'] = None
+      doc['fields']['version'] = 1
+      doc['fields']['uuid'] = uuid_default()
+      doc['fields']['parent_directory'] = [home_dir.uuid, home_dir.version, home_dir.is_history]
+    else:  # Update existing doc or create new
+      try:
+        existing_doc = Document2.objects.get_by_uuid(doc['fields']['uuid'], owner=request.user)
+        doc['pk'] = existing_doc.pk
+      except FilesystemException, e:
+        LOG.warn('Could not find document with UUID: %s, will create a new document on import.', doc['fields']['uuid'])
+        doc['pk'] = None
+        doc['fields']['version'] = 1
+
+      # Verify that parent exists, log warning and nullify parent if not found
+      if doc['fields']['parent_directory']:
+        uuid, version, is_history = doc['fields']['parent_directory']
+        if not Document2.objects.filter(uuid=uuid, version=version, is_history=is_history).exists():
+          LOG.warn('Could not find parent document with UUID: %s, will set parent to home directory' % uuid)
+          doc['fields']['parent_directory'] = [home_dir.uuid, home_dir.version, home_dir.is_history]
+
+    # Verify that dependencies exist, raise critical error if any dependency not found
+    if doc['fields']['dependencies']:
+      for uuid, version, is_history in doc['fields']['dependencies']:
+        if not Document2.objects.filter(uuid=uuid, version=version, is_history=is_history).exists():
+          raise PopupException(_('Cannot import document, dependency with UUID: %s not found.') % uuid)
+
+    # Set last modified date to now
+    doc['fields']['last_modified'] = datetime.now().replace(microsecond=0).isoformat()
 
 
     docs.append(doc)
     docs.append(doc)
 
 
   f = tempfile.NamedTemporaryFile(mode='w+', suffix='.json')
   f = tempfile.NamedTemporaryFile(mode='w+', suffix='.json')
+
   f.write(json.dumps(docs))
   f.write(json.dumps(docs))
   f.flush()
   f.flush()
 
 

+ 17 - 4
desktop/core/src/desktop/models.py

@@ -806,15 +806,28 @@ class Document2Manager(models.Manager):
   def get_by_natural_key(self, uuid, version, is_history):
   def get_by_natural_key(self, uuid, version, is_history):
     return self.get(uuid=uuid, version=version, is_history=is_history)
     return self.get(uuid=uuid, version=version, is_history=is_history)
 
 
-  def get_by_uuid(self, uuid):
+  def get_by_uuid(self, uuid, owner=None):
     """
     """
     Since UUID is not a unique field, but part of a composite unique key, this returns the latest version by UUID
     Since UUID is not a unique field, but part of a composite unique key, this returns the latest version by UUID
     This should always be used in place of Document2.objects.get(uuid=) when a single document is expected
     This should always be used in place of Document2.objects.get(uuid=) when a single document is expected
-    WARNING: This does not check for read/write pernissions!
+    WARNING: This does not check for read/write permissions!
+
+    :param uuid
+    :param owner: optional filter
     """
     """
-    docs = self.filter(uuid=uuid).order_by('-last_modified')
+    docs = self.filter(uuid=uuid)
+
+    if owner:
+      docs = docs.filter(owner=owner)
+
+    docs = docs.order_by('-last_modified')
+
     if not docs.exists():
     if not docs.exists():
-      raise FilesystemException(_('Document with UUID %s not found.') % uuid)
+      clause = ''
+      if owner:
+        clause = _(' and owner %s ') % owner.username
+      raise FilesystemException(_('Document with UUID %(uuid)s%(clause)s not found.') % {'uuid': uuid, 'clause': clause})
+
     return docs[0]
     return docs[0]
 
 
   def get_history(self, user, doc_type):
   def get_history(self, user, doc_type):