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
Added storage request query abstraction for storages API
Andreas Pfohl5cc45da9a34a
diff --git a/modules/storages/app/models/storages/file_link.rb b/modules/storages/app/models/storages/file_link.rbindex 786295bf86f..918a7944cc0 100644--- a/modules/storages/app/models/storages/file_link.rb+++ b/modules/storages/app/models/storages/file_link.rb@@ -67,7 +67,7 @@ class Storages::FileLink < ApplicationRecord# A standard Rails custom query:# https://www.rubyguides.com/2019/10/scopes-in-ruby-on-rails/# Purpose: limit to FileLink visible by given user.- # Used by: FileLinksAPI#visible_file_links_scope and WorkPackagesFileLinksAPI#visible_file_links_scope+ # Used by: FileLinksAPI#visible_file_links and WorkPackagesFileLinksAPI#visible_file_linksscope :visible, ->(user = User.current) {# join projects through the container, and filter on projects visible from# the userdiff --git a/modules/storages/lib/api/v3/file_links/create_endpoint.rb b/modules/storages/lib/api/v3/file_links/create_endpoint.rbindex 3239dea17e0..11bfe5e24d6 100644--- a/modules/storages/lib/api/v3/file_links/create_endpoint.rb+++ b/modules/storages/lib/api/v3/file_links/create_endpoint.rb@@ -26,59 +26,57 @@# See COPYRIGHT and LICENSE files for more details.#++-module API::V3::FileLinks- # Handles /api/v3/work_packages/:work_package_id/file_links as defined- # in modules/storages/lib/api/v3/file_links/work_packages_file_links_api.rb- #- # Multiple classes are involved during its lifecycle:- # - API::V3::FileLinks::ParseCreateParamsService- # - API::V3::FileLinks::FileLinkCollectionRepresenter- # - Storages::FileLinks::CreateService- #- # These classes are either deduced from the model class, or given as parameter- # on class instantiation.- class CreateEndpoint < API::Utilities::Endpoints::Create- include ::API::V3::Utilities::Endpoints::V3Deductions- include ::API::V3::Utilities::Endpoints::V3PresentSingle-- # As this endpoint receives a list of file links to create, it calls the- # create service multiple times, one time for each file link to create. The- # call is done by calling the `super` method. Results are aggregated in- # global_result using the `add_dependent!` method.- def process(request, params_elements)- global_result = ServiceResult.success+# Handles /api/v3/work_packages/:work_package_id/file_links as defined+# in modules/storages/lib/api/v3/file_links/work_packages_file_links_api.rb+#+# Multiple classes are involved during its lifecycle:+# - API::V3::Utilities::ParseCreateParamsService+# - API::V3::FileLinks::FileLinkCollectionRepresenter+# - Storages::FileLinks::CreateService+#+# These classes are either deduced from the model class, or given as parameter+# on class instantiation.+class API::V3::FileLinks::CreateEndpoint < API::Utilities::Endpoints::Create+ include ::API::V3::Utilities::Endpoints::V3Deductions+ include ::API::V3::Utilities::Endpoints::V3PresentSingle- Storages::FileLink.transaction do- params_elements.each do |params|- # call the default API::Utilities::Endpoints::Create#process- # implementation for each of the params_element array- one_result = super(request, params)- # merge service result in one- global_result.add_dependent!(one_result)- end+ # As this endpoint receives a list of file links to create, it calls the+ # create service multiple times, one time for each file link to create. The+ # call is done by calling the `super` method. Results are aggregated in+ # global_result using the `add_dependent!` method.+ def process(request, params_elements)+ global_result = ServiceResult.success- # rollback records created if an error occurred (validation failed)- raise ActiveRecord::Rollback if global_result.failure?+ Storages::FileLink.transaction do+ params_elements.each do |params|+ # call the default API::Utilities::Endpoints::Create#process+ # implementation for each of the params_element array+ one_result = super(request, params)+ # merge service result in one+ global_result.add_dependent!(one_result)end- global_result- end- def present_success(request, service_call)- render_representer.create(- service_call.all_results,- self_link: request.api_v3_paths.file_links(request.work_package.id),- current_user: request.current_user- )+ # rollback records created if an error occurred (validation failed)+ raise ActiveRecord::Rollback if global_result.failure?end+ global_result+ end++ def present_success(request, service_call)+ render_representer.create(+ service_call.all_results,+ self_link: request.api_v3_paths.file_links(request.work_package.id),+ current_user: request.current_user+ )+ end- private+ private- def params_modifier- ->(params) do- params[:container_id] = work_package.id- params[:container_type] = work_package.class.name- params- end+ def params_modifier+ ->(params) do+ params[:container_id] = work_package.id+ params[:container_type] = work_package.class.name+ paramsendendenddiff --git a/modules/storages/lib/api/v3/file_links/file_link_representer.rb b/modules/storages/lib/api/v3/file_links/file_link_representer.rbindex 7b3787c59c8..e9a8bbfc53b 100644--- a/modules/storages/lib/api/v3/file_links/file_link_representer.rb+++ b/modules/storages/lib/api/v3/file_links/file_link_representer.rb@@ -26,157 +26,153 @@# See COPYRIGHT and LICENSE files for more details.#++-module API- module V3- module FileLinks- URN_PERMISSION_VIEW = "#{::API::V3::URN_PREFIX}file-links:permission:View".freeze- URN_PERMISSION_NOT_ALLOWED = "#{::API::V3::URN_PREFIX}file-links:permission:NotAllowed".freeze- URN_PERMISSION_ERROR = "#{::API::V3::URN_PREFIX}file-links:permission:Error".freeze-- PERMISSION_LINKS = {- view: {- href: URN_PERMISSION_VIEW,- title: 'View'- },- not_allowed: {- href: URN_PERMISSION_NOT_ALLOWED,- title: 'Not allowed'- },- error: {- href: URN_PERMISSION_ERROR,- title: 'Error'- }- }.freeze-- class FileLinkRepresenter < ::API::Decorators::Single- include API::Decorators::LinkedResource- include API::Decorators::DateProperty- include ::API::Caching::CachedRepresenter- include API::V3::FileLinks::StorageUrlHelper-- property :id-- date_time_property :created_at-- date_time_property :updated_at-- property :originData,- exec_context: :decorator,- getter: ->(*) { make_origin_data(represented) },- setter: ->(fragment:, **) do- parse_origin_data(fragment).each do |attribute, value|- represented[attribute] = value- end- end-- self_link-- link :delete, cache_if: -> { user_allowed_to_manage?(represented) } do- {- href: api_v3_paths.file_link(represented.id),- method: :delete- }- end-- link :creator do- {- href: api_v3_paths.user(represented.creator_id),- title: represented.creator.name- }- end-- # Show a permission link only if we have actual permission information for a specific user- link :permission, uncacheable: true do- next if represented.origin_permission.nil?-- PERMISSION_LINKS[represented.origin_permission]- end-- link :originOpen do- {- href: storage_url_open_file(represented)- }- end-- link :staticOriginOpen do- {- href: api_v3_paths.file_link_open(represented.id)- }- end-- link :originOpenLocation do- {- href: storage_url_open_file(represented, open_location: true)- }- end-- link :staticOriginOpenLocation do- {- href: api_v3_paths.file_link_open(represented.id, true)- }- end-- link :staticOriginDownload do- {- href: api_v3_paths.file_link_download(represented.id)- }- end-- associated_resource :storage-- associated_resource :storageUrl,- skip_render: ->(*) { true },- getter: ->(*) {},- setter: ->(fragment:, **) {- break if fragment['href'].blank?-- canonical_url = fragment['href'].gsub(/\/+$/, '')- represented.storage = ::Storages::Storage.find_by(host: canonical_url)- represented.storage ||= ::Storages::Storage::InexistentStorage.new(host: canonical_url)- }-- associated_resource :container,- v3_path: :work_package,- representer: ::API::V3::WorkPackages::WorkPackageRepresenter-- def _type- 'FileLink'- end-- private-- def user_allowed_to_manage?(model)- current_user.allowed_to?(:manage_file_links, model.container.project)- end-- def make_origin_data(model)- {- id: model.origin_id,- name: model.origin_name,- mimeType: model.origin_mime_type,- createdAt: datetime_formatter.format_datetime(model.origin_created_at, allow_nil: true),- lastModifiedAt: datetime_formatter.format_datetime(model.origin_updated_at, allow_nil: true),- createdByName: model.origin_created_by_name,- lastModifiedByName: model.origin_last_modified_by_name- }- end-- def parse_origin_data(origin_data)- {- origin_id: origin_data["id"].to_s,- origin_name: origin_data["name"],- origin_mime_type: origin_data["mimeType"],- origin_created_by_name: origin_data["createdByName"],- origin_last_modified_by_name: origin_data["lastModifiedByName"],- origin_created_at: ::API::V3::Utilities::DateTimeFormatter.parse_datetime(origin_data["createdAt"],- 'originData.createdAt',- allow_nil: true),- origin_updated_at: ::API::V3::Utilities::DateTimeFormatter.parse_datetime(origin_data["lastModifiedAt"],- 'originData.lastModifiedAt',- allow_nil: true)- }- end- end+module API::V3::FileLinks+ URN_PERMISSION_VIEW = "#{::API::V3::URN_PREFIX}file-links:permission:View".freeze+ URN_PERMISSION_NOT_ALLOWED = "#{::API::V3::URN_PREFIX}file-links:permission:NotAllowed".freeze+ URN_PERMISSION_ERROR = "#{::API::V3::URN_PREFIX}file-links:permission:Error".freeze++ PERMISSION_LINKS = {+ view: {+ href: URN_PERMISSION_VIEW,+ title: 'View'+ },+ not_allowed: {+ href: URN_PERMISSION_NOT_ALLOWED,+ title: 'Not allowed'+ },+ error: {+ href: URN_PERMISSION_ERROR,+ title: 'Error'+ }+ }.freeze++ class FileLinkRepresenter < ::API::Decorators::Single+ include API::Decorators::LinkedResource+ include API::Decorators::DateProperty+ include ::API::Caching::CachedRepresenter+ include API::V3::Utilities::StorageUrlHelper++ property :id++ date_time_property :created_at++ date_time_property :updated_at++ property :originData,+ exec_context: :decorator,+ getter: ->(*) { make_origin_data(represented) },+ setter: ->(fragment:, **) do+ parse_origin_data(fragment).each do |attribute, value|+ represented[attribute] = value+ end+ end++ self_link++ link :delete, cache_if: -> { user_allowed_to_manage?(represented) } do+ {+ href: api_v3_paths.file_link(represented.id),+ method: :delete+ }+ end++ link :creator do+ {+ href: api_v3_paths.user(represented.creator_id),+ title: represented.creator.name+ }+ end++ # Show a permission link only if we have actual permission information for a specific user+ link :permission, uncacheable: true do+ next if represented.origin_permission.nil?++ PERMISSION_LINKS[represented.origin_permission]+ end++ link :originOpen do+ {+ href: storage_url_open_file(represented)+ }+ end++ link :staticOriginOpen do+ {+ href: api_v3_paths.file_link_open(represented.id)+ }+ end++ link :originOpenLocation do+ {+ href: storage_url_open_file(represented, open_location: true)+ }+ end++ link :staticOriginOpenLocation do+ {+ href: api_v3_paths.file_link_open(represented.id, true)+ }+ end++ link :staticOriginDownload do+ {+ href: api_v3_paths.file_link_download(represented.id)+ }+ end++ associated_resource :storage++ associated_resource :storageUrl,+ skip_render: ->(*) { true },+ getter: ->(*) {},+ setter: ->(fragment:, **) {+ break if fragment['href'].blank?++ canonical_url = fragment['href'].gsub(/\/+$/, '')+ represented.storage = ::Storages::Storage.find_by(host: canonical_url)+ represented.storage ||= ::Storages::Storage::InexistentStorage.new(host: canonical_url)+ }++ associated_resource :container,+ v3_path: :work_package,+ representer: ::API::V3::WorkPackages::WorkPackageRepresenter++ def _type+ 'FileLink'+ end++ private++ def user_allowed_to_manage?(model)+ current_user.allowed_to?(:manage_file_links, model.container.project)+ end++ def make_origin_data(model)+ {+ id: model.origin_id,+ name: model.origin_name,+ mimeType: model.origin_mime_type,+ createdAt: datetime_formatter.format_datetime(model.origin_created_at, allow_nil: true),+ lastModifiedAt: datetime_formatter.format_datetime(model.origin_updated_at, allow_nil: true),+ createdByName: model.origin_created_by_name,+ lastModifiedByName: model.origin_last_modified_by_name+ }+ end++ def parse_origin_data(origin_data)+ {+ origin_id: origin_data["id"].to_s,+ origin_name: origin_data["name"],+ origin_mime_type: origin_data["mimeType"],+ origin_created_by_name: origin_data["createdByName"],+ origin_last_modified_by_name: origin_data["lastModifiedByName"],+ origin_created_at: ::API::V3::Utilities::DateTimeFormatter.parse_datetime(origin_data["createdAt"],+ 'originData.createdAt',+ allow_nil: true),+ origin_updated_at: ::API::V3::Utilities::DateTimeFormatter.parse_datetime(origin_data["lastModifiedAt"],+ 'originData.lastModifiedAt',+ allow_nil: true)+ }endendenddiff --git a/modules/storages/lib/api/v3/file_links/file_links_api.rb b/modules/storages/lib/api/v3/file_links/file_links_api.rbindex d0a96479ac3..5faa1ba015e 100644--- a/modules/storages/lib/api/v3/file_links/file_links_api.rb+++ b/modules/storages/lib/api/v3/file_links/file_links_api.rb@@ -29,40 +29,34 @@# This class provides definitions for API routes and endpoints for the file_links namespace. It inherits the# functionality from the Grape REST API framework. It is mounted in lib/api/v3/root.rb.# -> /api/v3/file_links/...-module API- module V3- module FileLinks- class FileLinksAPI < ::API::OpenProjectAPI- # helpers is defined by the grape framework. They make methods from the- # module available from within the endpoint context.- helpers API::V3::Utilities::StoragesHelpers+class API::V3::FileLinks::FileLinksAPI < ::API::OpenProjectAPI+ # helpers is defined by the grape framework. They make methods from the+ # module available from within the endpoint context.+ helpers API::V3::Utilities::Scopes- # The `:resources` keyword defines the API namespace -> /api/v3/file_links/...- resources :file_links do- # `route_param` extends the route by a route parameter of the endpoint.- # The input parameter value is parsed into the `:file_link_id` symbol.- route_param :file_link_id, type: Integer, desc: 'File link id' do- # The after validation hook executes after the validation of the request format, but before any execution- # inside the endpoint context. Hence, it is a good place to actually fetch the handled resource.- after_validation do- @file_link = visible_file_links_scope.find(params[:file_link_id])- end+ # The `:resources` keyword defines the API namespace -> /api/v3/file_links/...+ resources :file_links do+ # `route_param` extends the route by a route parameter of the endpoint.+ # The input parameter value is parsed into the `:file_link_id` symbol.+ route_param :file_link_id, type: Integer, desc: 'File link id' do+ # The after validation hook executes after the validation of the request format, but before any execution+ # inside the endpoint context. Hence, it is a good place to actually fetch the handled resource.+ after_validation do+ @file_link = visible_file_links.find(params[:file_link_id])+ end- # A helper is used to define the behaviour at GET /api/v3/file_links/:file_link_id- get &::API::V3::Utilities::Endpoints::Show.new(model: ::Storages::FileLink).mount+ # A helper is used to define the behaviour at GET /api/v3/file_links/:file_link_id+ get &::API::V3::Utilities::Endpoints::Show.new(model: ::Storages::FileLink).mount- # A helper is used to define the behaviour at DELETE /api/v3/file_links/:file_link_id- delete &::API::V3::Utilities::Endpoints::Delete.new(model: ::Storages::FileLink,- process_service: ::Storages::FileLinks::DeleteService)- .mount+ # A helper is used to define the behaviour at DELETE /api/v3/file_links/:file_link_id+ delete &::API::V3::Utilities::Endpoints::Delete.new(model: ::Storages::FileLink,+ process_service: ::Storages::FileLinks::DeleteService)+ .mount- # Additional API definitions are mounted under the current namespace, hence they are- # appended to /api/v3/file_links/:file_link_id/...- mount ::API::V3::FileLinks::FileLinksOpenAPI- mount ::API::V3::FileLinks::FileLinksDownloadAPI- end- end- end+ # Additional API definitions are mounted under the current namespace, hence they are+ # appended to /api/v3/file_links/:file_link_id/...+ mount ::API::V3::FileLinks::FileLinksOpenAPI+ mount ::API::V3::FileLinks::FileLinksDownloadAPIendendenddiff --git a/modules/storages/lib/api/v3/file_links/file_links_download_api.rb b/modules/storages/lib/api/v3/file_links/file_links_download_api.rbindex 6f000e7a96b..68c269794b2 100644--- a/modules/storages/lib/api/v3/file_links/file_links_download_api.rb+++ b/modules/storages/lib/api/v3/file_links/file_links_download_api.rb@@ -26,23 +26,17 @@# See COPYRIGHT and LICENSE files for more details.#++-module API- module V3- module FileLinks- class FileLinksDownloadAPI < ::API::OpenProjectAPI- helpers API::V3::FileLinks::StorageUrlHelper+class API::V3::FileLinks::FileLinksDownloadAPI < ::API::OpenProjectAPI+ helpers API::V3::Utilities::StorageUrlHelper- resources :download do- get do- download_url = make_download_url file_link: @file_link, user: User.current+ resources :download do+ get do+ download_url = make_download_url file_link: @file_link, user: User.current- raise API::Errors::InternalError.new(download_url.result) if download_url.failure?+ raise API::Errors::InternalError.new(download_url.result) if download_url.failure?- redirect download_url.result, body: "The requested resource can be downloaded from #{download_url.result}"- status 303- end- end- end+ redirect download_url.result, body: "The requested resource can be downloaded from #{download_url.result}"+ status 303endendenddiff --git a/modules/storages/lib/api/v3/file_links/file_links_open_api.rb b/modules/storages/lib/api/v3/file_links/file_links_open_api.rbindex a36b3cb05e6..d9490a0ec34 100644--- a/modules/storages/lib/api/v3/file_links/file_links_open_api.rb+++ b/modules/storages/lib/api/v3/file_links/file_links_open_api.rb@@ -26,20 +26,14 @@# See COPYRIGHT and LICENSE files for more details.#++-module API- module V3- module FileLinks- class FileLinksOpenAPI < ::API::OpenProjectAPI- helpers API::V3::FileLinks::StorageUrlHelper+class API::V3::FileLinks::FileLinksOpenAPI < ::API::OpenProjectAPI+ helpers API::V3::Utilities::StorageUrlHelper- resources :open do- get do- url = storage_url_open_file(@file_link, open_location: params[:location])- redirect url, body: "The requested resource can be viewed at #{url}"- status 303 # The follow-up request to the resource must be GET- end- end- end+ resources :open do+ get do+ url = storage_url_open_file(@file_link, open_location: params[:location])+ redirect url, body: "The requested resource can be viewed at #{url}"+ status 303 # The follow-up request to the resource must be GETendendenddiff --git a/modules/storages/lib/api/v3/file_links/parse_create_params_service.rb b/modules/storages/lib/api/v3/file_links/parse_create_params_service.rbdeleted file mode 100644index fe1618ad7fb..00000000000--- a/modules/storages/lib/api/v3/file_links/parse_create_params_service.rb+++ /dev/null@@ -1,76 +0,0 @@-#-- copyright-# OpenProject is an open source project management software.-# Copyright (C) 2012-2022 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 COPYRIGHT and LICENSE files for more details.-#++--module API::V3::FileLinks- class ParseCreateParamsService < ::API::ParseResourceParamsService- MAX_ELEMENTS = 20-- attr_reader :request_body-- private-- def parse_attributes(request_body)- @request_body = request_body- assert_valid_elements-- elements.map do |element|- super(element)- end- end-- def elements- @elements ||= request_body.dig("_embedded", "elements")- end-- def assert_valid_elements- assert_elements_is_present- assert_elements_is_an_array- assert_elements_does_not_exceed_maximum- end-- def assert_elements_is_present- return if elements.present?-- raise API::Errors::PropertyMissingError.new('_embedded/elements')- end-- def assert_elements_is_an_array- return if elements.is_a?(Array)-- raise API::Errors::PropertyFormatError.new('_embedded/elements', 'Array', elements.class.name)- end-- def assert_elements_does_not_exceed_maximum- return if elements.size <= MAX_ELEMENTS-- raise API::Errors::Validation.new('_embedded/elements',- I18n.t('api_v3.errors.too_many_elements_created_at_once',- max: MAX_ELEMENTS, actual: elements.size))- end- end-enddiff --git a/modules/storages/lib/api/v3/file_links/work_packages_file_links_api.rb b/modules/storages/lib/api/v3/file_links/work_packages_file_links_api.rbindex 9102c618cd9..e0fff0daa12 100644--- a/modules/storages/lib/api/v3/file_links/work_packages_file_links_api.rb+++ b/modules/storages/lib/api/v3/file_links/work_packages_file_links_api.rb@@ -30,57 +30,51 @@# functionality from the Grape REST API framework. It is mounted in lib/api/v3/work_packages/work_packages_api.rb,# which puts the file_links namespace behind the provided namespace of the work packages api# -> /api/v3/work_packages/:id/file_links/...-module API- module V3- module FileLinks- class WorkPackagesFileLinksAPI < ::API::OpenProjectAPI- # helpers is defined by the grape framework. They make methods from the- # module available from within the endpoint context.- helpers API::V3::Utilities::StoragesHelpers+class API::V3::FileLinks::WorkPackagesFileLinksAPI < ::API::OpenProjectAPI+ # helpers is defined by the grape framework. They make methods from the+ # module available from within the endpoint context.+ helpers API::V3::Utilities::Scopes- # The `:resources` keyword defines the API namespace -> /api/v3/work_packages/:id/file_links/...- resources :file_links do- # Get the list of FileLinks related to a work package, with updated information from Nextcloud.- get do- # API supports query filters on storages, for example { storage: { operator: '=', values: [storage_id] }- query = ParamsToQueryService- .new(::Storages::Storage,- current_user,- query_class: ::Queries::Storages::FileLinks::FileLinkQuery)- .call(params)+ # The `:resources` keyword defines the API namespace -> /api/v3/work_packages/:id/file_links/...+ resources :file_links do+ # Get the list of FileLinks related to a work package, with updated information from Nextcloud.+ get do+ # API supports query filters on storages, for example { storage: { operator: '=', values: [storage_id] }+ query = ParamsToQueryService+ .new(::Storages::Storage,+ current_user,+ query_class: ::Queries::Storages::FileLinks::FileLinkQuery)+ .call(params)- unless query.valid?- message = I18n.t('api_v3.errors.missing_or_malformed_parameter')- raise ::API::Errors::InvalidQuery.new(message)- end-- # Get a (potentially huge...) list of all FileLinks for the work package.- file_links = query.results- .where(id: visible_file_links_scope- .where(container_id: @work_package.id, container_type: 'WorkPackage'))+ unless query.valid?+ message = I18n.t('api_v3.errors.missing_or_malformed_parameter')+ raise ::API::Errors::InvalidQuery.new(message)+ end- # Synchronize with Nextcloud. StorageAPI has handled OAuth2 for us before.- # We ignore the result, because partial errors (storage network issues) are written to each FileLink- service_result = ::Storages::FileLinkSyncService- .new(user: current_user)- .call(file_links)+ # Get a (potentially huge...) list of all FileLinks for the work package.+ file_links = query.results+ .where(id: visible_file_links+ .where(container_id: @work_package.id, container_type: 'WorkPackage'))- ::API::V3::FileLinks::FileLinkCollectionRepresenter.new(- service_result.result,- self_link: api_v3_paths.file_links(@work_package.id),- current_user:- )- end+ # Synchronize with Nextcloud. StorageAPI has handled OAuth2 for us before.+ # We ignore the result, because partial errors (storage network issues) are written to each FileLink+ service_result = ::Storages::FileLinkSyncService+ .new(user: current_user)+ .call(file_links)- post &CreateEndpoint- .new(- model: ::Storages::FileLink,- parse_service: ParseCreateParamsService,- render_representer: FileLinkCollectionRepresenter- )- .mount- end- end+ ::API::V3::FileLinks::FileLinkCollectionRepresenter.new(+ service_result.result,+ self_link: api_v3_paths.file_links(@work_package.id),+ current_user:+ )end++ post &::API::V3::FileLinks::CreateEndpoint+ .new(+ model: ::Storages::FileLink,+ parse_service: ::API::V3::Utilities::ParseCreateParamsService,+ render_representer: ::API::V3::FileLinks::FileLinkCollectionRepresenter+ )+ .mountendenddiff --git a/modules/storages/lib/api/v3/storage_files/storage_file_collection_representer.rb b/modules/storages/lib/api/v3/storage_files/storage_file_collection_representer.rbindex 96a6b9e77b6..a23d488269b 100644--- a/modules/storages/lib/api/v3/storage_files/storage_file_collection_representer.rb+++ b/modules/storages/lib/api/v3/storage_files/storage_file_collection_representer.rb@@ -26,11 +26,7 @@# See COPYRIGHT and LICENSE files for more details.#++-module API- module V3- module StorageFiles- class StorageFileCollectionRepresenter < ::API::Decorators::UnpaginatedCollection- end- end+module API::V3::StorageFiles+ class StorageFileCollectionRepresenter < ::API::Decorators::UnpaginatedCollectionendenddiff --git a/modules/storages/lib/api/v3/storage_files/storage_file_representer.rb b/modules/storages/lib/api/v3/storage_files/storage_file_representer.rbindex d3a56c39054..37f25322c89 100644--- a/modules/storages/lib/api/v3/storage_files/storage_file_representer.rb+++ b/modules/storages/lib/api/v3/storage_files/storage_file_representer.rb@@ -26,25 +26,21 @@# See COPYRIGHT and LICENSE files for more details.#++-module API- module V3- module StorageFiles- class StorageFileRepresenter < ::API::Decorators::Single- include API::Decorators::DateProperty+module API::V3::StorageFiles+ class StorageFileRepresenter < ::API::Decorators::Single+ include API::Decorators::DateProperty- property :id- property :name- property :mime_type- date_time_property :created_at- date_time_property :last_modified_at- property :created_by_name- property :last_modified_by_name- property :location+ property :id+ property :name+ property :mime_type+ date_time_property :created_at+ date_time_property :last_modified_at+ property :created_by_name+ property :last_modified_by_name+ property :location- def _type- 'StorageFile'- end- end+ def _type+ 'StorageFile'endendenddiff --git a/modules/storages/lib/api/v3/storage_files/storage_files_api.rb b/modules/storages/lib/api/v3/storage_files/storage_files_api.rbindex e775b372a45..e3e3fa2b8e1 100644--- a/modules/storages/lib/api/v3/storage_files/storage_files_api.rb+++ b/modules/storages/lib/api/v3/storage_files/storage_files_api.rb@@ -26,16 +26,16 @@# See COPYRIGHT and LICENSE files for more details.#++-module API- module V3- module StorageFiles- class StorageFilesAPI < ::API::OpenProjectAPI- resources :files do- get do- files = ::Storages::StorageFile.all- StorageFileCollectionRepresenter.new(files, self_link: api_v3_paths.storage_files(@storage.id), current_user:)- end- end+module API::V3::StorageFiles+ class StorageFilesAPI < ::API::OpenProjectAPI+ resources :files do+ get do+ files_query = ::API::V3::Utilities::StorageRequests.new(storage: @storage).files_query++ ::API::V3::StorageFiles::StorageFileCollectionRepresenter.new(+ files_query.call,+ self_link: api_v3_paths.storage_files(@storage.id), current_user:+ )endendenddiff --git a/modules/storages/lib/api/v3/storages/storage_representer.rb b/modules/storages/lib/api/v3/storages/storage_representer.rbindex fb3f2fa8a6f..be7bb30d46d 100644--- a/modules/storages/lib/api/v3/storages/storage_representer.rb+++ b/modules/storages/lib/api/v3/storages/storage_representer.rb@@ -30,76 +30,72 @@# "Representable maps Ruby objects to documents and back"# Reference: Roar is a thin layer on top of Representable https://github.com/trailblazer/roar# Reference: Roar-Rails integration: https://github.com/apotonick/roar-rails-module API- module V3- module Storages- URN_CONNECTION_CONNECTED = "#{::API::V3::URN_PREFIX}storages:authorization:Connected".freeze- URN_CONNECTION_AUTH_FAILED = "#{::API::V3::URN_PREFIX}storages:authorization:FailedAuthorization".freeze- URN_CONNECTION_ERROR = "#{::API::V3::URN_PREFIX}storages:authorization:Error".freeze-- class StorageRepresenter < ::API::Decorators::Single- # LinkedResource module defines helper methods to describe attributes- include API::Decorators::LinkedResource- include API::Decorators::DateProperty- include API::V3::FileLinks::StorageUrlHelper-- def initialize(model, current_user:, embed_links: nil)- @connection_manager =- ::OAuthClients::ConnectionManager.new(user: current_user, oauth_client: model.oauth_client)-- super- end-- property :id-- property :name-- date_time_property :created_at-- date_time_property :updated_at-- self_link-- link :type do- {- href: "#{::API::V3::URN_PREFIX}storages:Nextcloud",- title: 'Nextcloud'- }- end-- link :origin do- { href: represented.host }- end-- link :open do- { href: storage_url_open(represented) }- end-- link :authorizationState do- state = @connection_manager.authorization_state- urn = case state- when :connected- URN_CONNECTION_CONNECTED- when :failed_authorization- URN_CONNECTION_AUTH_FAILED- else- URN_CONNECTION_ERROR- end- title = I18n.t(:"oauth_client.urn_connection_status.#{state}")-- { href: urn, title: }- end-- link :authorize do- next unless @connection_manager.authorization_state == :failed_authorization-- { href: @connection_manager.get_authorization_uri, title: 'Authorize' }- end-- def _type- 'Storage'- end- end+module API::V3::Storages+ URN_CONNECTION_CONNECTED = "#{::API::V3::URN_PREFIX}storages:authorization:Connected".freeze+ URN_CONNECTION_AUTH_FAILED = "#{::API::V3::URN_PREFIX}storages:authorization:FailedAuthorization".freeze+ URN_CONNECTION_ERROR = "#{::API::V3::URN_PREFIX}storages:authorization:Error".freeze++ class StorageRepresenter < ::API::Decorators::Single+ # LinkedResource module defines helper methods to describe attributes+ include API::Decorators::LinkedResource+ include API::Decorators::DateProperty+ include API::V3::Utilities::StorageUrlHelper++ def initialize(model, current_user:, embed_links: nil)+ @connection_manager =+ ::OAuthClients::ConnectionManager.new(user: current_user, oauth_client: model.oauth_client)++ super+ end++ property :id++ property :name++ date_time_property :created_at++ date_time_property :updated_at++ self_link++ link :type do+ {+ href: "#{::API::V3::URN_PREFIX}storages:Nextcloud",+ title: 'Nextcloud'+ }+ end++ link :origin do+ { href: represented.host }+ end++ link :open do+ { href: storage_url_open(represented) }+ end++ link :authorizationState do+ state = @connection_manager.authorization_state+ urn = case state+ when :connected+ URN_CONNECTION_CONNECTED+ when :failed_authorization+ URN_CONNECTION_AUTH_FAILED+ else+ URN_CONNECTION_ERROR+ end+ title = I18n.t(:"oauth_client.urn_connection_status.#{state}")++ { href: urn, title: }+ end++ link :authorize do+ next unless @connection_manager.authorization_state == :failed_authorization++ { href: @connection_manager.get_authorization_uri, title: 'Authorize' }+ end++ def _type+ 'Storage'endendenddiff --git a/modules/storages/lib/api/v3/storages/storages_api.rb b/modules/storages/lib/api/v3/storages/storages_api.rbindex 117a19e1bd2..5979c0605b9 100644--- a/modules/storages/lib/api/v3/storages/storages_api.rb+++ b/modules/storages/lib/api/v3/storages/storages_api.rb@@ -30,40 +30,35 @@# functionality from the Grape REST API framework. It is mounted in lib/api/v3/root.rb.# `modules/storages/lib/` is a defined root directory for grape, providing a root level look up for the namespaces.# Hence, the modules of the class have to be represented in the directory structure.-module API- module V3- module Storages- # OpenProjectAPI is a simple subclass of Grape::API that handles patches.- class StoragesAPI < ::API::OpenProjectAPI- # helpers is defined by the grape framework. They make methods from the- # module available from within the endpoint context.- helpers API::V3::Utilities::StoragesHelpers- # The `:resources` keyword defines the API namespace -> /api/v3/storages/...- resources :storages do- # `route_param` extends the route by a route parameter of the endpoint.- # The input parameter value is parsed into the `:storage_id` symbol.- route_param :storage_id, type: Integer, desc: 'Storage id' do- # Execute the do...end lines after parameter validation but before the actual- # call to the API method.- # Please see: The after_validation call-back in Grape:- # https://github.com/ruby-grape/grape#before-after-and-finally- after_validation do- @storage = visible_storages_scope.find(params[:storage_id])- end+# OpenProjectAPI is a simple subclass of Grape::API that handles patches.+class API::V3::Storages::StoragesAPI < ::API::OpenProjectAPI+ # helpers is defined by the grape framework. They make methods from the+ # module available from within the endpoint context.+ helpers API::V3::Utilities::Scopes- # A helper is used to define the behaviour at GET /api/v3/storages/:storage_id- # The endpoint helper standardizes a lot of the parsing, validation and rendering logic.- # the `mount` method from the endpoint returns a proc. This proc is- # passed as a block to the `get` helper thanks to the `&` operator.- # The block will get called everytime a GET request is sent to this- # route.- get &::API::V3::Utilities::Endpoints::Show.new(model: ::Storages::Storage).mount-- mount API::V3::StorageFiles::StorageFilesAPI- end- end+ # The `:resources` keyword defines the API namespace -> /api/v3/storages/...+ resources :storages do+ # `route_param` extends the route by a route parameter of the endpoint.+ # The input parameter value is parsed into the `:storage_id` symbol.+ route_param :storage_id, type: Integer, desc: 'Storage id' do+ # Execute the do...end lines after parameter validation but before the actual+ # call to the API method.+ # Please see: The after_validation call-back in Grape:+ # https://github.com/ruby-grape/grape#before-after-and-finally+ after_validation do+ @storage = visible_storages.find(params[:storage_id])end++ # A helper is used to define the behaviour at GET /api/v3/storages/:storage_id+ # The endpoint helper standardizes a lot of the parsing, validation and rendering logic.+ # the `mount` method from the endpoint returns a proc. This proc is+ # passed as a block to the `get` helper thanks to the `&` operator.+ # The block will get called everytime a GET request is sent to this+ # route.+ get &::API::V3::Utilities::Endpoints::Show.new(model: ::Storages::Storage).mount++ mount API::V3::StorageFiles::StorageFilesAPIendendenddiff --git a/modules/storages/lib/api/v3/utilities/parse_create_params_service.rb b/modules/storages/lib/api/v3/utilities/parse_create_params_service.rbnew file mode 100644index 00000000000..4a05c3c84c5--- /dev/null+++ b/modules/storages/lib/api/v3/utilities/parse_create_params_service.rb@@ -0,0 +1,74 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2022 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 COPYRIGHT and LICENSE files for more details.+#++++class API::V3::Utilities::ParseCreateParamsService < ::API::ParseResourceParamsService+ MAX_ELEMENTS = 20++ attr_reader :request_body++ private++ def parse_attributes(request_body)+ @request_body = request_body+ assert_valid_elements++ elements.map do |element|+ super(element)+ end+ end++ def elements+ @elements ||= request_body.dig("_embedded", "elements")+ end++ def assert_valid_elements+ assert_elements_is_present+ assert_elements_is_an_array+ assert_elements_does_not_exceed_maximum+ end++ def assert_elements_is_present+ return if elements.present?++ raise API::Errors::PropertyMissingError.new('_embedded/elements')+ end++ def assert_elements_is_an_array+ return if elements.is_a?(Array)++ raise API::Errors::PropertyFormatError.new('_embedded/elements', 'Array', elements.class.name)+ end++ def assert_elements_does_not_exceed_maximum+ return if elements.size <= MAX_ELEMENTS++ raise API::Errors::Validation.new('_embedded/elements',+ I18n.t('api_v3.errors.too_many_elements_created_at_once',+ max: MAX_ELEMENTS, actual: elements.size))+ end+enddiff --git a/modules/storages/lib/api/v3/utilities/storages_helpers.rb b/modules/storages/lib/api/v3/utilities/scopes.rbsimilarity index 84%rename from modules/storages/lib/api/v3/utilities/storages_helpers.rbrename to modules/storages/lib/api/v3/utilities/scopes.rbindex 4e73b5cb332..f3d5f562c57 100644--- a/modules/storages/lib/api/v3/utilities/storages_helpers.rb+++ b/modules/storages/lib/api/v3/utilities/scopes.rb@@ -26,14 +26,12 @@# See COPYRIGHT and LICENSE files for more details.#++-module API::V3::Utilities- module StoragesHelpers- def visible_storages_scope- ::Storages::Storage.visible(current_user)- end+module API::V3::Utilities::Scopes+ def visible_storages+ ::Storages::Storage.visible(current_user)+ end- def visible_file_links_scope- ::Storages::FileLink.visible(current_user)- end+ def visible_file_links+ ::Storages::FileLink.visible(current_user)endenddiff --git a/modules/storages/lib/api/v3/utilities/storage_interaction/abstract_storage_query.rb b/modules/storages/lib/api/v3/utilities/storage_interaction/abstract_storage_query.rbnew file mode 100644index 00000000000..2e943165f42--- /dev/null+++ b/modules/storages/lib/api/v3/utilities/storage_interaction/abstract_storage_query.rb@@ -0,0 +1,7 @@+module API::V3::Utilities::StorageInteraction+ class AbstractStorageQuery+ def files+ raise NotImplementedError+ end+ end+enddiff --git a/modules/storages/lib/api/v3/utilities/storage_interaction/nextcloud_storage_query.rb b/modules/storages/lib/api/v3/utilities/storage_interaction/nextcloud_storage_query.rbnew file mode 100644index 00000000000..893f65f35e1--- /dev/null+++ b/modules/storages/lib/api/v3/utilities/storage_interaction/nextcloud_storage_query.rb@@ -0,0 +1,7 @@+module API::V3::Utilities::StorageInteraction+ class NextcloudStorageQuery < AbstractStorageQuery+ def files+ ::Storages::StorageFile.all+ end+ end+enddiff --git a/modules/storages/lib/api/v3/storages/storage_request_factory.rb b/modules/storages/lib/api/v3/utilities/storage_requests.rbsimilarity index 53%rename from modules/storages/lib/api/v3/storages/storage_request_factory.rbrename to modules/storages/lib/api/v3/utilities/storage_requests.rbindex c89ac883cd5..ef804ab5ba9 100644--- a/modules/storages/lib/api/v3/storages/storage_request_factory.rb+++ b/modules/storages/lib/api/v3/utilities/storage_requests.rb@@ -26,36 +26,42 @@# See COPYRIGHT and LICENSE files for more details.#++-module API- module V3- module Storages- class StorageRequestFactory- def initialize(oauth_client:)- @oauth_client = oauth_client- end+class API::V3::Utilities::StorageRequests+ def initialize(storage:)+ @storage = storage+ @oauth_client = storage.oauth_client+ end++ def download_command+ ->(access_token:, file_id:) do+ request_url = File.join(@oauth_client.integration.host, '/ocs/v2.php/apps/dav/api/v1/direct')+ body = { fileId: file_id }+ header = {+ 'Authorization' => "Bearer #{access_token}",+ 'OCS-APIRequest' => 'true',+ 'Accept' => 'application/json'+ }- def download_command- ->(access_token:, file_id:) do- request_url = File.join(@oauth_client.integration.host, '/ocs/v2.php/apps/dav/api/v1/direct')- body = { fileId: file_id }- header = {- 'Authorization' => "Bearer #{access_token}",- 'OCS-APIRequest' => 'true',- 'Accept' => 'application/json'- }+ begin+ response = RestClient.post request_url, body, header+ rescue RestClient::Unauthorized+ return ServiceResult.failure(result: I18n.t('http.request.failed_authorization'))+ rescue StandardError => e+ return ServiceResult.failure(result: e.message)+ end- begin- response = RestClient.post request_url, body, header- rescue RestClient::Unauthorized- return ServiceResult.failure(result: I18n.t('http.request.failed_authorization'))- rescue StandardError => e- return ServiceResult.failure(result: e.message)- end+ ServiceResult.success(result: response)+ end+ end- ServiceResult.success(result: response)- end- end+ def files_query+ case @storage.provider_type+ when ::Storages::Storage::PROVIDER_TYPE_NEXTCLOUD+ ->() do+ ::API::V3::Utilities::StorageInteraction::NextcloudStorageQuery.new.filesend+ else+ raise ArgumentErrorendendenddiff --git a/modules/storages/lib/api/v3/file_links/storage_url_helper.rb b/modules/storages/lib/api/v3/utilities/storage_url_helper.rbsimilarity index 93%rename from modules/storages/lib/api/v3/file_links/storage_url_helper.rbrename to modules/storages/lib/api/v3/utilities/storage_url_helper.rbindex df2ceeaf8d6..9fa02410211 100644--- a/modules/storages/lib/api/v3/file_links/storage_url_helper.rb+++ b/modules/storages/lib/api/v3/utilities/storage_url_helper.rb@@ -27,7 +27,7 @@#++# Helper for open and download links for a file link object.-module API::V3::FileLinks::StorageUrlHelper+module API::V3::Utilities::StorageUrlHelperdef storage_url_open_file(file_link, open_location: false)location_flag = ActiveModel::Type::Boolean.new.cast(open_location) ? 0 : 1@@ -46,7 +46,7 @@ module API::V3::FileLinks::StorageUrlHelperclient_token = get_oauth_client_token(user:, oauth_client:)return client_token if client_token.failure?- direct_download_response = make_direct_download oauth_client:,+ direct_download_response = make_direct_download storage:,access_token: client_token.result.access_token,file_id: file_link.origin_idreturn direct_download_response if direct_download_response.failure?@@ -70,9 +70,9 @@ module API::V3::FileLinks::StorageUrlHelperclient_token.success? ? client_token : ServiceResult.failure(result: I18n.t('http.request.missing_authorization'))end- def make_direct_download(oauth_client:, access_token:, file_id:)- response = API::V3::Storages::StorageRequestFactory- .new(oauth_client:)+ def make_direct_download(storage:, access_token:, file_id:)+ response = API::V3::Storages::StorageRequests+ .new(storage:).download_command.call(access_token:, file_id:)diff --git a/modules/storages/spec/requests/api/v3/file_links/file_links_spec.rb b/modules/storages/spec/requests/api/v3/file_links/file_links_spec.rbindex bf7c6877b24..cf3eb15b162 100644--- a/modules/storages/spec/requests/api/v3/file_links/file_links_spec.rb+++ b/modules/storages/spec/requests/api/v3/file_links/file_links_spec.rb@@ -359,8 +359,8 @@ describe 'API v3 file links resource', type: :request doactual: 'Integer')end- context "when more than #{API::V3::FileLinks::ParseCreateParamsService::MAX_ELEMENTS} embedded elements" do- let(:max) { API::V3::FileLinks::ParseCreateParamsService::MAX_ELEMENTS }+ context "when more than #{API::V3::Utilities::ParseCreateParamsService::MAX_ELEMENTS} embedded elements" do+ let(:max) { API::V3::Utilities::ParseCreateParamsService::MAX_ELEMENTS }let(:too_many) { max + 1 }let(:embedded_elements) { build_list(:file_link_element, too_many, storage_url: storage_url1) }@@ -473,7 +473,7 @@ describe 'API v3 file links resource', type: :request dodescribe 'GET /api/v3/file_links/:file_link_id/download' dolet(:connection_manager) { instance_double(::OAuthClients::ConnectionManager) }- let(:request_factory) { instance_double(::API::V3::Storages::StorageRequestFactory) }+ let(:request_factory) { instance_double(::API::V3::Storages::StorageRequests) }let(:access_token_result) { ServiceResult.success(result: create(:oauth_client_token)) }let(:path) { api_v3_paths.file_link_download(file_link.id) }let(:download_response) { instance_double(RestClient::Response) }@@ -484,7 +484,7 @@ describe 'API v3 file links resource', type: :request doallow(connection_manager).to receive(:get_access_token).and_return(access_token_result)allow(::OAuthClients::ConnectionManager).to receive(:new).and_return(connection_manager)allow(request_factory).to receive(:download_command).and_return(->(*) { download_command_result })- allow(::API::V3::Storages::StorageRequestFactory).to receive(:new).and_return(request_factory)+ allow(::API::V3::Storages::StorageRequests).to receive(:new).and_return(request_factory)allow(download_response).to receive(:body).and_return(response_body)get path