Skip to content

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

Make attachments API BaseServices compatible

Oliver Güntherc59c57ad765a
diff --git a/app/contracts/attachments/create_contract.rb b/app/contracts/attachments/create_contract.rb
new file mode 100644
index 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
+end
diff --git a/app/services/attachments/create_service.rb b/app/services/attachments/create_service.rb
index 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::Create
include 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)
+ super
end
end
- 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)
end
end
end
- 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 message
end
end
diff --git a/app/services/attachments/set_attributes_service.rb b/app/services/attachments/set_attributes_service.rb
new file mode 100644
index 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
+end
diff --git a/lib/api/utilities/endpoints/bodied.rb b/lib/api/utilities/endpoints/bodied.rb
index c5e2ca2697c..39494f0eea6 100644
--- a/lib/api/utilities/endpoints/bodied.rb
+++ b/lib/api/utilities/endpoints/bodied.rb
@@ -46,10 +46,17 @@ module API
end
end
+ 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 API
self.api_name = api_name
self.instance_generator = instance_generator
self.params_modifier = params_modifier
+ self.params_getter = params_getter
self.process_state = process_state
self.parse_representer = parse_representer || deduce_parse_representer
self.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))
.result
end
@@ -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.rb
index d5bc386c05f..67714002f17 100644
--- a/lib/api/utilities/endpoints/create.rb
+++ b/lib/api/utilities/endpoints/create.rb
@@ -29,7 +29,7 @@
module API
module Utilities
module Endpoints
- class Create < Modify
+ class Create < Modify
def default_instance_generator(_model)
->(_params) do
end
diff --git a/lib/api/v3/attachments/attachment_parsing_representer.rb b/lib/api/v3/attachments/attachment_parsing_representer.rb
index 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 API
module V3
module 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
+ end
end
end
end
diff --git a/lib/api/v3/attachments/attachments_api.rb b/lib/api/v3/attachments/attachments_api.rb
index e4cb927667b..f2a1bc8eb8f 100644
--- a/lib/api/v3/attachments/attachments_api.rb
+++ b/lib/api/v3/attachments/attachments_api.rb
@@ -39,25 +39,12 @@ module API
def container
nil
end
-
- def check_attachments_addable
- raise API::Errors::Unauthorized if Redmine::Acts::Attachable.attachables.none?(&:attachments_addable?)
- end
end
- post do
- check_attachments_addable
-
- ::API::V3::Attachments::AttachmentRepresenter.new(parse_and_create, current_user: current_user)
- end
+ post &API::V3::Attachments::AttachmentsByContainerAPI.create
namespace :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.prepare
end
route_param :id, type: Integer, desc: 'Attachment ID' do
diff --git a/lib/api/v3/attachments/attachments_by_container_api.rb b/lib/api/v3/attachments/attachments_by_container_api.rb
index 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 API
request.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 = nil
unless metadata
raise ::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 metadata
end
def 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?
end
def require_direct_uploads
@@ -130,30 +80,10 @@ module API
end
end
- 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)
+ end
end
end
@@ -168,19 +98,33 @@ module API
def 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)
+ .mount
end
end
def self.prepare(permissions = [])
-> do
require_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)
+ .mount
end
end
end