OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Make attachments API BaseServices compatible
Oliver Güntherc59c57ad765a
diff --git a/app/contracts/attachments/create_contract.rb b/app/contracts/attachments/create_contract.rbnew file mode 100644index 00000000000..d8a23e7c227--- /dev/null+++ b/app/contracts/attachments/create_contract.rb@@ -0,0 +1,66 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Attachments+ class CreateContract < ::ModelContract+ attribute :file+ attribute :filename+ attribute :filesize+ attribute :digest+ attribute :description+ attribute :content_type+ attribute :container+ attribute :author++ validate :validate_attachments_addable+ validate :validate_container_addable+ validate :validate_author++ private++ def validate_attachments_addable+ if Redmine::Acts::Attachable.attachables.none?(&:attachments_addable?)+ errors.add(:base, :error_unauthorized)+ end+ end++ def validate_author+ unless model.author == user+ errors.add(:author, :invalid)+ end+ end++ def validate_container_addable+ return unless model.container++ errors.add(:base, :error_unauthorized) unless model.container.attachments_addable?(user)+ end+ end+enddiff --git a/app/services/attachments/create_service.rb b/app/services/attachments/create_service.rbindex 0671dc65a22..772b5ef3f2d 100644--- a/app/services/attachments/create_service.rb+++ b/app/services/attachments/create_service.rb@@ -26,78 +26,63 @@# See docs/COPYRIGHT.rdoc for more details.#++-class Attachments::CreateService+class Attachments::CreateService < ::BaseServices::Createinclude Attachments::TouchContainer- attr_reader :container, :author+ around_call :error_wrapped_call- def initialize(container, author:)- @container = container- @author = author- end-- ##- # Adds and saves the uploaded file as attachment of the given container.- # In case the container supports it, a journal will be written.- #- # An ActiveRecord::RecordInvalid error is raised if any record can't be saved.- def call(uploaded_file:, description:)- create_attachment(uploaded_file, description)- .tap(&method(:created_event))- end-- private-- def create_attachment(uploaded_file, description)- if container.nil?- save_attachment(uploaded_file, description)- elsif container.class.journaled?- create_journalized(uploaded_file, description)+ def persist(call)+ attachment = call.result+ if attachment.container+ in_container_mutex(attachment.container) { super }else- create_unjournalized(uploaded_file, description)+ superendend- def create_journalized(uploaded_file, description)+ def in_container_mutex(container)OpenProject::Mutex.with_advisory_lock_transaction(container) do- save_attachment(uploaded_file, description).tap do+ yield.tap do# Get the latest attachments to ensure having them all for journalization.# We just created an attachment and a different worker might have added attachments# in the meantime, e.g when bulk uploading.container.attachments.reload-- touch(container)endendend- def create_unjournalized(uploaded_file, description)- save_attachment(uploaded_file, description).tap do- touch(container)- end- end-- def save_attachment(uploaded_file, description)- attachment = Attachment.new(file: uploaded_file,- container: container,- description: description,- author: author)-- attachment.save!- attachment- end+ def after_perform(call)+ attachment = call.result+ container = attachment.container- def build_attachment(uploaded_file, description)- container.attachments.build(file: uploaded_file,- description: description,- content_type: uploaded_file.content_type,- author: author)- end+ touch(container) unless container.nil?- def created_event(attachment)OpenProject::Notifications.send(OpenProject::Events::ATTACHMENT_CREATED,attachment: attachment)++ call+ end++ def error_wrapped_call+ yield+ rescue StandardError => e+ binding.pry+ log_attachment_saving_error(e)++ message =+ if e&.class&.to_s == 'Errno::EACCES'+ I18n.t('api_v3.errors.unable_to_create_attachment_permissions')+ else+ I18n.t('api_v3.errors.unable_to_create_attachment')+ end+ raise message+ end++ def log_attachment_saving_error(error)+ message = "Failed to save attachment: #{error&.class} - #{error&.message || 'Unknown error'}"++ OpenProject.logger.error messageendenddiff --git a/app/services/attachments/set_attributes_service.rb b/app/services/attachments/set_attributes_service.rbnew file mode 100644index 00000000000..334ada1fac0--- /dev/null+++ b/app/services/attachments/set_attributes_service.rb@@ -0,0 +1,37 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Attachments+ class SetAttributesService < ::BaseServices::SetAttributes+ def set_default_attributes(params)+ model.author = user if model.author.nil?+ end+ end+enddiff --git a/lib/api/utilities/endpoints/bodied.rb b/lib/api/utilities/endpoints/bodied.rbindex c5e2ca2697c..39494f0eea6 100644--- a/lib/api/utilities/endpoints/bodied.rb+++ b/lib/api/utilities/endpoints/bodied.rb@@ -46,10 +46,17 @@ module APIendend+ def default_params_getter+ ->(request) do+ request.request_body+ end+ end+def initialize(model:,api_name: model.name.demodulize,instance_generator: default_instance_generator(model),params_modifier: default_params_modifier,+ params_getter: default_params_getter,process_state: default_process_state,parse_representer: nil,render_representer: nil,@@ -60,6 +67,7 @@ module APIself.api_name = api_nameself.instance_generator = instance_generatorself.params_modifier = params_modifier+ self.params_getter = params_getterself.process_state = process_stateself.parse_representer = parse_representer || deduce_parse_representerself.render_representer = render_representer || deduce_render_representer@@ -86,7 +94,7 @@ module API.new(request.current_user,model: model,representer: parse_representer)- .call(request.request_body)+ .call(params_getter.call(request)).resultend@@ -121,6 +129,7 @@ module API:instance_generator,:parse_representer,:render_representer,+ :params_getter,:params_modifier,:process_contract,:process_service,diff --git a/lib/api/utilities/endpoints/create.rb b/lib/api/utilities/endpoints/create.rbindex d5bc386c05f..67714002f17 100644--- a/lib/api/utilities/endpoints/create.rb+++ b/lib/api/utilities/endpoints/create.rb@@ -29,7 +29,7 @@module APImodule Utilitiesmodule Endpoints- class Create < Modify+ class Create < Modifydef default_instance_generator(_model)->(_params) doenddiff --git a/lib/api/v3/attachments/attachment_parsing_representer.rb b/lib/api/v3/attachments/attachment_parsing_representer.rbindex 323bf60e69f..34c37354896 100644--- a/lib/api/v3/attachments/attachment_parsing_representer.rb+++ b/lib/api/v3/attachments/attachment_parsing_representer.rb@@ -34,22 +34,35 @@ require 'roar/json/hal'module APImodule V3module Attachments- class AttachmentMetadataRepresenter < ::API::Decorators::Single- def initialize(attachment)- super(attachment, current_user: nil)- end+ class AttachmentParsingRepresenter < ::API::Decorators::Single+ property :file,+ setter: ->(fragment:, **) {+ self.file = OpenProject::Files.build_uploaded_file fragment[:tempfile],+ fragment[:type]+ }++ nested :metadata do+ property :filename,+ as: :fileName++ property :description,+ getter: ->(*) {+ ::API::Decorators::Formattable.new(description, plain: true)+ },+ setter: ->(fragment:, **) { self.description = fragment['raw'] },+ render_nil: true- property :file_name- property :description,- getter: ->(*) {- ::API::Decorators::Formattable.new(description, plain: true)- },- setter: ->(fragment:, **) { self.description = fragment['raw'] },- render_nil: true-- property :content_type, render_nil: false- property :file_size, render_nil: false- property :digest, render_nil: false+ property :content_type,+ as: :contentType,+ render_nil: false++ property :filesize,+ as: :fileSize,+ render_nil: false++ property :digest,+ render_nil: false+ endendendenddiff --git a/lib/api/v3/attachments/attachments_api.rb b/lib/api/v3/attachments/attachments_api.rbindex e4cb927667b..f2a1bc8eb8f 100644--- a/lib/api/v3/attachments/attachments_api.rb+++ b/lib/api/v3/attachments/attachments_api.rb@@ -39,25 +39,12 @@ module APIdef containernilend-- def check_attachments_addable- raise API::Errors::Unauthorized if Redmine::Acts::Attachable.attachables.none?(&:attachments_addable?)- endend- post do- check_attachments_addable-- ::API::V3::Attachments::AttachmentRepresenter.new(parse_and_create, current_user: current_user)- end+ post &API::V3::Attachments::AttachmentsByContainerAPI.createnamespace :prepare do- post do- require_direct_uploads- check_attachments_addable-- ::API::V3::Attachments::AttachmentUploadRepresenter.new(parse_and_prepare, current_user: current_user)- end+ post &API::V3::Attachments::AttachmentsByContainerAPI.prepareendroute_param :id, type: Integer, desc: 'Attachment ID' dodiff --git a/lib/api/v3/attachments/attachments_by_container_api.rb b/lib/api/v3/attachments/attachments_by_container_api.rbindex 745096e05ff..089be45c488 100644--- a/lib/api/v3/attachments/attachments_by_container_api.rb+++ b/lib/api/v3/attachments/attachments_by_container_api.rb@@ -47,39 +47,14 @@ module APIrequest.env['REQUEST_METHOD'] == 'POST'end- def parse_metadata(json)- return nil unless json-- metadata = OpenStruct.new- ::API::V3::Attachments::AttachmentMetadataRepresenter.new(metadata).from_json(json)-- unless metadata.file_name- raise ::API::Errors::Validation.new(- :file_name,- "fileName #{I18n.t('activerecord.errors.messages.blank')}"- )- end-- metadata- end-def parse_and_prepare- metadata = parse_metadata params[:metadata]+ metadata = nilunless metadataraise ::API::Errors::InvalidRequestBody.new(I18n.t('api_v3.errors.multipart_body_error'))end- unless metadata.file_size- raise ::API::Errors::Validation.new(- :file_size,- "fileSize #{I18n.t('activerecord.errors.messages.blank')}"- )- end-- with_handled_create_errors do- create_attachment metadata- end+ create_attachment metadataenddef create_attachment(metadata)@@ -92,36 +67,11 @@ module API)end- def parse_and_create- metadata = parse_metadata params[:metadata]- file = params[:file]-- unless metadata && file- raise ::API::Errors::InvalidRequestBody.new(I18n.t('api_v3.errors.multipart_body_error'))- end-- build_and_attach(metadata, file)- end-- def build_and_attach(metadata, file)- uploaded_file = OpenProject::Files.build_uploaded_file file[:tempfile],- file[:type],- file_name: metadata.file_name.to_s-- service = ::Attachments::CreateService.new(container, author: current_user)-- with_handled_create_errors do- service.call uploaded_file: uploaded_file,- description: metadata.description- end- end-- def check_permissions(permissions)- if permissions.empty?- raise API::Errors::Unauthorized unless container.attachments_addable?(current_user)- else- authorize_any(permissions, projects: container.project)- end+ ##+ # Additionally to what would be checked by the contract,+ # we need to restrict permissions in some use cases of the mounts of this endpoint.+ def restrict_permissions(permissions)+ authorize_any(permissions, projects: container.project) unless permissions.empty?enddef require_direct_uploads@@ -130,30 +80,10 @@ module APIendend- def with_handled_create_errors- yield- rescue ActiveRecord::RecordInvalid => e- raise ::API::Errors::ErrorBase.create_and_merge_errors(e.record.errors)- rescue StandardError => e- log_attachment_saving_error(e)- message =- if e&.class&.to_s == 'Errno::EACCES'- I18n.t('api_v3.errors.unable_to_create_attachment_permissions')- else- I18n.t('api_v3.errors.unable_to_create_attachment')- end- raise ::API::Errors::InternalError.new(message)- end-- def log_attachment_saving_error(error)- container_message = if container- "on #{container.class} with ID #{container.id}"- else- "without container"- end- message = "Failed to save attachment #{container_message}: #{error&.class} - #{error&.message || 'Unknown error'}"-- Rails.logger.error message+ def parse_multipart(request)+ request.params.tap do |params|+ params[:metadata] = JSON.parse(params[:metadata]) if params.key?(:metadata)+ endendend@@ -168,19 +98,33 @@ module APIdef self.create(permissions = [])-> do- check_permissions permissions-- ::API::V3::Attachments::AttachmentRepresenter.new(parse_and_create,- current_user: current_user)+ restrict_permissions permissions++ instance_exec &::API::V3::Utilities::Endpoints::Create+ .new(model: ::Attachment,+ parse_representer: AttachmentParsingRepresenter,+ params_getter: method(:parse_multipart),+ params_modifier: ->(params) do+ params.merge(container: container)+ end)+ .mountendenddef self.prepare(permissions = [])-> dorequire_direct_uploads- check_permissions permissions-- ::API::V3::Attachments::AttachmentUploadRepresenter.new(parse_and_prepare, current_user: current_user)+ restrict_permissions permissions++ instance_exec &::API::V3::Utilities::Endpoints::Create+ .new(model: ::Attachment,+ parse_representer: AttachmentParsingRepresenter,+ process_service: nil, # TODO prepare service+ params_getter: ->(request) { request.params },+ params_modifier: ->(params) do+ params.merge(container: container)+ end)+ .mountendendend