浏览代码

HUE-9066 [gist] Properly load back the SQL gist

Romain 6 年之前
父节点
当前提交
52d6c5b992

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

@@ -824,26 +824,36 @@ def user_preferences(request, key=None):
 @api_error_handler
 def gist_create(request):
   '''
-  Only supporting Editor currently.
+  Only supporting Editor App currently.
   '''
   response = {'status': 0}
 
-  text = request.POST.get('text', '')
-  gist_type = request.POST.get('type', 'query-hive')
+  statement = request.POST.get('statement', '')
+  gist_type = request.POST.get('doc_type', 'query-hive')
   name = request.POST.get('name', '')
   description = request.POST.get('description', '')
 
+  if not name:
+    name = _('%s Query') % gist_type.rsplit('-')[-1].capitalize()
+  if not statement.strip().startswith('--'):
+    statement = '-- Created by %s\n\n%s' % (request.user.get_full_name() or request.user.username, statement)
+
   gist_doc = Document2.objects.create(
     name=name,
     type='gist',
     owner=request.user,
-    data=json.dumps({'text': text}),
-    extra=gist_type
+    data=json.dumps({'statement': statement}),
+    extra=gist_type,
+    parent_directory=Document2.objects.get_gist_directory(request.user)
   )
 
   response['id'] = gist_doc.id
   response['uuid'] = gist_doc.uuid
-  response['link'] = '/gist?=%s' % gist_doc.uuid
+  response['link'] = '%(scheme)s://%(host)s/hue/gist?uuid=%(uuid)s' % {
+    'scheme': 'https' if request.is_secure() else 'http',
+    'host': request.get_host(),
+    'uuid': gist_doc.uuid,
+  }
 
   return JsonResponse(response)
 
@@ -853,8 +863,7 @@ def gist_get(request):
 
   gist_doc = _get_gist_document(uuid=gist_uuid)
 
-  return redirect('%(host)s/hue/editor?gist=%(uuid)s&type=%s(type)' % {
-    'host': get_host(),
+  return redirect('/hue/editor?gist=%(uuid)s&type=%(type)s' % {
     'uuid': gist_doc.uuid,
     'type': gist_doc.extra.rsplit('-')[-1]
   })

+ 4 - 2
desktop/core/src/desktop/js/api/apiHelper.js

@@ -2948,7 +2948,8 @@ class ApiHelper {
   /**
    *
    * @param {Object} options
-   * @param {string} options.text
+   * @param {string} options.statement
+   * @param {string} options.doc_type
    * @param {string} options.name
    * @param {string} options.description
    * @param {boolean} [options.silenceErrors]
@@ -2960,7 +2961,8 @@ class ApiHelper {
     const request = self.simplePost(
       GIST_API + 'create',
       {
-        text: options.text,
+        statement: options.statement,
+        doc_type: options.doc_type,
         name: options.name,
         description: options.description
       },

+ 2 - 2
desktop/core/src/desktop/js/apps/notebook/editorViewModel.js

@@ -413,14 +413,14 @@ class EditorViewModel {
     self.init = function() {
       if (editor_id) {
         self.openNotebook(editor_id);
+      } else if (window.location.getParameter('gist') !== '') {
+        self.newNotebook(window.location.getParameter('type'));
       } else if (window.location.getParameter('editor') !== '') {
         self.openNotebook(window.location.getParameter('editor'));
       } else if (notebooks.length > 0) {
         self.loadNotebook(notebooks[0]); // Old way of loading json for /browse
       } else if (window.location.getParameter('type') !== '') {
         self.newNotebook(window.location.getParameter('type'));
-      } else if (window.location.getParameter('gist') !== '') {
-        self.newNotebook();
       } else {
         self.newNotebook();
       }

+ 2 - 1
desktop/core/src/desktop/js/apps/notebook/snippet.js

@@ -1915,10 +1915,11 @@ class Snippet {
       if (self.isSqlDialect()) {
         apiHelper
           .createGist({
-            text:
+            statement:
               self.ace().getSelectedText() != ''
                 ? self.ace().getSelectedText()
                 : self.statement_raw(),
+            doc_type: self.type(),
             name: self.name(),
             description: ''
           })

+ 2 - 2
desktop/core/src/desktop/js/apps/notebook2/components/ko.snippetEditorActions.js

@@ -41,9 +41,9 @@ const TEMPLATE = `
       </li>
       <li>
         <a href="javascript:void(0)" data-bind="click: format, css: { 'disabled': !createGistEnabled() }" title="${I18n(
-          'Create a gist link for sharing the selected SQL queries'
+          'Share the query selection via a link'
         )}">
-          <i class="fa fa-wf fa-link"></i> ${I18n('Share')}
+          <i class="fa fa-wf fa-link"></i> ${I18n('Share link')}
         </a>
       </li>
       <li>

+ 16 - 1
desktop/core/src/desktop/models.py

@@ -1020,6 +1020,13 @@ class Document2Manager(models.Manager, Document2QueryMixin):
 
       return parent_home_dir
 
+  def get_gist_directory(self, user):
+    try:
+      home_dir = self.get_home_directory(user)
+      return self.get(owner=user, parent_directory=home_dir, name=Document2.GIST_DIR, type='directory')
+    except Document2.DoesNotExist:
+      return self.create_user_directories(user)
+
   def get_by_path(self, user, path):
     """
     This can be an expensive operation b/c we have to traverse the path tree, so if possible, request a document by UUID
@@ -1060,6 +1067,11 @@ class Document2Manager(models.Manager, Document2QueryMixin):
     if created:
       LOG.info('Successfully created trash directory for user: %s' % user.username)
 
+    gist_dir, created = Directory.objects.get_or_create(name=Document2.GIST_DIR, owner=user, parent_directory=home_dir)
+
+    if created:
+      LOG.info('Successfully created gist directory for user: %s' % user.username)
+
     # For any directories or documents that do not have a parent directory, assign it to home directory
     count = 0
     for doc in Document2.objects.filter(owner=user).filter(parent_directory=None).exclude(id__in=[home_dir.id, trash_dir.id]):
@@ -1074,6 +1086,7 @@ class Document2Manager(models.Manager, Document2QueryMixin):
 class Document2(models.Model):
 
   HOME_DIR = ''
+  GIST_DIR = 'Gist'
   TRASH_DIR = '.Trash'
   EXAMPLES_DIR = 'examples'
 
@@ -1173,6 +1186,8 @@ class Document2(models.Model):
         url = '/editor' + '?editor=' + str(self.id)
       elif self.type == 'directory':
         url = '/home2' + '?uuid=' + self.uuid
+      elif self.type == 'gist':
+        url = '/hue/gist?uuid=' + str(self.uuid)
       elif self.type == 'notebook':
         url = reverse('notebook:notebook') + '?notebook=' + str(self.id)
       elif self.type == 'search-dashboard':
@@ -2060,7 +2075,7 @@ def get_data_link(meta):
 
 
 def _get_gist_document(uuid):
-  return Document2.objects.get(uuid=uuid) # Workaround until there is a share to all permission
+  return Document2.objects.get(uuid=uuid, type='gist') # Workaround until there is a share to all permission
 
 
 def __paginate(page, limit, queryset):

+ 1 - 1
desktop/core/src/desktop/templates/common_header_footer_components.mako

@@ -293,7 +293,7 @@ from metadata.conf import has_optimizer, OPTIMIZER
     <div class="row-fluid">
       <div class="span12">
         <div>
-          <input class="input-xlarge" name="gist-link" type="text" placeholder="${ _('Link') }"/>
+          <input class="input-xxlarge" name="gist-link" type="text" placeholder="${ _('Link') }"/>
         </div>
         <div class="input-prepend">
           <a class="btn" data-dismiss="modal">${_('Copy')}</a>

+ 1 - 1
desktop/core/src/desktop/templates/global_js_constants.mako

@@ -286,7 +286,7 @@
     'Foreign key': '${_('Foreign key')}',
     'Foreign keys': '${_('Foreign keys')}',
     'Format the current SQL query': '${ _('Format the current SQL query') }',
-    'Create a gist link for sharing the selected SQL queries': '${ _('Create a gist link for sharing the selected SQL queries') }',
+    'Share the query selection via a link': '${ _('Share the query selection via a link') }',
     'Format': '${ _('Format') }',
     'France': '${ _('France') }',
     'Functions': '${ _('Functions') }',

+ 7 - 5
desktop/libs/notebook/src/notebook/api.py

@@ -33,7 +33,7 @@ from azure.abfs.__init__ import abfspath
 from desktop.conf import TASK_SERVER
 from desktop.lib.i18n import smart_str
 from desktop.lib.django_util import JsonResponse
-from desktop.models import Document2, Document, __paginate
+from desktop.models import Document2, Document, __paginate, _get_gist_document
 from indexer.file_format import HiveFormat
 from indexer.fields import Field
 
@@ -63,12 +63,14 @@ def create_notebook(request):
   directory_uuid = request.POST.get('directory_uuid')
 
   if gist_id:
-    editor_type = 'impala'
+    gist_doc = _get_gist_document(uuid=gist_id)
+    statement = json.loads(gist_doc.data)['statement']
+
     editor = make_notebook(
-      name='name',
-      description='desc',
+      name='',
+      description='',
       editor_type=editor_type,
-      statement='SELECT ...',
+      statement=statement,
     )
   else:
     editor = Notebook()

+ 2 - 2
desktop/libs/notebook/src/notebook/templates/editor_components.mako

@@ -1794,8 +1794,8 @@ ${ sqlSyntaxDropdown.sqlSyntaxDropdown() }
           </a>
         </li>
         <li>
-          <a href="javascript:void(0)" data-bind="click: createGist, css: {'disabled': ! isReady() }" title="${ _('Create a gist link for sharing the selected SQL queries') }">
-            <i class="fa fa-fw fa-link"></i> ${_('Share')}
+          <a href="javascript:void(0)" data-bind="click: createGist, css: {'disabled': ! isReady() }" title="${ _('Share the query selection via a link') }">
+            <i class="fa fa-fw fa-link"></i> ${_('Share link')}
           </a>
         </li>
         <!-- ko if: formatEnabled -->