Browse Source

Refactoring: Created generic UploadCache class, controller and routes to handle attachment upload.

Thorsten Eckel 6 years ago
parent
commit
c7f8045569

+ 54 - 56
app/assets/javascripts/app/controllers/_ui_element/richtext.coffee

@@ -38,8 +38,7 @@ class App.UiElement.richtext
         # delete attachment from storage
         App.Ajax.request(
           type:        'DELETE'
-          url:         "#{App.Config.get('api_path')}/ticket_attachment_upload"
-          data:        JSON.stringify(id: id),
+          url:         "#{App.Config.get('api_path')}/upload_caches/#{@form_id}/items/#{id}"
           processData: false
         )
 
@@ -57,59 +56,58 @@ class App.UiElement.richtext
       @attachmentsHolder     = item.find('.attachments')
       @cancelContainer       = item.find('.js-cancel')
 
-      u = => html5Upload.initialize(
-        uploadUrl:              App.Config.get('api_path') + '/ticket_attachment_upload'
-        dropContainer:          item.closest('form').get(0)
-        cancelContainer:        @cancelContainer
-        inputField:             item.find('input').get(0)
-        maxSimultaneousUploads: 1,
-        key:                    'File'
-        data:
-          form_id: item.closest('form').find('[name=form_id]').val()
-        onFileAdded: (file) =>
-
-          file.on(
-            onStart: =>
-              @attachmentPlaceholder.addClass('hide')
-              @attachmentUpload.removeClass('hide')
-              @cancelContainer.removeClass('hide')
-              item.find('[contenteditable]').trigger('fileUploadStart')
-              App.Log.debug 'UiElement.richtext', 'upload start'
-
-            onAborted: =>
-              @attachmentPlaceholder.removeClass('hide')
-              @attachmentUpload.addClass('hide')
-              item.find('input').val('')
-              item.find('[contenteditable]').trigger('fileUploadStop', ['aborted'])
-
-            # Called after received response from the server
-            onCompleted: (response) =>
-              response = JSON.parse(response)
-
-              @attachmentPlaceholder.removeClass('hide')
-              @attachmentUpload.addClass('hide')
-
-              # reset progress bar
-              @progressBar.width(parseInt(0) + '%')
-              @progressText.text('')
-
-              renderFile(response.data)
-              item.find('input').val('')
-              item.find('[contenteditable]').trigger('fileUploadStop', ['completed'])
-              App.Log.debug 'UiElement.richtext', 'upload complete', response.data
-
-            # Called during upload progress, first parameter
-            # is decimal value from 0 to 100.
-            onProgress: (progress, fileSize, uploadedBytes) =>
-              @progressBar.width(parseInt(progress) + '%')
-              @progressText.text(parseInt(progress))
-              # hide cancel on 90%
-              if parseInt(progress) >= 90
-                @cancelContainer.addClass('hide')
-              App.Log.debug 'UiElement.richtext', 'uploadProgress ', parseInt(progress)
-
-          )
-      )
-      App.Delay.set(u, 100, undefined, 'form_upload')
+      upload_initialize_callback = =>
+        form_id = item.closest('form').find('[name=form_id]').val()
+        html5Upload.initialize(
+          uploadUrl:              "#{App.Config.get('api_path')}/upload_caches/#{form_id}"
+          dropContainer:          item.closest('form').get(0)
+          cancelContainer:        @cancelContainer
+          inputField:             item.find('input').get(0)
+          maxSimultaneousUploads: 1,
+          key:                    'File'
+          onFileAdded: (file) =>
+
+            file.on(
+              onStart: =>
+                @attachmentPlaceholder.addClass('hide')
+                @attachmentUpload.removeClass('hide')
+                @cancelContainer.removeClass('hide')
+                item.find('[contenteditable]').trigger('fileUploadStart')
+                App.Log.debug 'UiElement.richtext', 'upload start'
+
+              onAborted: =>
+                @attachmentPlaceholder.removeClass('hide')
+                @attachmentUpload.addClass('hide')
+                item.find('input').val('')
+                item.find('[contenteditable]').trigger('fileUploadStop', ['aborted'])
+
+              # Called after received response from the server
+              onCompleted: (response) =>
+                response = JSON.parse(response)
+
+                @attachmentPlaceholder.removeClass('hide')
+                @attachmentUpload.addClass('hide')
+
+                # reset progress bar
+                @progressBar.width(parseInt(0) + '%')
+                @progressText.text('')
+
+                renderFile(response.data)
+                item.find('input').val('')
+                item.find('[contenteditable]').trigger('fileUploadStop', ['completed'])
+                App.Log.debug 'UiElement.richtext', 'upload complete', response.data
+
+              # Called during upload progress, first parameter
+              # is decimal value from 0 to 100.
+              onProgress: (progress, fileSize, uploadedBytes) =>
+                @progressBar.width(parseInt(progress) + '%')
+                @progressText.text(parseInt(progress))
+                # hide cancel on 90%
+                if parseInt(progress) >= 90
+                  @cancelContainer.addClass('hide')
+                App.Log.debug 'UiElement.richtext', 'uploadProgress ', parseInt(progress)
+            )
+        )
+      App.Delay.set(upload_initialize_callback, 100, undefined, 'form_upload')
 
     item

+ 2 - 3
app/assets/javascripts/app/controllers/_ui_element/textarea.coffee

@@ -22,11 +22,10 @@ class App.UiElement.textarea
 
         # only add upload item if html element exists
         if $('#' + fileUploaderId )[0]
+          form_id = item.closest('form').find('[name=form_id]').val()
           $('#' + fileUploaderId ).fineUploader(
             request:
-              endpoint: App.Config.get('api_path') + '/ticket_attachment_upload'
-              params:
-                form_id: item.closest('form').find('[name=form_id]').val()
+              endpoint: "#{App.Config.get('api_path')}/upload_caches/#{form_id}"
             text:
               uploadButton: App.Utils.icon('paperclip')
             template: '<div class="qq-uploader">' +

+ 1 - 2
app/assets/javascripts/app/controllers/ticket_zoom.coffee

@@ -958,8 +958,7 @@ class App.TicketZoom extends App.Controller
     # reset/delete uploaded attachments
     App.Ajax.request(
       type:  'DELETE'
-      url:   App.Config.get('api_path') + '/ticket_attachment_upload'
-      data:  JSON.stringify(form_id: @form_id)
+      url:   "#{App.Config.get('api_path')}/upload_caches/#{@form_id}"
       processData: false
     )
 

+ 3 - 6
app/assets/javascripts/app/controllers/ticket_zoom/article_new.coffee

@@ -172,13 +172,11 @@ class App.TicketZoomArticleNew extends App.Controller
     })
 
     html5Upload.initialize(
-      uploadUrl:       App.Config.get('api_path') + '/ticket_attachment_upload'
+      uploadUrl:       "#{App.Config.get('api_path')}/upload_caches/#{@form_id}"
       dropContainer:   @$('.article-add').get(0)
       cancelContainer: @cancelContainer
       inputField:      @$('.article-attachment input').get(0)
       key:             'File'
-      data:
-        form_id: @form_id
       maxSimultaneousUploads: 1
       onFileAdded:            (file) =>
 
@@ -599,9 +597,8 @@ class App.TicketZoomArticleNew extends App.Controller
 
       # delete attachment from storage
       App.Ajax.request(
-        type:  'DELETE'
-        url:   App.Config.get('api_path') + '/ticket_attachment_upload'
-        data:  JSON.stringify(id: id)
+        type:        'DELETE'
+        url:         "#{App.Config.get('api_path')}/upload_caches/#{@form_id}/items/#{id}"
         processData: false
       )
 

+ 3 - 9
app/controllers/concerns/creates_ticket_articles.rb

@@ -55,10 +55,7 @@ module CreatesTicketArticles
 
     # find attachments in upload cache
     if form_id
-      article.attachments = Store.list(
-        object: 'UploadCache',
-        o_id:   form_id,
-      )
+      article.attachments = UploadCache.new(form_id).attachments
     end
 
     # set subtype of present
@@ -130,11 +127,8 @@ module CreatesTicketArticles
       .first { |taskbar| taskbar.persisted_form_id == form_id }
       &.update!(state: {})
 
-    # remove attachments from upload cache
-    Store.remove(
-      object: 'UploadCache',
-      o_id:   form_id,
-    )
+    # remove temporary attachment cache
+    UploadCache.new(form_id).destroy
 
     article
   end

+ 0 - 60
app/controllers/ticket_articles_controller.rb

@@ -154,66 +154,6 @@ class TicketArticlesController < ApplicationController
     raise Exceptions::NotAuthorized, 'Not authorized (admin permission required)!'
   end
 
-  # DELETE /ticket_attachment_upload
-  def ticket_attachment_upload_delete
-
-    if params[:id].present?
-      Store.remove_item(params[:id])
-      render json: {
-        success: true,
-      }
-      return
-    end
-
-    if params[:form_id].present?
-      Store.remove(
-        object: 'UploadCache',
-        o_id:   params[:form_id],
-      )
-      render json: {
-        success: true,
-      }
-      return
-    end
-
-    render json: { message: 'No such id or form_id!' }, status: :unprocessable_entity
-  end
-
-  # POST /ticket_attachment_upload
-  def ticket_attachment_upload_add
-
-    # store file
-    file = params[:File]
-    content_type = file.content_type
-    if !content_type || content_type == 'application/octet-stream'
-      content_type = if MIME::Types.type_for(file.original_filename).first
-                       MIME::Types.type_for(file.original_filename).first.content_type
-                     else
-                       'application/octet-stream'
-                     end
-    end
-    headers_store = {
-      'Content-Type' => content_type
-    }
-    store = Store.add(
-      object:      'UploadCache',
-      o_id:        params[:form_id],
-      data:        file.read,
-      filename:    file.original_filename,
-      preferences: headers_store
-    )
-
-    # return result
-    render json: {
-      success: true,
-      data:    {
-        id:       store.id,
-        filename: file.original_filename,
-        size:     store.size,
-      }
-    }
-  end
-
   # POST /ticket_attachment_upload_clone_by_article
   def ticket_attachment_upload_clone_by_article
     article = Ticket::Article.find(params[:article_id])

+ 58 - 0
app/controllers/upload_caches_controller.rb

@@ -0,0 +1,58 @@
+# Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
+
+class UploadCachesController < ApplicationController
+  prepend_before_action :authentication_check
+
+  # POST /upload_caches/1
+  def update
+    file = params[:File]
+    content_type = file.content_type
+    if !content_type || content_type == 'application/octet-stream'
+      mime_type    = MIME::Types.type_for(file.original_filename).first
+      content_type = mime_type&.content_type || 'application/octet-stream'
+    end
+    headers_store = {
+      'Content-Type' => content_type
+    }
+
+    store = cache.add(
+      filename:    file.original_filename,
+      data:        file.read,
+      preferences: headers_store
+    )
+
+    # return result
+    render json: {
+      success: true,
+      data:    {
+        id:       store.id, # TODO: rename?
+        filename: file.original_filename,
+        size:     store.size,
+      }
+    }
+  end
+
+  # DELETE /upload_caches/1
+  def destroy
+    cache.destroy
+
+    render json: {
+      success: true,
+    }
+  end
+
+  # DELETE /upload_caches/1/items/1
+  def remove_item
+    cache.remove_item(params[:store_id])
+
+    render json: {
+      success: true,
+    }
+  end
+
+  private
+
+  def cache
+    UploadCache.new(params[:id])
+  end
+end

+ 1 - 1
app/models/taskbar.rb

@@ -54,7 +54,7 @@ class Taskbar < ApplicationModel
   def attachments
     return [] if persisted_form_id.blank?
 
-    Store.list(object: 'UploadCache', o_id: persisted_form_id)
+    UploadCache.new(persisted_form_id).attachments
   end
 
   def add_attachments_to_attributes(attributes)

+ 0 - 2
config/routes/ticket.rb

@@ -42,8 +42,6 @@ Zammad::Application.routes.draw do
   match api_path + '/ticket_articles/:id',                           to: 'ticket_articles#update',          via: :put
   match api_path + '/ticket_articles/:id',                           to: 'ticket_articles#destroy',     via: :delete
   match api_path + '/ticket_attachment/:ticket_id/:article_id/:id',  to: 'ticket_articles#attachment',      via: :get
-  match api_path + '/ticket_attachment_upload',                      to: 'ticket_articles#ticket_attachment_upload_add', via: :post
-  match api_path + '/ticket_attachment_upload',                      to: 'ticket_articles#ticket_attachment_upload_delete', via: :delete
   match api_path + '/ticket_attachment_upload_clone_by_article/:article_id', to: 'ticket_articles#ticket_attachment_upload_clone_by_article', via: :post
   match api_path + '/ticket_article_plain/:id',                      to: 'ticket_articles#article_plain',   via: :get
 

+ 9 - 0
config/routes/upload_cache.rb

@@ -0,0 +1,9 @@
+Zammad::Application.routes.draw do
+  api_path = Rails.configuration.api_path
+
+  # upload cache
+  match api_path + '/upload_caches/:id',                 to: 'upload_caches#update', via: :post
+  match api_path + '/upload_caches/:id',                 to: 'upload_caches#destroy', via: :delete
+  match api_path + '/upload_caches/:id/items/:store_id', to: 'upload_caches#remove_item', via: :delete
+
+end

Some files were not shown because too many files changed in this diff