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
[#46331] Project members experience a fully automatically managed project folder
Pavel Balashov5241f811edb7
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/files_query_helpers.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/files_query_helpers.rbdeleted file mode 100644index 596db2caaa4..00000000000--- a/modules/storages/app/common/storages/peripherals/storage_interaction/files_query_helpers.rb+++ /dev/null@@ -1,47 +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 Storages::Peripherals::StorageInteraction- module FilesQueryHelpers- def files_query(storage, user)- Storages::Peripherals::StorageRequests- .new(storage:)- .files_query(user:)- end-- def file_query(storage, user)- Storages::Peripherals::StorageRequests- .new(storage:)- .file_query(user:)- end-- def execute_files_query(data)- ->(query) { query.call(data) }- end- end-enddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/add_user_to_group_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/add_user_to_group_command.rbnew file mode 100644index 00000000000..3618235a868--- /dev/null+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/add_user_to_group_command.rb@@ -0,0 +1,81 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2023 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 Storages::Peripherals::StorageInteraction::Nextcloud+ class AddUserToGroupCommand+ def initialize(storage)+ @uri = URI(storage.host).normalize+ @username = storage.username+ @password = storage.password+ @group = storage.group+ end++ # rubocop:disable Metrics/AbcSize+ def call(user:, group: @group)+ response = Util.http(@uri).post(+ Util.join_uri_path(@uri, 'ocs/v1.php/cloud/users', CGI.escapeURIComponent(user), 'groups'),+ "groupid=#{CGI.escapeURIComponent(group)}",+ Util+ .basic_auth_header(@username, @password)+ .merge(+ 'OCS-APIRequest' => 'true'+ )+ )++ case response+ when Net::HTTPSuccess+ statuscode = Nokogiri::XML(response.body).xpath('/ocs/meta/statuscode').text+ case statuscode+ when "100"+ ServiceResult.success(message: "User has been added successfully")+ when "101"+ ServiceResult.failure(message: "No group specified")+ when "102"+ ServiceResult.failure(message: "Group does not exist")+ when "103"+ ServiceResult.failure(message: "User does not exist")+ when "104"+ ServiceResult.failure(message: "Insufficient privileges")+ when "105"+ ServiceResult.failure(message: "Failed to add user to group")+ end+ when Net::HTTPMethodNotAllowed+ Util.error(:not_allowed)+ when Net::HTTPUnauthorized+ Util.error(:not_authorized)+ when Net::HTTPNotFound+ Util.error(:not_found)+ when Net::HTTPConflict+ Util.error(:conflict)+ else+ Util.error(:error)+ end+ end+ # rubocop:enable Metrics/AbcSize+ end+enddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/create_folder_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/create_folder_command.rbindex 4f41b260e7c..5afbdb70588 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/create_folder_command.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/create_folder_command.rb@@ -27,30 +27,21 @@#++module Storages::Peripherals::StorageInteraction::Nextcloud- class CreateFolderCommand < Storages::Peripherals::StorageInteraction::StorageCommand+ class CreateFolderCommandusing Storages::Peripherals::ServiceResultRefinementsdef initialize(storage)- super()-@uri = URI(storage.host).normalize- @base_path = Util.join_uri_path(@uri.path, "remote.php/dav/files", Util.escape_whitespace(storage.username))- @groupfolder = storage.groupfolder@username = storage.username@password = storage.passwordend# rubocop:disable Metrics/AbcSize- def execute(folder:)- http = Net::HTTP.new(@uri.host, @uri.port)- http.use_ssl = @uri.scheme == 'https'-- response = http.mkcol(- "#{@base_path}/#{@groupfolder}/#{requested_folder(folder)}",+ def call(folder_path:)+ response = Util.http(@uri).mkcol(+ Util.join_uri_path(@uri.path, "remote.php/dav/files", CGI.escapeURIComponent(@username), Util.escape_path(folder_path)),nil,- {- 'Authorization' => "Basic #{Base64::encode64("#{@username}:#{@password}")}"- }+ Util.basic_auth_header(@username, @password))case response@@ -76,12 +67,6 @@ module Storages::Peripherals::StorageInteraction::Nextcloudprivate- def requested_folder(folder)- raise ArgumentError.new("Folder can't be nil or empty string!") if folder.blank?-- Util.escape_whitespace(folder)- end-def error_text_from_response(response)Nokogiri::XML(response.body).xpath("//s:message").textenddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/download_link_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/download_link_query.rbindex c984baf6927..2004a9cde4a 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/download_link_query.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/download_link_query.rb@@ -27,33 +27,21 @@#++module Storages::Peripherals::StorageInteraction::Nextcloud- class DownloadLinkQuery < Storages::Peripherals::StorageInteraction::StorageQuery+ class DownloadLinkQueryusing Storages::Peripherals::ServiceResultRefinements- def initialize(base_uri:, token:, retry_proc:)- super()-- @base_uri = base_uri- @uri = Util.join_uri_path(base_uri, '/ocs/v2.php/apps/dav/api/v1/direct')- @token = token- @retry_proc = retry_proc- end-- def query(file_link)- outbound_response(file_link)- .bind { |response_body| direct_download_token(body: response_body) }- .map { |download_token| download_link(download_token, file_link.origin_name) }+ def initialize(storage)+ @base_uri = URI(storage.host).normalize+ @oauth_client = storage.oauth_clientend- private-# rubocop:disable Metrics/AbcSize- def outbound_response(file_link)- @retry_proc.call(@token) do |token|+ def call(user:, file_link:)+ result = Util.token(user:, oauth_client: @oauth_client) do |token|service_result = beginServiceResult.success(result: RestClient.post(- @uri.to_s,+ Util.join_uri_path(@base_uri, '/ocs/v2.php/apps/dav/api/v1/direct'),{ fileId: file_link.origin_id },{'Authorization' => "Bearer #{token.access_token}",@@ -81,10 +69,16 @@ module Storages::Peripherals::StorageInteraction::Nextcloudendendend++ result+ .bind { |response_body| direct_download_token(body: response_body) }+ .map { |download_token| download_link(download_token, file_link.origin_name) }end# rubocop:enable Metrics/AbcSize+ private+def download_link(token, origin_name)Util.join_uri_path(@base_uri, 'index.php/apps/integration_openproject/direct', token, CGI.escape(origin_name))enddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/file_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/file_query.rbindex 25f4a13efb9..36efa4b8b47 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/file_query.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/file_query.rb@@ -27,55 +27,58 @@#++module Storages::Peripherals::StorageInteraction::Nextcloud- class FileQuery < Storages::Peripherals::StorageInteraction::StorageQuery+ class FileQueryusing Storages::Peripherals::ServiceResultRefinements+ # TODO: check if this path is present on nextcloud instance withou pretty urls enabled+ # check integration_openproject repositoryFILE_INFO_PATH = 'ocs/v1.php/apps/integration_openproject/fileinfo'.freeze- def initialize(base_uri:, token:, retry_proc:)- super()+ def initialize(storage)+ @uri = URI(storage.host).normalize+ @oauth_client = storage.oauth_client+ end- @base_uri = base_uri- @token = token- @retry_proc = retry_proc+ def call(user:, file_id:)+ Util.token(user:, oauth_client: @oauth_client) do |token|+ file_info(file_id, token) >>+ method(:handle_access_control) >>+ method(:storage_file)+ endend- def query(file_id)- file_info(file_id) >>- method(:handle_access_control) >>- method(:storage_file)+ def error(code, log_message = nil, data = nil)+ ServiceResult.failure(errors: Storages::StorageError.new(code:, log_message:, data:))endprivate- def file_info(file_id)- @retry_proc.call(@token) do |token|- service_result = begin- ServiceResult.success(- result: RestClient::Request.execute(- method: :get,- url: Util.join_uri_path(@base_uri, FILE_INFO_PATH, file_id),- headers: {- 'Authorization' => "Bearer #{token.access_token}",- 'Accept' => 'application/json',- 'Content-Type' => 'application/json'- }- )+ def file_info(file_id, token)+ service_result = begin+ ServiceResult.success(+ result: RestClient::Request.execute(+ method: :get,+ url: Util.join_uri_path(@uri, FILE_INFO_PATH, file_id),+ headers: {+ 'Authorization' => "Bearer #{token.access_token}",+ 'Accept' => 'application/json',+ 'Content-Type' => 'application/json'+ })- rescue RestClient::Unauthorized => e- Util.error(:not_authorized, 'Outbound request not authorized!', e.response)- rescue RestClient::NotFound => e- Util.error(:not_found, 'Outbound request destination not found!', e.response)- rescue RestClient::ExceptionWithResponse => e- Util.error(:error, 'Outbound request failed!', e.response)- rescue StandardError- Util.error(:error, 'Outbound request failed!')- end-- # rubocop:disable Style/OpenStructUse- service_result.map { |response| JSON.parse(response.body, object_class: OpenStruct) }- # rubocop:enable Style/OpenStructUse+ )+ rescue RestClient::Unauthorized => e+ error(:not_authorized, 'Outbound request not authorized!', e.response)+ rescue RestClient::NotFound => e+ Util.error(:not_found, 'Outbound request destination not found!', e.response)+ rescue RestClient::ExceptionWithResponse => e+ Util.error(:error, 'Outbound request failed!', e.response)+ rescue StandardError+ Util.error(:error, 'Outbound request failed!')end++ # rubocop:disable Style/OpenStructUse+ service_result.map { |response| JSON.parse(response.body, object_class: OpenStruct) }+ # rubocop:enable Style/OpenStructUseenddef handle_access_control(file_info_response)@@ -101,7 +104,6 @@ module Storages::Peripherals::StorageInteraction::Nextcloudfile_info_data.dav_permissions)ServiceResult.success(result: storage_file)end-# rubocop:enable Metrics/AbcSizedef location(files_path)diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/files_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/files_query.rbindex 5aefb8c1ffd..f42dde51d9b 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/files_query.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/files_query.rb@@ -27,25 +27,19 @@#++module Storages::Peripherals::StorageInteraction::Nextcloud- class FilesQuery < Storages::Peripherals::StorageInteraction::StorageQuery- include API::V3::Utilities::PathHelper-- def initialize(base_uri:, token:, retry_proc:)- super()- @uri = base_uri- @token = token- @retry_proc = retry_proc- @base_path = Util.join_uri_path(@uri.path, "remote.php/dav/files", Util.escape_whitespace(token.origin_user_id))+ class FilesQuery+ def initialize(storage)+ @uri = URI(storage.host).normalize+ @oauth_client = storage.oauth_clientend# rubocop:disable Metrics/AbcSize- def query(folder)- http = Net::HTTP.new(@uri.host, @uri.port)- http.use_ssl = @uri.scheme == 'https'+ def call(user:, folder:)+ result = Util.token(user:, oauth_client: @oauth_client) do |token|+ @base_path = Util.join_uri_path(@uri.path, "remote.php/dav/files", CGI.escapeURIComponent(token.origin_user_id))- result = @retry_proc.call(@token) do |token|- response = http.propfind(- "#{@base_path}#{requested_folder(folder)}",+ response = Util.http(@uri).propfind(+ Util.join_uri_path(@base_path, requested_folder(folder)),requested_properties,{'Depth' => '1',@@ -74,7 +68,7 @@ module Storages::Peripherals::StorageInteraction::Nextclouddef requested_folder(folder)return '' if folder.nil?- Util.escape_whitespace(folder)+ Util.escape_path(folder)end# rubocop:disable Metrics/AbcSizediff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/upload_link_query_helpers.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/group_users_query.rbsimilarity index 51%rename from modules/storages/app/common/storages/peripherals/storage_interaction/upload_link_query_helpers.rbrename to modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/group_users_query.rbindex 439a34b632e..36fdea298cf 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/upload_link_query_helpers.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/group_users_query.rb@@ -1,6 +1,6 @@#-- copyright# OpenProject is an open source project management software.-# Copyright (C) 2012-2022 the OpenProject GmbH+# Copyright (C) 2012-2023 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.@@ -26,30 +26,41 @@# See COPYRIGHT and LICENSE files for more details.#++-module Storages::Peripherals::StorageInteraction- module UploadLinkQueryHelpers+module Storages::Peripherals::StorageInteraction::Nextcloud+ class GroupUsersQueryusing Storages::Peripherals::ServiceResultRefinements- def validate_request_body(body)- case body.transform_keys(&:to_sym)- in { projectId: project_id, fileName: file_name, parent: parent }- authorize(:manage_file_links, context: Project.find(project_id))- ServiceResult.success(result: { fileName: file_name, parent: }.transform_keys(&:to_s))- else- ServiceResult.failure(- errors: Storages::StorageError.new(code: :bad_request, log_message: 'Request body malformed!')- )- end- end-- def upload_link_query(storage, user)- Storages::Peripherals::StorageRequests- .new(storage:)- .upload_link_query(user:)+ def initialize(storage)+ @uri = URI(storage.host).normalize+ @username = storage.username+ @password = storage.password+ @group = storage.groupend- def execute_upload_link_query(request_body)- ->(query) { validate_request_body(request_body) >> query }+ # rubocop:disable Metrics/AbcSize+ def call(group: @group)+ response = Util.http(@uri).get(+ Util.join_uri_path(@uri, "ocs/v1.php/cloud/groups", CGI.escapeURIComponent(group)),+ Util.basic_auth_header(@username, @password).merge('OCS-APIRequest' => 'true')+ )+ case response+ when Net::HTTPSuccess+ group_users = Nokogiri::XML(response.body)+ .xpath('/ocs/data/users/element')+ .map(&:text)+ ServiceResult.success(result: group_users)+ when Net::HTTPMethodNotAllowed+ Util.error(:not_allowed)+ when Net::HTTPUnauthorized+ Util.error(:not_authorized)+ when Net::HTTPNotFound+ Util.error(:not_found)+ when Net::HTTPConflict+ Util.error(:conflict, error_text_from_response(response))+ else+ Util.error(:error)+ endend+ # rubocop:enable Metrics/AbcSizeendenddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/legacy_upload_link_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/legacy_upload_link_query.rbindex ee7444187a2..d41388a26f9 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/legacy_upload_link_query.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/legacy_upload_link_query.rb@@ -27,21 +27,19 @@#++module Storages::Peripherals::StorageInteraction::Nextcloud- class LegacyUploadLinkQuery < Storages::Peripherals::StorageInteraction::StorageQuery- using Storages::Peripherals::ServiceResultRefinements # use '>>' (bind) operator for ServiceResult+ class LegacyUploadLinkQuery+ using Storages::Peripherals::ServiceResultRefinementsURI_BASE_PATH = '/ocs/v2.php/apps/files_sharing/api/v1/shares'.freezeUPLOAD_LINK_BASE = '/public.php/webdav'.freeze- def initialize(base_uri:, token:, retry_proc:)- super()-- @base_uri = base_uri- @token = token- @retry_proc = retry_proc+ def initialize(storage)+ @uri = URI(storage.host).normalize+ @oauth_client = storage.oauth_clientend- def query(data)+ def call(user:, data:)+ @user = uservalidated(data) >>method(:create_file_share) >>method(:apply_drop_permission) >>@@ -90,7 +88,7 @@ module Storages::Peripherals::StorageInteraction::Nextcloudenddef build_upload_link(share)- destination = @base_uri.merge("#{UPLOAD_LINK_BASE}/#{ERB::Util.url_encode(share.file_name)}")+ destination = @uri.merge("#{UPLOAD_LINK_BASE}/#{CGI.escapeURIComponent(share.file_name)}")destination.user = share.tokendestination.password = share.password@@ -98,12 +96,12 @@ module Storages::Peripherals::StorageInteraction::Nextcloudenddef outbound_response(method:, relative_path:, payload:) # rubocop:disable Metrics/AbcSize- @retry_proc.call(@token) do |token|+ response = Util.token(user: @user, oauth_client: @oauth_client) do |token|response = beginServiceResult.success(result: RestClient::Request.execute(method:,- url: @base_uri.merge(relative_path).to_s,+ url: @uri.merge(relative_path).to_s,payload: payload.to_json,headers: {'Authorization' => "Bearer #{token.access_token}",diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/propfind_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/propfind_query.rbnew file mode 100644index 00000000000..5b0da785569--- /dev/null+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/propfind_query.rb@@ -0,0 +1,115 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2023 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 Storages::Peripherals::StorageInteraction::Nextcloud+ class PropfindQuery+ using Storages::Peripherals::ServiceResultRefinements++ def initialize(storage)+ @uri = URI(storage.host).normalize+ @username = storage.username+ @password = storage.password+ @group = storage.group+ end++ # rubocop:disable Metrics/AbcSize+ def call(depth:, path:)+ # possible_depth = %w[0 1 infinity]++ # possible_props = %w[+ # d:getlastmodified+ # d:getetag+ # d:getcontenttype+ # d:resourcetype+ # d:getcontentlength+ # d:permissions+ # d:size+ # oc:id+ # oc:fileid+ # oc:favorite+ # oc:comments-href+ # oc:comments-count+ # oc:comments-unread+ # oc:owner-id+ # oc:owner-display-name+ # oc:share-types+ # oc:checksums+ # oc:size+ # nc:has-preview+ # nc:rich-workspace+ # nc:contained-folder-count+ # nc:contained-file-count+ # nc:acl-list+ # ]++ body = Nokogiri::XML::Builder.new do |xml|+ xml['d'].propfind(+ 'xmlns:d' => 'DAV:',+ 'xmlns:oc' => 'http://owncloud.org/ns',+ 'xmlns:nc' => 'http://nextcloud.org/ns'+ ) do+ xml['d'].prop do+ # xml['nc'].send('acl-list')+ xml['oc'].send('fileid')+ end+ end+ end.to_xml++ response = Util.http(@uri).propfind(+ Util.join_uri_path(@uri, 'remote.php/dav/files', CGI.escapeURIComponent(@username), Util.escape_path(path)),+ body,+ Util.basic_auth_header(@username, @password).merge('Depth' => depth)+ )++ case response+ when Net::HTTPSuccess+ doc = Nokogiri::XML response.body+ result = {}+ doc.xpath('/d:multistatus/d:response').each do |resource_section|+ resource = CGI.unescape(resource_section.xpath("d:href").text.strip).gsub!("/remote.php/dav/files/#{@username}/", "")+ result[resource] = {}+ # In future it could be useful to respond not only with found, but not found props as well+ # resource_section.xpath("d:propstat[d:status[text() = 'HTTP/1.1 404 Not Found']]/d:prop/*")+ resource_section.xpath("d:propstat[d:status[text() = 'HTTP/1.1 200 OK']]/d:prop/*").each do |node|+ result[resource][node.name.to_s] = node.text.strip+ end+ end+ ServiceResult.success(result:)+ when Net::HTTPMethodNotAllowed+ Util.error(:not_allowed)+ when Net::HTTPUnauthorized+ Util.error(:not_authorized)+ when Net::HTTPNotFound+ Util.error(:not_found)+ else+ Util.error(:error)+ end+ end+ # rubocop:enable Metrics/AbcSize+ end+enddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/remove_user_from_group_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/remove_user_from_group_command.rbnew file mode 100644index 00000000000..3d62d12c30f--- /dev/null+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/remove_user_from_group_command.rb@@ -0,0 +1,81 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2023 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 Storages::Peripherals::StorageInteraction::Nextcloud+ class RemoveUserFromGroupCommand+ def initialize(storage)+ @uri = URI(storage.host).normalize+ @username = storage.username+ @password = storage.password+ @group = storage.group+ end++ # rubocop:disable Metrics/AbcSize+ def call(user:, group: @group)+ response = Util.http(@uri).delete(+ Util.join_uri_path(@uri,+ "ocs/v1.php/cloud/users",+ CGI.escapeURIComponent(user),+ "groups?groupid=#{CGI.escapeURIComponent(group)}"),+ Util.basic_auth_header(@username, @password).merge(+ 'OCS-APIRequest' => 'true'+ )+ )++ case response+ when Net::HTTPSuccess+ statuscode = Nokogiri::XML(response.body).xpath('/ocs/meta/statuscode').text+ case statuscode+ when "100"+ ServiceResult.success(message: "User has been removed from group")+ when "101"+ ServiceResult.failure(message: "No group specified")+ when "102"+ ServiceResult.failure(message: "Group does not exist")+ when "103"+ ServiceResult.failure(message: "User does not exist")+ when "104"+ ServiceResult.failure(message: "Insufficient privileges")+ when "105"+ ServiceResult.failure(message: "Failed to remove user from group")+ end+ when Net::HTTPMethodNotAllowed+ Util.error(:not_allowed)+ when Net::HTTPUnauthorized+ Util.error(:not_authorized)+ when Net::HTTPNotFound+ Util.error(:not_found)+ when Net::HTTPConflict+ Util.error(:conflict)+ else+ Util.error(:error)+ end+ end+ # rubocop:enable Metrics/AbcSize+ end+enddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/storage_commands.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/rename_file_command.rbsimilarity index 59%rename from modules/storages/app/common/storages/peripherals/storage_interaction/storage_commands.rbrename to modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/rename_file_command.rbindex c16ff447c35..fa61398218e 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/storage_commands.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/rename_file_command.rb@@ -26,33 +26,34 @@# See COPYRIGHT and LICENSE files for more details.#++-module Storages::Peripherals::StorageInteraction- class StorageCommands- using ::Storages::Peripherals::ServiceResultRefinements+module Storages::Peripherals::StorageInteraction::Nextcloud+ class RenameFileCommand+ using Storages::Peripherals::ServiceResultRefinementsdef initialize(storage)- @storage = storage+ @uri = URI(storage.host).normalize+ @base_path = Util.join_uri_path(@uri.path, "remote.php/dav/files", CGI.escapeURIComponent(storage.username))+ @username = storage.username+ @password = storage.passwordend- def set_permissions_command- case @storage.provider_type- when ::Storages::Storage::PROVIDER_TYPE_NEXTCLOUD- ServiceResult.success(- result: ::Storages::Peripherals::StorageInteraction::Nextcloud::SetPermissionsCommand.new(@storage)+ def call(source:, target:)+ response = Util.http(@uri).move(+ Util.join_uri_path(@base_path, Util.escape_path(source)),+ Util.basic_auth_header(@username, @password).merge(+ 'Destination' => Util.join_uri_path(@base_path, Util.escape_path(target)))- else- raise ArgumentError- end- end+ )- def create_folder_command- case @storage.provider_type- when ::Storages::Storage::PROVIDER_TYPE_NEXTCLOUD- ServiceResult.success(- result: ::Storages::Peripherals::StorageInteraction::Nextcloud::CreateFolderCommand.new(@storage)- )+ case response+ when Net::HTTPSuccess+ ServiceResult.success+ when Net::HTTPNotFound+ Util.error(:not_found)+ when Net::HTTPUnauthorized+ Util.error(:not_authorized)else- raise ArgumentError+ Util.error(:error)endendenddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/set_permissions_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/set_permissions_command.rbindex 055561936c6..6d29fa133ef 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/set_permissions_command.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/set_permissions_command.rb@@ -27,62 +27,23 @@#++module Storages::Peripherals::StorageInteraction::Nextcloud- class SetPermissionsCommand < Storages::Peripherals::StorageInteraction::StorageCommand+ class SetPermissionsCommandusing Storages::Peripherals::ServiceResultRefinements- PERMISSION_MAP = {- read_files: 1,- write_files: 2,- create_files: 4,- delete_files: 8,- share_files: 16- }.freeze-def initialize(storage)- super()-@uri = URI(storage.host).normalize- @base_path = Util.join_uri_path(@uri.path, "remote.php/dav/files", Util.escape_whitespace(storage.username))- @groupfolder = storage.groupfolder- @group = storage.group@username = storage.username@password = storage.passwordend- def execute(folder:, permissions:)- http = Net::HTTP.new(@uri.host, @uri.port)- http.use_ssl = @uri.scheme == 'https'+ # rubocop:disable Metrics/AbcSize+ def call(path:, permissions:)+ raise ArgumentError if path.blank?- response = http.proppatch(- "#{@base_path}/#{@groupfolder}/#{requested_folder(folder)}",- converted_permissions(permissions:),- {- 'Authorization' => "Basic #{Base64::encode64("#{@username}:#{@password}")}"- }- )+ users_permissions = permissions.fetch(:users)+ groups_permissions = permissions.fetch(:groups)- case response- when Net::HTTPSuccess- ServiceResult.success- when Net::HTTPNotFound- Util.error(:not_found)- when Net::HTTPUnauthorized- Util.error(:not_authorized)- else- Util.error(:error)- end- end-- private-- def requested_folder(folder)- raise ArgumentError.new("Folder can't be nil or empty string!") if folder.blank?-- Util.escape_whitespace(folder)- end-- def converted_permissions(permissions:)- Nokogiri::XML::Builder.new do |xml|+ body = Nokogiri::XML::Builder.new do |xml|xml['d'].propertyupdate('xmlns:d' => 'DAV:','xmlns:nc' => 'http://nextcloud.org/ns'@@ -90,53 +51,53 @@ module Storages::Peripherals::StorageInteraction::Nextcloudxml['d'].set doxml['d'].prop doxml['nc'].send('acl-list') do- control_user_permissions(xml)- control_group_permissions(xml)- user_permissions(xml, permissions)+ groups_permissions.each do |group, group_permissions|+ xml['nc'].acl do+ xml['nc'].send('acl-mapping-type', 'group')+ xml['nc'].send('acl-mapping-id', group)+ xml['nc'].send('acl-mask', '31')+ xml['nc'].send('acl-permissions', group_permissions.to_s)+ end+ end+ users_permissions.each do |user, user_permissions|+ xml['nc'].acl do+ xml['nc'].send('acl-mapping-type', 'user')+ xml['nc'].send('acl-mapping-id', user)+ xml['nc'].send('acl-mask', '31')+ xml['nc'].send('acl-permissions', user_permissions.to_s)+ end+ endendendendendend.to_xml- end- def control_user_permissions(xml)- xml['nc'].acl do- xml['nc'].send('acl-mapping-type', 'user')- xml['nc'].send('acl-mapping-id', @username)- xml['nc'].send('acl-mask', '31')- xml['nc'].send('acl-permissions', '31')- end- end-- def control_group_permissions(xml)- xml['nc'].acl do- xml['nc'].send('acl-mapping-type', 'group')- xml['nc'].send('acl-mapping-id', @group)- xml['nc'].send('acl-mask', '31')- xml['nc'].send('acl-permissions', '0')- end- end-- def user_permissions(xml, permissions)- permissions.each do |permission|- username = permission[:origin_user_id]- assignable_permission = nextcloud_permission(permission[:permissions])+ response = Util.http(@uri).proppatch(+ Util.join_uri_path(@uri.path,+ "remote.php/dav/files",+ CGI.escapeURIComponent(@username),+ Util.escape_path(path)),+ body,+ Util.basic_auth_header(@username, @password)+ )- xml['nc'].acl do- xml['nc'].send('acl-mapping-type', 'user')- xml['nc'].send('acl-mapping-id', username)- xml['nc'].send('acl-mask', '31')- xml['nc'].send('acl-permissions', assignable_permission)+ case response+ when Net::HTTPSuccess+ doc = Nokogiri::XML(response.body)+ if doc.xpath("/d:multistatus/d:response/d:propstat[d:status[text() = 'HTTP/1.1 200 OK']]/d:prop/nc:acl-list").present?+ ServiceResult.success+ else+ ServiceResult.failureend+ when Net::HTTPNotFound+ Util.error(:not_found)+ when Net::HTTPUnauthorized+ Util.error(:not_authorized)+ else+ Util.error(:error)endend-- def nextcloud_permission(permission)- permission.reduce(0) do |acc, (k, v)|- acc = acc + PERMISSION_MAP[k] if v- acc- end- end+ # rubocop:enable Metrics/AbcSizeendenddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rbindex 5eea1c7bd73..b7f5369c50a 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rb@@ -27,92 +27,82 @@#++module Storages::Peripherals::StorageInteraction::Nextcloud- class UploadLinkQuery < Storages::Peripherals::StorageInteraction::StorageQuery- using Storages::Peripherals::ServiceResultRefinements # use '>>' (bind) operator for ServiceResult+ class UploadLinkQuery+ using Storages::Peripherals::ServiceResultRefinementsURI_TOKEN_REQUEST = 'index.php/apps/integration_openproject/direct-upload-token'.freezeURI_UPLOAD_BASE_PATH = 'index.php/apps/integration_openproject/direct-upload'.freeze- def initialize(base_uri:, token:, retry_proc:)- super()-- @base_uri = base_uri- @token = token- @retry_proc = retry_proc- end-- def query(data)- validated(data) >>- method(:request_direct_upload_token) >>- method(:build_upload_link)+ def initialize(storage)+ @base_uri = URI(storage.host).normalize+ @oauth_client = storage.oauth_clientend- private-- def validated(data)- if data.nil? || data['parent'].nil?- Util.error(:error, 'Data is invalid', data)- else- ServiceResult.success(- result: Struct.new(:parent).new(data['parent'])- )+ def call(user:, data:)+ Util.token(user:, oauth_client: @oauth_client) do |token|+ if data.nil? || data['parent'].nil?+ error(:error, 'Data is invalid', data)+ else+ r = outbound_response(+ method: :post,+ relative_path: URI_TOKEN_REQUEST,+ payload: { folder_id: data['parent'] },+ token:+ )+ r.success? ? build_upload_link(r.result) : r+ endendend- def request_direct_upload_token(data)- outbound_response(- method: :post,- relative_path: URI_TOKEN_REQUEST,- payload: { folder_id: data.parent }- )+ def error(code, log_message = nil, data = nil)+ ServiceResult.failure(errors: Storages::StorageError.new(code:, log_message:, data:))end+ private+def build_upload_link(response)destination = URI.parse(Util.join_uri_path(@base_uri, URI_UPLOAD_BASE_PATH, response.token))ServiceResult.success(result: Storages::UploadLink.new(destination))end# rubocop:disable Metrics/AbcSize- def outbound_response(method:, relative_path:, payload:)- @retry_proc.call(@token) do |token|- response = begin- ServiceResult.success(- result: RestClient::Request.execute(- method:,- url: Util.join_uri_path(@base_uri, relative_path),- payload: payload.to_json,- headers: {- 'Authorization' => "Bearer #{token.access_token}",- 'Accept' => 'application/json',- 'Content-Type' => 'application/json'- }- )+ def outbound_response(method:, relative_path:, payload:, token:)+ response = begin+ ServiceResult.success(+ result: RestClient::Request.execute(+ method:,+ url: Util.join_uri_path(@base_uri, relative_path),+ payload: payload.to_json,+ headers: {+ 'Authorization' => "Bearer #{token.access_token}",+ 'Accept' => 'application/json',+ 'Content-Type' => 'application/json'+ })- rescue RestClient::Unauthorized => e- Util.error(:not_authorized, 'Outbound request not authorized!', e.response)- rescue RestClient::NotFound => e- Util.error(:not_found, 'Outbound request destination not found!', e.response)- rescue RestClient::ExceptionWithResponse => e- Util.error(:error, 'Outbound request failed!', e.response)- rescue StandardError- Util.error(:error, 'Outbound request failed!')- end+ )+ rescue RestClient::Unauthorized => e+ Util.error(:not_authorized, 'Outbound request not authorized!', e.response)+ rescue RestClient::NotFound => e+ Util.error(:not_found, 'Outbound request destination not found!', e.response)+ rescue RestClient::ExceptionWithResponse => e+ Util.error(:error, 'Outbound request failed!', e.response)+ rescue StandardError+ Util.error(:error, 'Outbound request failed!')+ end- # rubocop:disable Style/OpenStructUse- # rubocop:disable Style/MultilineBlockChain- response- .bind do |r|- # The nextcloud API returns a successful response with empty body if the authorization is missing or expired- if r.body.blank?- Util.error(:not_authorized, 'Outbound request not authorized!')- else- ServiceResult.success(result: r)- end+ # rubocop:disable Style/OpenStructUse+ # rubocop:disable Style/MultilineBlockChain+ response+ .bind do |r|+ # The nextcloud API returns a successful response with empty body if the authorization is missing or expired+ if r.body.blank?+ Util.error(:not_authorized, 'Outbound request not authorized!')+ else+ ServiceResult.success(result: r)end- .map { |r| JSON.parse(r.body, object_class: OpenStruct) }- # rubocop:enable Style/MultilineBlockChain- # rubocop:enable Style/OpenStructUse Style/MultilineBlockChain- end+ end.map { |r| JSON.parse(r.body, object_class: OpenStruct) }+ # rubocop:enable Style/MultilineBlockChain+ # rubocop:enable Style/OpenStructUse Style/MultilineBlockChainend# rubocop:enable Metrics/AbcSizeenddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/util.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/util.rbindex dfd3c2a2fe9..e6e24e13d56 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/util.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/util.rb@@ -27,9 +27,17 @@#++module Storages::Peripherals::StorageInteraction::Nextcloud::Util+ using Storages::Peripherals::ServiceResultRefinements+class << self- def escape_whitespace(value)- value.gsub(' ', '%20')+ def escape_path(path)+ path.split('/').map { |i| CGI.escapeURIComponent(i) }.join('/')+ end++ def basic_auth_header(username, password)+ {+ 'Authorization' => "Basic #{Base64::encode64("#{username}:#{password}")}"+ }enddef error(code, log_message = nil, data = nil)@@ -46,5 +54,21 @@ module Storages::Peripherals::StorageInteraction::Nextcloud::Util# URI::join cannot be used, as it behaves very different for the path parts depending on trailing slashes.File.join(uri.to_s, *parts)end++ def token(user:, oauth_client:, &block)+ connection_manager = ::OAuthClients::ConnectionManager.new(user:, oauth_client:)+ connection_manager.get_access_token.match(+ on_success: ->(token) do+ connection_manager.request_with_token_refresh(token) { block.call(token) }+ end,+ on_failure: ->(_) { error(:not_authorized, 'Query could not be created! No access token found!') }+ )+ end++ def http(uri)+ http = Net::HTTP.new(uri.host, uri.port)+ http.use_ssl = uri.scheme == 'https'+ http+ endendenddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/storage_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/storage_command.rbdeleted file mode 100644index 2c47fb7616a..00000000000--- a/modules/storages/app/common/storages/peripherals/storage_interaction/storage_command.rb+++ /dev/null@@ -1,35 +0,0 @@-#-- copyright-# OpenProject is an open source project management software.-# Copyright (C) 2012-2023 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 Storages::Peripherals::StorageInteraction- class StorageCommand- def execute(data)- raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"- end- end-enddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/storage_queries.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/storage_queries.rbdeleted file mode 100644index 7e98d772b93..00000000000--- a/modules/storages/app/common/storages/peripherals/storage_interaction/storage_queries.rb+++ /dev/null@@ -1,124 +0,0 @@-#-- copyright-# OpenProject is an open source project management software.-# Copyright (C) 2012-2023 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 Storages::Peripherals::StorageInteraction- class StorageQueries- using ::Storages::Peripherals::ServiceResultRefinements-- def initialize(uri:, provider_type:, user:, oauth_client:)- @uri = uri- @provider_type = provider_type- @user = user- @oauth_client = oauth_client- end-- def download_link_query- case @provider_type- when ::Storages::Storage::PROVIDER_TYPE_NEXTCLOUD- retry_with_refreshed_token do |token, with_refreshed_token_proc|- ::Storages::Peripherals::StorageInteraction::Nextcloud::DownloadLinkQuery.new(- base_uri: @uri,- token:,- retry_proc: with_refreshed_token_proc- )- end- else- raise ArgumentError- end- end-- def upload_link_query- case @provider_type- when ::Storages::Storage::PROVIDER_TYPE_NEXTCLOUD- retry_with_refreshed_token do |token, with_refreshed_token_proc|- if OpenProject::FeatureDecisions.legacy_upload_preparation_active?- ::Storages::Peripherals::StorageInteraction::Nextcloud::LegacyUploadLinkQuery.new(- base_uri: @uri,- token:,- retry_proc: with_refreshed_token_proc- )- else- ::Storages::Peripherals::StorageInteraction::Nextcloud::UploadLinkQuery.new(- base_uri: @uri,- token:,- retry_proc: with_refreshed_token_proc- )- end- end- else- raise ArgumentError- end- end-- def files_query- case @provider_type- when ::Storages::Storage::PROVIDER_TYPE_NEXTCLOUD- retry_with_refreshed_token do |token, with_refreshed_token_proc|- ::Storages::Peripherals::StorageInteraction::Nextcloud::FilesQuery.new(- base_uri: @uri,- token:,- retry_proc: with_refreshed_token_proc- )- end- else- raise ArgumentError- end- end-- def file_query- case @provider_type- when ::Storages::Storage::PROVIDER_TYPE_NEXTCLOUD- retry_with_refreshed_token do |token, with_refreshed_token_proc|- ::Storages::Peripherals::StorageInteraction::Nextcloud::FileQuery.new(- base_uri: @uri,- token:,- retry_proc: with_refreshed_token_proc- )- end- else- raise ArgumentError- end- end-- private-- def retry_with_refreshed_token- connection_manager = ::OAuthClients::ConnectionManager.new(user: @user, oauth_client: @oauth_client)- connection_manager.get_access_token.match(- on_success: ->(token) do- ServiceResult.success(result: yield(token, connection_manager.method(:request_with_token_refresh).to_proc))- end,- on_failure: ->(_) { error(:not_authorized, 'Query could not be created! No access token found!') }- )- end-- def error(code, log_message = nil, data = nil)- ServiceResult.failure(errors: Storages::StorageError.new(code:, log_message:, data:))- end- end-enddiff --git a/modules/storages/app/common/storages/peripherals/storage_requests.rb b/modules/storages/app/common/storages/peripherals/storage_requests.rbindex 371b4311017..bbc00067b1b 100644--- a/modules/storages/app/common/storages/peripherals/storage_requests.rb+++ b/modules/storages/app/common/storages/peripherals/storage_requests.rb@@ -28,61 +28,50 @@module Storages::Peripheralsclass StorageRequests- def initialize(storage:)- @storage = storage- @oauth_client = storage.oauth_client- end-- def download_link_query(user:)- storage_queries(user)- .download_link_query- .map { |query| query.method(:query).to_proc }- end+ COMMANDS = %i[+ set_permissions_command+ create_folder_command+ add_user_to_group_command+ remove_user_from_group_command+ rename_file_command+ ].freeze- def files_query(user:)- storage_queries(user)- .files_query- .map { |query| query.method(:query).to_proc }- end-- def file_query(user:)- storage_queries(user)- .file_query- .map { |query| query.method(:query).to_proc }- end+ QUERIES = %i[+ download_link_query+ file_query+ files_query+ upload_link_query+ group_users_query+ propfind_query+ ].freeze- def upload_link_query(user:)- storage_queries(user)- .upload_link_query- .map { |query| query.method(:query).to_proc }+ def initialize(storage:)+ @storage = storageend- def set_permissions_command- storage_commands- .set_permissions_command- .map { |command| command.method(:execute).to_proc }+ (COMMANDS + QUERIES - ['upload_link_query']).each do |request|+ define_method(request) do+ result(clazz(@storage, request))+ endend- def create_folder_command- storage_commands- .create_folder_command- .map { |command| command.method(:execute).to_proc }+ def upload_link_query+ query_clazz = if OpenProject::FeatureDecisions.legacy_upload_preparation_active?+ clazz(@storage, 'legacy_upload_link_query')+ else+ clazz(@storage, 'upload_link_query')+ end+ result(query_clazz)endprivate- def storage_queries(user)- ::Storages::Peripherals::StorageInteraction::StorageQueries- .new(- uri: URI(@storage.host).normalize,- provider_type: @storage.provider_type,- user:,- oauth_client: @oauth_client- )+ def result(request_class)+ ServiceResult.success(result: request_class.new(@storage).method(:call).to_proc)end- def storage_commands- ::Storages::Peripherals::StorageInteraction::StorageCommands.new(@storage)+ def clazz(storage, request)+ "::Storages::Peripherals::StorageInteraction::#{storage.short_provider_type.capitalize}::#{request.to_s.classify}".constantizeendendenddiff --git a/modules/storages/app/models/storages/project_storage.rb b/modules/storages/app/models/storages/project_storage.rbindex ed6ece0842e..c896105a049 100644--- a/modules/storages/app/models/storages/project_storage.rb+++ b/modules/storages/app/models/storages/project_storage.rb@@ -45,6 +45,7 @@ class Storages::ProjectStorage < ApplicationRecordenum project_folder_mode: {inactive: 'inactive',- manual: 'manual'+ manual: 'manual',+ managed: 'automatic'}.freeze, _prefix: 'project_folder'enddiff --git a/modules/storages/app/models/storages/storage.rb b/modules/storages/app/models/storages/storage.rbindex 89196ef8e92..07191f810b5 100644--- a/modules/storages/app/models/storages/storage.rb+++ b/modules/storages/app/models/storages/storage.rb@@ -85,7 +85,8 @@ class Storages::Storage < ApplicationRecordin provider_name:provider_name.downcaseelse- raise "Unknown provider_type! Given: #{provider_type}. " \+ raise ArgumentError,+ "Unknown provider_type! Given: #{provider_type}. " \"Expected the following signature: Storages::{Name of the provider}Storage"endenddiff --git a/modules/storages/app/workers/manage_nextcloud_integration_job.rb b/modules/storages/app/workers/manage_nextcloud_integration_job.rbnew file mode 100644index 00000000000..41fc88114ac--- /dev/null+++ b/modules/storages/app/workers/manage_nextcloud_integration_job.rb@@ -0,0 +1,180 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2023 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 ManageNextcloudIntegrationJob < Cron::CronJob+ using ::Storages::Peripherals::ServiceResultRefinements++ PERMISSION_MAP = {+ read_files: 1,+ write_files: 2,+ create_files: 4,+ delete_files: 8,+ share_files: 16+ }.freeze++ queue_with_priority :low++ self.cron_expression = '*/5 * * * *'++ def perform+ Storages::NextcloudStorage.where("provider_fields->>'has_managed_project_folders' = 'true'").each do |storage|+ username = storage.username+ password = storage.password+ group = storage.group+ groupfolder = storage.groupfolder+ nextcloud_usernames_used_in_openprojects = Set.new+ project_folder_ids_used_in_openproject = Set.new++ requests = Storages::Peripherals::StorageRequests.new(storage:)++ group_users = requests.group_users_query.result.call(group:).match(+ on_success: ->(r) { r },+ on_failure: ->(r) { raise "group_users_query failed: #{r}, group: #{group}" }+ )+ requests.set_permissions_command.result.call(+ path: groupfolder,+ permissions: {+ users: { "#{username}": 31 },+ groups: { "#{group}": 1 }+ }+ ).match(+ on_success: ->(_) {},+ on_failure: ->(r) { raise "set_permissions_command failed: #{r}, path: #{path}, permissions: #{permissions}" }+ )++ folders_props = requests+ .propfind_query+ .result+ .call(depth: '1', path: groupfolder)+ .match(+ on_success: ->(r) { r },+ on_failure: ->(r) { raise "propfind_query failed: #{r}, depth: 1, path: #{groupfolder}" }+ )+ file_ids = folders_props.map { |_path, props| props['fileid'] }++ storage.projects_storages.where(project_folder_mode: 'automatic').each do |project_storage|+ project_folder_id = project_storage.project_folder_id+ project = project_storage.project+ target = "#{groupfolder}/#{project.name.gsub('/', '|')}(#{project.id})/"++ if file_ids.include?(project_folder_id)+ source = folders_props.find { |_k, v| v['fileid'] == project_folder_id }.first+ if source != target+ requests.rename_file_command.result.call(source:, target:).match(+ on_success: ->(r) { r },+ on_failure: ->(r) { raise "rename_file_command failed: #{r}, source: #{source} target: #{target}" }+ )+ end+ else+ requests.create_folder_command.result.call(folder_path: target)+ .match(+ on_success: ->(_) {+ propfind_response2 = requests+ .propfind_query+ .result+ .call(depth: '0', path: target)+ .match(+ on_success: ->(r) { r },+ on_failure: ->(r) { raise "propfind_query failed: #{r}, depth: 0, path: #{target}" }+ )+ project_storage.update(project_folder_id: propfind_response2[target]['fileid'])+ },+ on_failure: ->(r) { raise "create_folder_command failed: #{r}, folder_path: #{target}" }+ )+ end+ project_folder_ids_used_in_openproject << project_storage.project_folder_id+ project = project_storage.project+ project_users = project.users+ oauth_client = OAuthClient.where(integration_id: storage.id,+ integration_type: 'Storages::Storage').first+ tokens = OAuthClientToken.where(oauth_client:, user: project_users)+ permissions = {+ users: { "#{username}": 31 },+ groups: { "#{group}": 0 }+ }++ tokens.each do |token|+ nextcloud_username = token.origin_user_id+ permissions[:users][nextcloud_username.to_sym] = calculate_permissions(user: token.user, project:)++ if group_users.exclude?(nextcloud_username) && nextcloud_usernames_used_in_openprojects.exclude?(nextcloud_username)+ requests.add_user_to_group_command.result.call(user: nextcloud_username).match(+ on_success: ->(_) {},+ on_failure: ->(r) { raise "add_user_to_group_command failed: #{r}, user: #{netcloud_username}" }+ )+ end+ nextcloud_usernames_used_in_openprojects << nextcloud_username+ end++ requests.set_permissions_command.result.call(path: target, permissions:).match(+ on_success: ->(_) {},+ on_failure: ->(r) { raise "set_permissions_command failed: #{r}, path: #{target}, permissions: #{permissions}" }+ )+ end++ (group_users - nextcloud_usernames_used_in_openprojects.to_a).each do |user|+ requests.remove_user_from_group_command.result.call(user:)+ .match(+ on_success: ->(_) {},+ on_failure: ->(r) { raise "remove_user_from_group_command failed: #{r}, user: #{user}" }+ )+ end++ lost_folder_paths = folders_props+ .except("#{groupfolder}/")+ .each_with_object([]) do |(path, attrs), array|+ array.push(path) if project_folder_ids_used_in_openproject.exclude?(attrs['fileid'])+ end+ lost_folder_paths.each do |path|+ requests.set_permissions_command.result.call(+ path:,+ permissions: {+ users: { "#{username}": 31 },+ groups: { "#{group}": 0 }+ }+ ).match(+ on_success: ->(_) {},+ on_failure: ->(r) { raise "set_permissions_command failed: #{r}, path: #{path}, permissions: #{permissions}" }+ )+ end+ end+ end++ def calculate_permissions(user:, project:)+ {+ read_files: user.allowed_to?(:read_files, project),+ write_files: user.allowed_to?(:write_files, project),+ create_files: user.allowed_to?(:create_files, project),+ share_files: user.allowed_to?(:share_files, project),+ delete_files: user.allowed_to?(:delete_files, project)+ }.reduce(0) do |acc, (k, v)|+ acc = acc + PERMISSION_MAP[k] if v+ acc+ end+ end+enddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/storage_query.rb b/modules/storages/db/migrate/20230517075214_add_automatic_to_project_folder_modes.rbsimilarity index 85%rename from modules/storages/app/common/storages/peripherals/storage_interaction/storage_query.rbrename to modules/storages/db/migrate/20230517075214_add_automatic_to_project_folder_modes.rbindex 6e5a51b18c0..34f7eb2efcc 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/storage_query.rb+++ b/modules/storages/db/migrate/20230517075214_add_automatic_to_project_folder_modes.rb@@ -1,4 +1,3 @@-#-- copyright# OpenProject is an open source project management software.# Copyright (C) 2012-2023 the OpenProject GmbH#@@ -26,10 +25,12 @@# See COPYRIGHT and LICENSE files for more details.#++-module Storages::Peripherals::StorageInteraction- class StorageQuery- def query(data)- raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"- end+class AddAutomaticToProjectFolderModes < ActiveRecord::Migration[7.0]+ disable_ddl_transaction!++ def up+ execute <<-SQL.squish+ ALTER TYPE project_folder_modes ADD VALUE 'automatic';+ SQLendenddiff --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 7e729852b5b..bbef2561d1c 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@@ -34,11 +34,11 @@ class API::V3::FileLinks::FileLinksDownloadAPI < API::OpenProjectAPIget doStorages::Peripherals::StorageRequests.new(storage: @file_link.storage)- .download_link_query(user: User.current)+ .download_link_query.match(on_success: ->(download_link_query) {download_link_query- .call(@file_link)+ .call(user: User.current, file_link: @file_link).match(on_success: ->(url) doredirect(url, body: "The requested resource can be downloaded from #{url}")diff --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 58908ed40c9..85bd9eaacd2 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@@ -30,12 +30,13 @@ module API::V3::StorageFilesclass StorageFilesAPI < ::API::OpenProjectAPIusing Storages::Peripherals::ServiceResultRefinementshelpers Storages::Peripherals::StorageErrorHelper- helpers Storages::Peripherals::StorageInteraction::UploadLinkQueryHelpers- helpers Storages::Peripherals::StorageInteraction::FilesQueryHelpersresources :files doget do- (files_query(@storage, current_user) >> execute_files_query(params[:parent]))+ (Storages::Peripherals::StorageRequests.new(storage: @storage).files_query >> ->(query) {+ query.call(user: current_user,+ folder: params[:parent])+ }).match(on_success: ->(files) { API::V3::StorageFiles::StorageFilesRepresenter.new(files, @storage, current_user:) },on_failure: ->(error) { raise_error(error) }@@ -44,7 +45,10 @@ module API::V3::StorageFilesroute_param :file_id, type: String, desc: 'Storage file id' doget do- (file_query(@storage, current_user) >> execute_files_query(params[:file_id]))+ (Storages::Peripherals::StorageRequests.new(storage: @storage).file_query >> ->(query) {+ query.call(user: current_user,+ file_id: params[:file_id])+ }).match(on_success: ->(storage_file) {API::V3::StorageFiles::StorageFileRepresenter.new(storage_file, @storage, current_user:)@@ -55,11 +59,26 @@ module API::V3::StorageFilesendpost :prepare_upload do- (upload_link_query(@storage, current_user) >> execute_upload_link_query(request_body))- .match(- on_success: ->(link) { API::V3::StorageFiles::StorageUploadLinkRepresenter.new(link, current_user:) },- on_failure: ->(error) { raise_error(error) }- )+ validate = ->(_body) do+ case request_body.transform_keys(&:to_sym)+ in { projectId: project_id, fileName: file_name, parent: parent }+ authorize(:manage_file_links, context: Project.find(project_id))+ ServiceResult.success(result: { fileName: file_name, parent: }.transform_keys(&:to_s))+ else+ ServiceResult.failure(errors: Storages::StorageError.new(code: :bad_request, log_message: 'Request body malformed!'))+ end+ end++ validate.call(request_body) >> ->(data) do+ (Storages::Peripherals::StorageRequests.new(storage: @storage).upload_link_query >> ->(query) {+ query.call(user: current_user,+ data:)+ })+ .match(+ on_success: ->(link) { API::V3::StorageFiles::StorageUploadLinkRepresenter.new(link, current_user:) },+ on_failure: ->(error) { raise_error(error) }+ )+ endendendenddiff --git a/modules/storages/lib/open_project/storages/engine.rb b/modules/storages/lib/open_project/storages/engine.rbindex 43dec67fa59..2c3196baa65 100644--- a/modules/storages/lib/open_project/storages/engine.rb+++ b/modules/storages/lib/open_project/storages/engine.rb@@ -71,7 +71,9 @@ module OpenProject::Storages{ 'storages/admin/projects_storages': %i[index new edit update create destroy set_permissions] },dependencies: %i[]- if OpenProject::FeatureDecisions.managed_project_folders_active?+ # explicit check for test env is needed, because `with_flag: { managed_project_folders: true }` set for a test case+ # handled later and at this moment feature is disabled.+ if OpenProject::FeatureDecisions.managed_project_folders_active? || Rails.env.test?permission :read_files,{},dependencies: %i[]@@ -225,6 +227,11 @@ module OpenProject::Storagesmount ::API::V3::FileLinks::WorkPackagesFileLinksAPIend- add_cron_jobs { CleanupUncontaineredFileLinksJob }+ add_cron_jobs do+ [+ CleanupUncontaineredFileLinksJob,+ ManageNextcloudIntegrationJob+ ]+ endendenddiff --git a/modules/storages/spec/common/peripherals/storage_requests_spec.rb b/modules/storages/spec/common/peripherals/storage_requests_spec.rbindex 006ac940af1..72a93d1cc25 100644--- a/modules/storages/spec/common/peripherals/storage_requests_spec.rb+++ b/modules/storages/spec/common/peripherals/storage_requests_spec.rb@@ -29,42 +29,749 @@require 'spec_helper'describe Storages::Peripherals::StorageRequests, webmock: true do- using Storages::Peripherals::ServiceResultRefinements-- let(:user) { build_stubbed(:user) }-+ let(:user) { create(:user) }let(:url) { 'https://example.com' }let(:origin_user_id) { 'admin' }+ let(:storage) { build(:storage, host: url, password: 'OpenProjectSecurePassword') }++ subject { described_class.new(storage:) }++ context 'when requests depend on OAuth token' do+ let(:token) do+ create(:oauth_client_token, origin_user_id:, access_token: 'xyz', oauth_client:, user:)+ end+ let(:oauth_client) { create(:oauth_client, integration: storage) }++ before { token }++ describe '#download_link_query' do+ let(:file_link) do+ Struct.new(:file_link) do+ def origin_id+ 42+ end++ def origin_name+ 'example.md'+ end+ end.new+ end+ let(:download_token) { "8dM3dC9iy1N74F5AJ0ClnjSF4dWTxfymVy1HTXBh8rbZVM81CpcBJaIYZvmR" }+ let(:uri) do+ "#{url}/index.php/apps/integration_openproject/direct/#{download_token}/#{CGI.escape(file_link.origin_name)}"+ end+ let(:json) do+ {+ ocs: {+ meta: {+ status: 'ok',+ statuscode: 200,+ message: 'OK'+ },+ data: {+ url: "https://example.com/remote.php/direct/#{download_token}"+ }+ }+ }.to_json+ end++ before do+ stub_request(:post, "#{url}/ocs/v2.php/apps/dav/api/v1/direct")+ .to_return(status: 200, body: json, headers: {})+ end++ describe 'with Nextcloud storage type selected' do+ it 'must return a download link URL' do+ result = subject+ .download_link_query+ .result+ .call(user:, file_link:)+ expect(result).to be_success+ expect(result.result).to be_eql(uri)+ end++ context 'if Nextcloud is running on a sub path' do+ let(:url) { 'https://example.com/html' }++ it 'must return a download link URL' do+ result = subject+ .download_link_query+ .result+ .call(user:, file_link:)+ expect(result).to be_success+ expect(result.result).to be_eql(uri)+ end+ end+ end++ describe 'with not supported storage type selected' do+ before do+ allow(storage).to receive(:provider_type).and_return('not_supported_storage_type'.freeze)+ end++ it 'must raise ArgumentError' do+ expect { subject.download_link_query }.to raise_error(ArgumentError)+ end+ end++ describe 'with missing OAuth token' do+ before do+ allow_any_instance_of(OAuthClients::ConnectionManager).to receive(:get_access_token).and_return(ServiceResult.failure)+ end++ it 'must return ":not_authorized" ServiceResult' do+ result = subject+ .download_link_query+ .result+ .call(user:, file_link:)+ expect(result).to be_failure+ expect(result.errors.code).to be(:not_authorized)+ end+ end++ describe 'with outbound request returning 200 and an empty body' do+ before do+ stub_request(:post, "#{url}/ocs/v2.php/apps/dav/api/v1/direct").to_return(status: 200, body: '')+ end++ it 'must return :not_authorized ServiceResult' do+ result = subject+ .download_link_query+ .result+ .call(user:, file_link:)+ expect(result).to be_failure+ expect(result.errors.code).to be(:not_authorized)+ end+ end++ shared_examples_for 'outbound is failing' do |code = 500, symbol = :error|+ describe "with outbound request returning #{code}" do+ before do+ stub_request(:post, "#{url}/ocs/v2.php/apps/dav/api/v1/direct").to_return(status: code)+ end++ it "must return :#{symbol} ServiceResult" do+ result = subject+ .download_link_query+ .result+ .call(user:, file_link:)+ expect(result).to be_failure+ expect(result.errors.code).to be(symbol)+ end+ end+ end++ include_examples 'outbound is failing', 404, :not_found+ include_examples 'outbound is failing', 401, :not_authorized+ include_examples 'outbound is failing', 500, :error+ end++ describe '#files_query' do+ let(:parent) { '' }+ let(:root_path) { '' }+ let(:xml) { create(:webdav_data, parent_path: parent, root_path:) }+ let(:url) { "https://example.com#{root_path}" }+ let(:request_url) do+ Storages::Peripherals::StorageInteraction::Nextcloud::Util.join_uri_path(+ url,+ "/remote.php/dav/files/",+ CGI.escapeURIComponent(origin_user_id),+ parent+ )+ end++ context 'when outbound is success' do+ before do+ stub_request(:propfind, request_url).to_return(status: 207, body: xml, headers: {})+ end++ describe 'with Nextcloud storage type selected' do+ it 'returns a list files directories with names and permissions' do+ result = subject+ .files_query+ .result+ .call(folder: nil, user:)+ expect(result).to be_success+ expect(result.result.files.size).to eq(4)+ expect(result.result.ancestors.size).to eq(0)+ expect(result.result.parent).not_to be_nil++ expect(result).to be_success+ expect(result.result.files[0].name).to eq('Folder1')+ expect(result.result.files[0].mime_type).to eq('application/x-op-directory')+ expect(result.result.files[0].id).to eq('11')+ expect(result.result.files[0].permissions).to include(:readable)+ expect(result.result.files[0].permissions).to include(:writeable)++ expect(result.result.files[1].mime_type).to eq('application/x-op-directory')+ expect(result.result.files[1].permissions).to include(:readable)+ expect(result.result.files[1].permissions).not_to include(:writeable)++ expect(result.result.files[2].mime_type).to eq('text/markdown')+ expect(result.result.files[2].name).to eq('README.md')+ expect(result.result.files[2].id).to eq('12')+ expect(result.result.files[2].permissions).to include(:readable)+ expect(result.result.files[2].permissions).to include(:writeable)++ expect(result.result.files[3].mime_type).to eq('application/pdf')+ expect(result.result.files[3].permissions).to include(:readable)+ expect(result.result.files[3].permissions).not_to include(:writeable)+ end++ describe 'with origin user id containing whitespaces' do+ let(:origin_user_id) { 'my user' }+ let(:xml) { create(:webdav_data, origin_user_id:) }++ it do+ result = subject+ .files_query+ .result+ .call(folder: parent, user:)+ expect(result.result.files[0].location).to eq('/Folder1')- let(:storage) do- build(:storage, host: url, password: 'OpenProjectSecurePassword')+ assert_requested(:propfind, request_url)+ end+ end++ describe 'with parent query parameter' do+ let(:parent) { '/Photos/Birds' }++ it do+ result = subject+ .files_query+ .result+ .call(folder: parent, user:)+ expect(result.result.files[2].location).to eq('/Photos/Birds/README.md')+ expect(result.result.ancestors[0].location).to eq('/')+ expect(result.result.ancestors[1].location).to eq('/Photos')++ assert_requested(:propfind, request_url)+ end+ end++ describe 'with storage running on a sub path' do+ let(:root_path) { '/storage' }++ it do+ result = subject+ .files_query+ .result+ .call(folder: nil, user:)+ expect(result.result.files[2].location).to eq('/README.md')+ assert_requested(:propfind, request_url)+ end+ end++ describe 'with storage running on a sub path and with parent parameter' do+ let(:root_path) { '/storage' }+ let(:parent) { '/Photos/Birds' }++ it do+ result = subject+ .files_query+ .result+ .call(folder: parent, user:)++ expect(result.result.files[2].location).to eq('/Photos/Birds/README.md')+ assert_requested(:propfind, request_url)+ end+ end+ end++ describe 'with not supported storage type selected' do+ before do+ allow(storage).to receive(:provider_type).and_return('not_supported_storage_type'.freeze)+ end++ it 'must raise ArgumentError' do+ expect { subject.files_query }.to raise_error(ArgumentError)+ end+ end++ describe 'with missing OAuth token' do+ before do+ allow_any_instance_of(OAuthClients::ConnectionManager).to receive(:get_access_token).and_return(ServiceResult.failure)+ end++ it 'must return ":not_authorized" ServiceResult' do+ result = subject+ .files_query+ .result+ .call(folder: parent, user:)+ expect(result).to be_failure+ expect(result.errors.code).to be(:not_authorized)+ end+ end+ end++ shared_examples_for 'outbound is failing' do |code = 500, symbol = :error|+ describe "with outbound request returning #{code}" do+ before do+ stub_request(:propfind, request_url).to_return(status: code)+ end++ it "must return :#{symbol} ServiceResult" do+ result = subject+ .files_query+ .result+ .call(folder: parent, user:)+ expect(result).to be_failure+ expect(result.errors.code).to be(symbol)+ end+ end+ end++ include_examples 'outbound is failing', 404, :not_found+ include_examples 'outbound is failing', 401, :not_authorized+ include_examples 'outbound is failing', 500, :error+ end++ describe '#file_query' do+ let(:file_id) { '819' }+ let(:expected_response_body) do+ <<~JSON+ {+ "ocs": {+ "meta": {+ "status": "ok",+ "statuscode": 100,+ "message": "OK",+ "totalitems": "",+ "itemsperpage": ""+ },+ "data": {+ "status": "OK",+ "statuscode": 200,+ "id": 819,+ "name": "[Sample] Project Name | Ehuuu(10)",+ "mtime": 1684491252,+ "ctime": 0,+ "mimetype": "application\\/x-op-directory",+ "size": 0,+ "owner_name": "OpenProject",+ "owner_id": "OpenProject",+ "trashed": false,+ "modifier_name": null,+ "modifier_id": null,+ "dav_permissions": "RMGDNVCK",+ "path": "files\\/OpenProject\\/[Sample] Project Name | Ehuuu(10)"+ }+ }+ }+ JSON+ end++ before do+ stub_request(:get, "https://example.com/ocs/v1.php/apps/integration_openproject/fileinfo/#{file_id}")+ .with(headers: {+ 'Accept' => 'application/json',+ 'Authorization' => 'Bearer xyz',+ 'Content-Type' => 'application/json'+ })+ .to_return(status: 200, body: expected_response_body, headers: {})+ end++ context 'with Nextcloud storage type selected' do+ it 'must return a list of files when called' do+ result = subject+ .file_query+ .result+ .call(user:, file_id:)+ expect(result).to be_success+ storage_file = result.result+ expect(storage_file.id).to eq(819)+ expect(storage_file.location).to eq("/OpenProject/[Sample] Project Name | Ehuuu(10)")+ expect(storage_file.mime_type).to eq("application/x-op-directory")+ expect(storage_file.name).to eq("[Sample] Project Name | Ehuuu(10)")+ expect(storage_file.permissions).to eq("RMGDNVCK")+ expect(storage_file.size).to eq(0)+ end+ end+ end++ describe '#upload_link_query' do+ let(:query_payload) { Struct.new(:parent).new(42) }+ let(:upload_token) { 'valid-token' }++ before do+ stub_request(:post, "#{url}/index.php/apps/integration_openproject/direct-upload-token")+ .with(body: { folder_id: query_payload.parent })+ .to_return(+ status: 200,+ body: {+ token: upload_token,+ expires_on: 1673883865+ }.to_json+ )+ end++ describe 'with Nextcloud storage type selected' do+ it 'must return an upload link URL' do+ link = subject+ .upload_link_query+ .result+ .call(user:, data: query_payload)+ .result+ expect(link.destination.path).to be_eql("/index.php/apps/integration_openproject/direct-upload/#{upload_token}")+ expect(link.destination.host).to be_eql(URI(url).host)+ expect(link.destination.scheme).to be_eql(URI(url).scheme)+ expect(link.destination.user).to be_nil+ expect(link.destination.password).to be_nil+ expect(link.method).to eq(:post)+ end+ end++ describe 'with not supported storage type selected' do+ before do+ allow(storage).to receive(:provider_type).and_return('not_supported_storage_type'.freeze)+ end++ it 'must raise ArgumentError' do+ expect { subject.upload_link_query }.to raise_error(ArgumentError)+ end+ end++ describe 'with missing OAuth token' do+ before do+ allow_any_instance_of(OAuthClients::ConnectionManager).to receive(:get_access_token).and_return(ServiceResult.failure)+ end++ it 'must return ":not_authorized" ServiceResult' do+ result = subject+ .upload_link_query+ .result+ .call(user:, data: query_payload)+ expect(result).to be_failure+ expect(result.errors.code).to be(:not_authorized)+ end+ end++ shared_examples_for 'outbound is failing' do |code, symbol|+ describe "with outbound request returning #{code}" do+ before do+ stub_request(:post, "#{url}/index.php/apps/integration_openproject/direct-upload-token").to_return(status: code)+ end++ it "must return :#{symbol} ServiceResult" do+ result = subject+ .upload_link_query+ .result+ .call(user:, data: query_payload)+ expect(result).to be_failure+ expect(result.errors.code).to be(symbol)+ end+ end+ end++ include_examples 'outbound is failing', 400, :error+ include_examples 'outbound is failing', 401, :not_authorized+ include_examples 'outbound is failing', 404, :not_found+ include_examples 'outbound is failing', 500, :error+ end++ describe '#legacy_upload_link_query', with_flag: { legacy_upload_preparation: true } do+ let(:query_payload) do+ Struct.new(:fileName, :parent).new("ape.png", "/Pictures")+ end++ let(:uri) do+ "#{url}/public.php/webdav/#{query_payload[:fileName]}"+ end++ let(:share_id) { 37 }++ before do+ stub_request(:post, "#{url}/ocs/v2.php/apps/files_sharing/api/v1/shares")+ .with(+ body: hash_including(+ {+ shareType: 3,+ path: query_payload.parent,+ expireDate: Date.tomorrow.iso8601+ }+ )+ )+ .to_return(+ status: 200,+ body: {+ ocs: {+ data: {+ id: share_id,+ token: 'jJ6t8yHe7CEX5Bp'+ }+ }+ }.to_json+ )+ stub_request(:put, "#{url}/ocs/v2.php/apps/files_sharing/api/v1/shares/#{share_id}")+ .with(body: { permissions: 5 })+ .to_return(status: 200, body: {}.to_json)+ end++ context 'with Nextcloud storage type selected' do+ it 'must return an upload link URL' do+ link = subject+ .upload_link_query+ .result+ .call(user:, data: query_payload)+ .result+ expect(link.destination.path).to be_eql("/public.php/webdav/#{query_payload.fileName}")+ expect(link.destination.host).to be_eql(URI(url).host)+ expect(link.destination.scheme).to be_eql(URI(url).scheme)+ expect(link.destination.user).not_to be_nil+ expect(link.destination.password).not_to be_nil+ expect(link.method).to eq(:put)+ end+ end++ context 'with not supported storage type selected' do+ before do+ allow(storage).to receive(:provider_type).and_return('not_supported_storage_type'.freeze)+ end++ it 'must raise ArgumentError' do+ expect do+ subject.upload_link_query.result.call(user:, data: query_payload)+ end.to raise_error(ArgumentError)+ end+ end++ context 'with missing OAuth token' do+ before do+ allow_any_instance_of(OAuthClients::ConnectionManager).to receive(:get_access_token).and_return(ServiceResult.failure)+ end++ it 'must return ":not_authorized" ServiceResult' do+ result = subject+ .upload_link_query+ .result+ .call(user:, data: query_payload)+ expect(result).to be_failure+ expect(result.errors.code).to be(:not_authorized)+ end+ end++ context 'with first outbound request returning 200 and an empty body' do+ before do+ stub_request(:post, "#{url}/ocs/v2.php/apps/files_sharing/api/v1/shares")+ .with(+ body: hash_including(+ {+ shareType: 3,+ path: query_payload.parent,+ expireDate: Date.tomorrow.iso8601+ }+ )+ )+ .to_return(status: 200)+ end++ it 'must return :not_authorized ServiceResult' do+ result = subject+ .upload_link_query+ .result+ .call(user:, data: query_payload)+ expect(result).to be_failure+ expect(result.errors.code).to be(:not_authorized)+ end+ end++ context 'with second outbound request returning 200 and an empty body' do+ before do+ stub_request(:put, "#{url}/ocs/v2.php/apps/files_sharing/api/v1/shares/#{share_id}")+ .with(body: { permissions: 5 })+ .to_return(status: 200)+ end++ it 'must return :not_authorized ServiceResult' do+ result = subject+ .upload_link_query+ .result+ .call(user:, data: query_payload)+ expect(result).to be_failure+ expect(result.errors.code).to be(:not_authorized)+ end+ end++ shared_examples_for 'outbound is failing' do |method = :get, path = '', code = 500, symbol = :error|+ context "with outbound request returning #{code}" do+ before do+ stub_request(method, "#{url}/ocs/v2.php/apps/files_sharing/api/v1/shares#{path}").to_return(status: code)+ end++ it "must return :#{symbol} ServiceResult" do+ result = subject+ .upload_link_query+ .result+ .call(user:, data: query_payload)+ expect(result).to be_failure+ expect(result.errors.code).to be(symbol)+ end+ end+ end++ include_examples 'outbound is failing', :post, '', 404, :not_found+ include_examples 'outbound is failing', :post, '', 401, :not_authorized+ include_examples 'outbound is failing', :post, '', 500, :error+ include_examples 'outbound is failing', :put, '/37', 404, :not_found+ include_examples 'outbound is failing', :put, '/37', 401, :not_authorized+ include_examples 'outbound is failing', :put, '/37', 500, :error+ endend- let(:token) do- token = instance_double(OAuthClientToken)- allow(token).to receive(:origin_user_id).and_return(origin_user_id)- allow(token).to receive(:access_token).and_return('xyz')- token+ describe '#group_users_query' do+ let(:expected_response_body) do+ <<~XML+ <?xml version="1.0"?>+ <ocs>+ <meta>+ <status>ok</status>+ <statuscode>100</statuscode>+ <message>OK</message>+ <totalitems></totalitems>+ <itemsperpage></itemsperpage>+ </meta>+ <data>+ <users>+ <element>admin</element>+ <element>OpenProject</element>+ <element>reader</element>+ <element>TestUser</element>+ <element>TestUser34</element>+ </users>+ </data>+ </ocs>+ XML+ end+ let(:expected_response) do+ {+ status: 200,+ body: expected_response_body,+ headers: {}+ }+ end++ before do+ stub_request(:get, "https://example.com/ocs/v1.php/cloud/groups/#{storage.group}")+ .with(+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6T3BlblByb2plY3RTZWN1cmVQYXNzd29yZA==',+ 'OCS-APIRequest' => 'true'+ }+ )+ .to_return(expected_response)+ end++ it 'responds with a strings array with group users' do+ result = subject+ .group_users_query+ .result+ .call+ expect(result).to be_success+ expect(result.result).to eq(["admin", "OpenProject", "reader", "TestUser", "TestUser34"])+ endend- let(:connection_manager) do- connection_manager = instance_double(OAuthClients::ConnectionManager)- allow(connection_manager).to receive(:get_access_token).and_return(ServiceResult.success(result: token))- allow(connection_manager).to receive(:request_with_token_refresh).and_yield(token)- connection_manager+ describe '#add_user_to_group_command' do+ let(:expected_response) do+ {+ status: 200,+ body: expected_response_body,+ headers: {}+ }+ end+ let(:expected_response_body) do+ <<~XML+ <?xml version="1.0"?>+ <ocs>+ <meta>+ <status>ok</status>+ <statuscode>100</statuscode>+ <message>OK</message>+ <totalitems></totalitems>+ <itemsperpage></itemsperpage>+ </meta>+ <data/>+ </ocs>+ XML+ end++ before do+ stub_request(:post, "https://example.com/ocs/v1.php/cloud/users/#{origin_user_id}/groups")+ .with(+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6T3BlblByb2plY3RTZWN1cmVQYXNzd29yZA==',+ 'OCS-APIRequest' => 'true'+ }+ )+ .to_return(expected_response)+ end++ it 'adds user to the group' do+ result = subject+ .add_user_to_group_command+ .result+ .call(user: origin_user_id)+ expect(result).to be_success+ expect(result.message).to eq("User has been added successfully")+ endend- subject { described_class.new(storage:) }+ describe '#remove_user_from_group' do+ let(:expected_response) do+ {+ status: 200,+ body: expected_response_body,+ headers: {}+ }+ end+ let(:expected_response_body) do+ <<~XML+ <?xml version="1.0"?>+ <ocs>+ <meta>+ <status>ok</status>+ <statuscode>100</statuscode>+ <message>OK</message>+ <totalitems></totalitems>+ <itemsperpage></itemsperpage>+ </meta>+ <data/>+ </ocs>+ XML+ end++ before do+ stub_request(:delete, "https://example.com/ocs/v1.php/cloud/users/#{origin_user_id}/groups?groupid=#{storage.group}")+ .with(+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6T3BlblByb2plY3RTZWN1cmVQYXNzd29yZA==',+ 'OCS-APIRequest' => 'true'+ }+ )+ .to_return(expected_response)+ end++ it 'removes user from the group' do+ result = subject+ .remove_user_from_group_command+ .result+ .call(user: origin_user_id)+ expect(result).to be_success+ expect(result.message).to eq("User has been removed from group")+ end+ enddescribe '#create_folder_command' do+ let(:folder_path) { 'OpenProject/JediProject' }+before dostub_request(:mkcol, "https://example.com/remote.php/dav/files/OpenProject/OpenProject/JediProject")- .with(- headers: {- 'Authorization' => 'Basic T3BlblByb2plY3Q6T3BlblByb2plY3RTZWN1cmVQYXNzd29yZA=='- }- )- .to_return(expected_response)+ .with(+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6T3BlblByb2plY3RTZWN1cmVQYXNzd29yZA=='+ }+ )+ .to_return(expected_response)endcontext 'when folder does not exist yet' do@@ -77,18 +784,12 @@ describe Storages::Peripherals::StorageRequests, webmock: true doendit 'creates a folder and responds with a success' do- subject- .create_folder_command- .match(- on_success: ->(command) do- result = command.call(folder: 'JediProject')- expect(result).to be_success- expect(result.message).to eq("Folder was successfully created.")- end,- on_failure: ->(error) do- raise "Create folder command could not be executed: #{error}"- end- )+ result = subject+ .create_folder_command+ .result+ .call(folder_path:)+ expect(result).to be_success+ expect(result.message).to eq("Folder was successfully created.")endend@@ -111,18 +812,12 @@ describe Storages::Peripherals::StorageRequests, webmock: true doendit 'does not create a folder and responds with a success' do- subject- .create_folder_command- .match(- on_success: ->(command) do- result = command.call(folder: 'JediProject')- expect(result).to be_success- expect(result.message).to eq("Folder already exists.")- end,- on_failure: ->(error) do- raise "Create folder command could not be executed: #{error}"- end- )+ result = subject+ .create_folder_command+ .result+ .call(folder_path:)+ expect(result).to be_success+ expect(result.message).to eq("Folder already exists.")endend@@ -145,47 +840,30 @@ describe Storages::Peripherals::StorageRequests, webmock: true doendit 'does not create a folder and responds with a failure' do- subject- .create_folder_command- .match(- on_success: ->(command) do- result = command.call(folder: 'JediProject')- expect(result).to be_failure- expect(result.result).to eq(:conflict)- expect(result.errors.log_message).to eq('Parent node does not exist')- end,- on_failure: ->(error) do- raise "Create folder command could not be executed: #{error}"- end- )+ result = subject+ .create_folder_command+ .result+ .call(folder_path:)+ expect(result).to be_failure+ expect(result.result).to eq(:conflict)+ expect(result.errors.log_message).to eq('Parent node does not exist')endendenddescribe '#set_permissions_command' do+ let(:path) { 'OpenProject/JediProject' }let(:permissions) do- [- {- origin_user_id: 'Obi-Wan',- permissions: {- read_files: true,- write_files: true,- create_files: true,- share_files: true,- delete_files: true- }+ {+ users: {+ OpenProject: 31,+ 'Obi-Wan': 31,+ 'Qui-Gon': 31},- {- origin_user_id: 'Qui-Gon',- permissions: {- read_files: true,- write_files: true,- create_files: true,- share_files: true,- delete_files: true- }+ groups: {+ OpenProject: 0}- ]+ }endlet(:expected_request_body) do@@ -196,16 +874,16 @@ describe Storages::Peripherals::StorageRequests, webmock: true do<d:prop><nc:acl-list><nc:acl>- <nc:acl-mapping-type>user</nc:acl-mapping-type>+ <nc:acl-mapping-type>group</nc:acl-mapping-type><nc:acl-mapping-id>OpenProject</nc:acl-mapping-id><nc:acl-mask>31</nc:acl-mask>- <nc:acl-permissions>31</nc:acl-permissions>+ <nc:acl-permissions>0</nc:acl-permissions></nc:acl><nc:acl>- <nc:acl-mapping-type>group</nc:acl-mapping-type>+ <nc:acl-mapping-type>user</nc:acl-mapping-type><nc:acl-mapping-id>OpenProject</nc:acl-mapping-id><nc:acl-mask>31</nc:acl-mask>- <nc:acl-permissions>0</nc:acl-permissions>+ <nc:acl-permissions>31</nc:acl-permissions></nc:acl><nc:acl><nc:acl-mapping-type>user</nc:acl-mapping-type>@@ -230,13 +908,13 @@ describe Storages::Peripherals::StorageRequests, webmock: true docontext 'with outbound request' dobefore dostub_request(:proppatch, "#{url}/remote.php/dav/files/OpenProject/OpenProject/JediProject")- .with(- body: expected_request_body,- headers: {- 'Authorization' => 'Basic T3BlblByb2plY3Q6T3BlblByb2plY3RTZWN1cmVQYXNzd29yZA=='- }- )- .to_return(expected_response)+ .with(+ body: expected_request_body,+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6T3BlblByb2plY3RTZWN1cmVQYXNzd29yZA=='+ }+ )+ .to_return(expected_response)endcontext 'when permissions can be set' do@@ -269,17 +947,11 @@ describe Storages::Peripherals::StorageRequests, webmock: true doendit 'returns success when permissions can be set' do- subject- .set_permissions_command- .match(- on_success: ->(command) do- result = command.call(folder: 'JediProject', permissions:)- expect(result).to be_success- end,- on_failure: ->(error) do- raise "Set permissions command could not be executed: #{error}"- end- )+ result = subject+ .set_permissions_command+ .result+ .call(path:, permissions:)+ expect(result).to be_successendend@@ -304,17 +976,11 @@ describe Storages::Peripherals::StorageRequests, webmock: true doendit 'returns failure' do- subject- .set_permissions_command- .match(- on_success: ->(command) do- result = command.call(folder: 'JediProject', permissions:)- expect(result).to be_failure- end,- on_failure: ->(error) do- raise "Set permissions command could not be executed: #{error}"- end- )+ result = subject+ .set_permissions_command+ .result+ .call(path:, permissions:)+ expect(result).to be_failureendend@@ -339,688 +1005,170 @@ describe Storages::Peripherals::StorageRequests, webmock: true doendit 'returns failure' do- subject- .set_permissions_command- .match(- on_success: ->(command) do- result = command.call(folder: 'JediProject', permissions:)- expect(result).to be_failure- end,- on_failure: ->(error) do- raise "Set permissions command could not be executed: #{error}"- end- )+ result = subject+ .set_permissions_command+ .result+ .call(path:, permissions:)+ expect(result).to be_failureendendendcontext 'when forbidden values are given as folder' doit 'raises an ArgumentError on nil' do- subject+ expect do+ subject.set_permissions_command- .match(- on_success: ->(command) do- expect { command.call(folder: nil, permissions:) }.to raise_error(ArgumentError)- end,- on_failure: ->(error) do- raise "Set permissions command could not be executed: #{error}"- end- )+ .result+ .call(path: nil, permissions:)+ end.to raise_error(ArgumentError)endit 'raises an ArgumentError on empty string' do- subject+ expect do+ subject.set_permissions_command- .match(- on_success: ->(command) do- expect { command.call(folder: '', permissions:) }.to raise_error(ArgumentError)- end,- on_failure: ->(error) do- raise "Set permissions command could not be executed: #{error}"- end- )- end- end- end- end-- describe '#download_link_query' do- let(:file_link) do- Struct.new(:file_link) do- def origin_id- 42- end-- def origin_name- 'example.md'- end- end.new- end- let(:download_token) { "8dM3dC9iy1N74F5AJ0ClnjSF4dWTxfymVy1HTXBh8rbZVM81CpcBJaIYZvmR" }- let(:uri) do- "#{url}/index.php/apps/integration_openproject/direct/#{download_token}/#{CGI.escape(file_link.origin_name)}"- end- let(:json) do- {- ocs: {- meta: {- status: 'ok',- statuscode: 200,- message: 'OK'- },- data: {- url: "https://example.com/remote.php/direct/#{download_token}"- }- }- }.to_json- end-- before do- allow(OAuthClients::ConnectionManager).to receive(:new).and_return(connection_manager)- stub_request(:post, "#{url}/ocs/v2.php/apps/dav/api/v1/direct")- .to_return(status: 200, body: json, headers: {})- end-- describe 'with Nextcloud storage type selected' do- it 'must return a download link URL' do- subject- .download_link_query(user:)- .match(- on_success: ->(query) do- result = query.call(file_link)- expect(result).to be_success- expect(result.result).to be_eql(uri)- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end-- context 'if Nextcloud is running on a sub path' do- let(:url) { 'https://example.com/html' }-- it 'must return a download link URL' do- subject- .download_link_query(user:)- .match(- on_success: ->(query) do- result = query.call(file_link)- expect(result).to be_success- expect(result.result).to be_eql(uri)- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end- end- end-- describe 'with not supported storage type selected' do- before do- allow(storage).to receive(:provider_type).and_return('not_supported_storage_type'.freeze)- end-- it 'must raise ArgumentError' do- expect { subject.download_link_query(user:) }.to raise_error(ArgumentError)- end- end-- describe 'with missing OAuth token' do- before do- allow(connection_manager).to receive(:get_access_token).and_return(ServiceResult.failure)- end-- it 'must return ":not_authorized" ServiceResult' do- expect(subject.download_link_query(user:)).to be_failure- end- end-- describe 'with outbound request returning 200 and an empty body' do- before do- stub_request(:post, "#{url}/ocs/v2.php/apps/dav/api/v1/direct").to_return(status: 200, body: '')- end-- it 'must return :not_authorized ServiceResult' do- subject- .download_link_query(user:)- .match(- on_success: ->(query) do- result = query.call(file_link)- expect(result).to be_failure- expect(result.errors.code).to be(:not_authorized)- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end- end-- shared_examples_for 'outbound is failing' do |code = 500, symbol = :error|- describe "with outbound request returning #{code}" do- before do- stub_request(:post, "#{url}/ocs/v2.php/apps/dav/api/v1/direct").to_return(status: code)- end-- it "must return :#{symbol} ServiceResult" do- subject- .download_link_query(user:)- .match(- on_success: ->(query) do- result = query.call(file_link)- expect(result).to be_failure- expect(result.errors.code).to be(symbol)- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )+ .result+ .call(path: '', permissions:)+ end.to raise_error(ArgumentError)endendend-- include_examples 'outbound is failing', 404, :not_found- include_examples 'outbound is failing', 401, :not_authorized- include_examples 'outbound is failing', 500, :errorend- describe '#files_query' do- let(:parent) { '' }- let(:root_path) { '' }- let(:xml) { create(:webdav_data, parent_path: parent, root_path:) }- let(:url) { "https://example.com#{root_path}" }- let(:request_url) { "#{url}/remote.php/dav/files/#{origin_user_id.gsub(' ', '%20')}#{parent}" }-- before do- allow(OAuthClients::ConnectionManager).to receive(:new).and_return(connection_manager)- stub_request(:propfind, request_url)- .to_return(status: 207, body: xml, headers: {})- end-- describe 'with Nextcloud storage type selected' do- it 'must return a list of files when called' do- subject- .files_query(user:)- .match(- on_success: ->(query) do- result = query.call(nil)- expect(result).to be_success- expect(result.result.files.size).to eq(4)- expect(result.result.ancestors.size).to eq(0)- expect(result.result.parent).not_to be_nil- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end-- it 'must return a named directory' do- subject- .files_query(user:)- .match(- on_success: ->(query) do- result = query.call(nil)- expect(result).to be_success- expect(result.result.files[0].name).to eq('Folder1')- expect(result.result.files[0].mime_type).to eq('application/x-op-directory')- expect(result.result.files[0].id).to eq('11')- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end-- it 'must return directories with permissions' do- subject- .files_query(user:)- .match(- on_success: ->(query) do- result = query.call(nil)- expect(result).to be_success-- expect(result.result.files[0].mime_type).to eq('application/x-op-directory')- expect(result.result.files[0].permissions).to include(:readable)- expect(result.result.files[0].permissions).to include(:writeable)-- expect(result.result.files[1].mime_type).to eq('application/x-op-directory')- expect(result.result.files[1].permissions).to include(:readable)- expect(result.result.files[1].permissions).not_to include(:writeable)- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end-- it 'must return files with permissions' do- subject- .files_query(user:)- .match(- on_success: ->(query) do- result = query.call(nil)- expect(result).to be_success-- expect(result.result.files[2].mime_type).to eq('text/markdown')- expect(result.result.files[2].permissions).to include(:readable)- expect(result.result.files[2].permissions).to include(:writeable)-- expect(result.result.files[3].mime_type).to eq('application/pdf')- expect(result.result.files[3].permissions).to include(:readable)- expect(result.result.files[3].permissions).not_to include(:writeable)- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end-- it 'must return a named file' do- subject- .files_query(user:)- .match(- on_success: ->(query) do- result = query.call(nil)- expect(result).to be_success- expect(result.result.files[2].name).to eq('README.md')- expect(result.result.files[2].mime_type).to eq('text/markdown')- expect(result.result.files[2].id).to eq('12')- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end-- describe 'with origin user id containing whitespaces' do- let(:origin_user_id) { 'my user' }- let(:xml) { create(:webdav_data, origin_user_id:) }-- it do- subject- .files_query(user:)- .match(- on_success: ->(query) {- result = query.call(parent)- expect(result.result.files[0].location).to eq('/Folder1')- },- on_failure: ->(error) { raise "Files query could not be created: #{error}" }- )-- assert_requested(:propfind, request_url)- end- end-- describe 'with parent query parameter' do- let(:parent) { '/Photos/Birds' }-- it do- subject- .files_query(user:)- .match(- on_success: ->(query) {- result = query.call(parent)- expect(result.result.files[2].location).to eq('/Photos/Birds/README.md')- expect(result.result.ancestors[0].location).to eq('/')- expect(result.result.ancestors[1].location).to eq('/Photos')- },- on_failure: ->(error) { raise "Files query could not be created: #{error}" }- )-- assert_requested(:propfind, request_url)- end- end-- describe 'with storage running on a sub path' do- let(:root_path) { '/storage' }-- it do- subject- .files_query(user:)- .match(- on_success: ->(query) {- result = query.call(nil)- expect(result.result.files[2].location).to eq('/README.md')- },- on_failure: ->(error) { raise "Files query could not be created: #{error}" }- )-- assert_requested(:propfind, request_url)- end- end-- describe 'with storage running on a sub path and with parent parameter' do- let(:root_path) { '/storage' }- let(:parent) { '/Photos/Birds' }-- it do- subject- .files_query(user:)- .match(- on_success: ->(query) {- result = query.call(parent)- expect(result.result.files[2].location).to eq('/Photos/Birds/README.md')- },- on_failure: ->(error) { raise "Files query could not be created: #{error}" }- )-- assert_requested(:propfind, request_url)- end- end- end-- describe 'with not supported storage type selected' do- before do- allow(storage).to receive(:provider_type).and_return('not_supported_storage_type'.freeze)- end-- it 'must raise ArgumentError' do- expect { subject.files_query(user:) }.to raise_error(ArgumentError)- end- end-- describe 'with missing OAuth token' do- before do- allow(connection_manager).to receive(:get_access_token).and_return(ServiceResult.failure)- end-- it 'must return ":not_authorized" ServiceResult' do- expect(subject.files_query(user:)).to be_failure- end+ describe '#propfind_query' do+ let(:expected_request_body) do+ <<~XML+ <?xml version="1.0"?>+ <d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">+ <d:prop>+ <oc:fileid/>+ </d:prop>+ </d:propfind>+ XMLend-- shared_examples_for 'outbound is failing' do |code = 500, symbol = :error|- describe "with outbound request returning #{code}" do- before do- stub_request(:propfind, "#{url}/remote.php/dav/files/#{origin_user_id}").to_return(status: code)- end-- it "must return :#{symbol} ServiceResult" do- subject- .files_query(user:)- .match(- on_success: ->(query) do- result = query.call(nil)- expect(result).to be_failure- expect(result.errors.code).to be(symbol)- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end- end+ let(:expected_response_body) do+ <<~XML+ <?xml version="1.0"?>+ <d:multistatus+ xmlns:d="DAV:"+ xmlns:s="http://sabredav.org/ns"+ xmlns:oc="http://owncloud.org/ns"+ xmlns:nc="http://nextcloud.org/ns">+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/</d:href>+ <d:propstat>+ <d:prop>+ <oc:fileid>349</oc:fileid>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/asd/</d:href>+ <d:propstat>+ <d:prop>+ <oc:fileid>783</oc:fileid>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/Project%231/</d:href>+ <d:propstat>+ <d:prop>+ <oc:fileid>773</oc:fileid>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/Project%20%232/</d:href>+ <d:propstat>+ <d:prop>+ <oc:fileid>381</oc:fileid>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/Project%232/</d:href>+ <d:propstat>+ <d:prop>+ <oc:fileid>398</oc:fileid>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/qwe/</d:href>+ <d:propstat>+ <d:prop>+ <oc:fileid>767</oc:fileid>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ <d:propstat>+ </d:response>+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/qweekk/</d:href>+ <d:propstat>+ <d:prop>+ <oc:fileid>802</oc:fileid>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ </d:multistatus>+ XMLend- include_examples 'outbound is failing', 404, :not_found- include_examples 'outbound is failing', 401, :not_authorized- include_examples 'outbound is failing', 500, :error- end-- describe '#upload_link_query' do- let(:query_payload) { Struct.new(:parent).new(42) }- let(:upload_token) { 'valid-token' }-before do- allow(OAuthClients::ConnectionManager).to receive(:new).and_return(connection_manager)- stub_request(:post, "#{url}/index.php/apps/integration_openproject/direct-upload-token")- .with(body: { folder_id: query_payload.parent })- .to_return(- status: 200,- body: {- token: upload_token,- expires_on: 1673883865- }.to_json- )+ stub_request(:propfind, "https://example.com/remote.php/dav/files/OpenProject/OpenProject").with(+ body: expected_request_body,+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6T3BlblByb2plY3RTZWN1cmVQYXNzd29yZA==',+ 'Depth' => '1'+ }+ ).to_return(status: 200, body: expected_response_body, headers: {})enddescribe 'with Nextcloud storage type selected' do- it 'must return an upload link URL' do- subject- .upload_link_query(user:)- .match(- on_success: ->(query) do- query.call(query_payload).match(- on_success: ->(link) {- expect(link.destination.path).to be_eql("/index.php/apps/integration_openproject/direct-upload/#{upload_token}")- expect(link.destination.host).to be_eql(URI(url).host)- expect(link.destination.scheme).to be_eql(URI(url).scheme)- expect(link.destination.user).to be_nil- expect(link.destination.password).to be_nil- expect(link.method).to eq(:post)- },- on_failure: ->(error) {- raise "Files query could not be executed: #{error}"- }- )- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end- end-- describe 'with not supported storage type selected' do- before do- allow(storage).to receive(:provider_type).and_return('not_supported_storage_type'.freeze)- end-- it 'must raise ArgumentError' do- expect { subject.upload_link_query(user:) }.to raise_error(ArgumentError)- end- end-- describe 'with missing OAuth token' do- before do- allow(connection_manager).to receive(:get_access_token).and_return(ServiceResult.failure)- end-- it 'must return ":not_authorized" ServiceResult' do- expect(subject.upload_link_query(user:)).to be_failure- end- end-- shared_examples_for 'outbound is failing' do |code, symbol|- describe "with outbound request returning #{code}" do- before do- stub_request(:post, "#{url}/index.php/apps/integration_openproject/direct-upload-token").to_return(status: code)- end-- it "must return :#{symbol} ServiceResult" do- subject- .upload_link_query(user:)- .match(- on_success: ->(query) do- result = query.call(query_payload)- expect(result).to be_failure- expect(result.errors.code).to be(symbol)- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end+ it 'responds with a list of paths and attributes for each of them' do+ result = subject+ .propfind_query+ .result+ .call(depth: '1', path: 'OpenProject')+ .result+ expect(result).to eq({ "OpenProject/" => { "fileid" => "349" },+ "OpenProject/Project #2/" => { "fileid" => "381" },+ "OpenProject/Project#1/" => { "fileid" => "773" },+ "OpenProject/Project#2/" => { "fileid" => "398" },+ "OpenProject/asd/" => { "fileid" => "783" },+ "OpenProject/qwe/" => { "fileid" => "767" } })endend-- include_examples 'outbound is failing', 400, :error- include_examples 'outbound is failing', 401, :not_authorized- include_examples 'outbound is failing', 404, :not_found- include_examples 'outbound is failing', 500, :errorend- describe '#legacy_upload_link_query', with_flag: { legacy_upload_preparation: true } do- let(:query_payload) do- Struct.new(:fileName, :parent).new("ape.png", "/Pictures")- end-- let(:uri) do- "#{url}/public.php/webdav/#{query_payload[:fileName]}"- end-- let(:share_id) { 37 }-+ describe '#rename_file_command' dobefore do- allow(OAuthClients::ConnectionManager).to receive(:new).and_return(connection_manager)- stub_request(:post, "#{url}/ocs/v2.php/apps/files_sharing/api/v1/shares")- .with(- body: hash_including(- {- shareType: 3,- path: query_payload.parent,- expireDate: Date.tomorrow.iso8601- }- )- )- .to_return(- status: 200,- body: {- ocs: {- data: {- id: share_id,- token: 'jJ6t8yHe7CEX5Bp'- }- }- }.to_json- )- stub_request(:put, "#{url}/ocs/v2.php/apps/files_sharing/api/v1/shares/#{share_id}")- .with(body: { permissions: 5 })- .to_return(status: 200, body: {}.to_json)+ stub_request(:move, "https://example.com/remote.php/dav/files/OpenProject/OpenProject/asd")+ .with(+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6T3BlblByb2plY3RTZWN1cmVQYXNzd29yZA==',+ 'Destination' => '/remote.php/dav/files/OpenProject/OpenProject/qwe'+ }+ ).to_return(status: 201, body: '', headers: {})enddescribe 'with Nextcloud storage type selected' do- it 'must return an upload link URL' do- subject- .upload_link_query(user:)- .match(- on_success: ->(query) do- query.call(query_payload).match(- on_success: ->(link) {- expect(link.destination.path).to be_eql("/public.php/webdav/#{query_payload.fileName}")- expect(link.destination.host).to be_eql(URI(url).host)- expect(link.destination.scheme).to be_eql(URI(url).scheme)- expect(link.destination.user).not_to be_nil- expect(link.destination.password).not_to be_nil- expect(link.method).to eq(:put)- },- on_failure: ->(error) {- raise "Files query could not be executed: #{error}"- }- )- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end- end-- describe 'with not supported storage type selected' do- before do- allow(storage).to receive(:provider_type).and_return('not_supported_storage_type'.freeze)- end-- it 'must raise ArgumentError' do- expect { subject.upload_link_query(user:) }.to raise_error(ArgumentError)- end- end-- describe 'with missing OAuth token' do- before do- allow(connection_manager).to receive(:get_access_token).and_return(ServiceResult.failure)- end-- it 'must return ":not_authorized" ServiceResult' do- expect(subject.upload_link_query(user:)).to be_failure+ it 'moves the file' do+ result = subject+ .rename_file_command+ .result+ .call(source: 'OpenProject/asd', target: 'OpenProject/qwe')+ expect(result).to be_successendend-- describe 'with first outbound request returning 200 and an empty body' do- before do- stub_request(:post, "#{url}/ocs/v2.php/apps/files_sharing/api/v1/shares")- .with(- body: hash_including(- {- shareType: 3,- path: query_payload.parent,- expireDate: Date.tomorrow.iso8601- }- )- )- .to_return(status: 200)- end-- it 'must return :not_authorized ServiceResult' do- subject- .upload_link_query(user:)- .match(- on_success: ->(query) do- result = query.call(query_payload)- expect(result).to be_failure- expect(result.errors.code).to be(:not_authorized)- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end- end-- describe 'with second outbound request returning 200 and an empty body' do- before do- stub_request(:put, "#{url}/ocs/v2.php/apps/files_sharing/api/v1/shares/#{share_id}")- .with(body: { permissions: 5 })- .to_return(status: 200)- end-- it 'must return :not_authorized ServiceResult' do- subject- .upload_link_query(user:)- .match(- on_success: ->(query) do- result = query.call(query_payload)- expect(result).to be_failure- expect(result.errors.code).to be(:not_authorized)- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end- end-- shared_examples_for 'outbound is failing' do |method = :get, path = '', code = 500, symbol = :error|- describe "with outbound request returning #{code}" do- before do- stub_request(method, "#{url}/ocs/v2.php/apps/files_sharing/api/v1/shares#{path}").to_return(status: code)- end-- it "must return :#{symbol} ServiceResult" do- subject- .upload_link_query(user:)- .match(- on_success: ->(query) do- result = query.call(query_payload)- expect(result).to be_failure- expect(result.errors.code).to be(symbol)- end,- on_failure: ->(error) do- raise "Files query could not be created: #{error}"- end- )- end- end- end-- include_examples 'outbound is failing', :post, '', 404, :not_found- include_examples 'outbound is failing', :post, '', 401, :not_authorized- include_examples 'outbound is failing', :post, '', 500, :error- include_examples 'outbound is failing', :put, '/37', 404, :not_found- include_examples 'outbound is failing', :put, '/37', 401, :not_authorized- include_examples 'outbound is failing', :put, '/37', 500, :errorendenddiff --git a/modules/storages/spec/features/create_file_links_spec.rb b/modules/storages/spec/features/create_file_links_spec.rbindex 86fd186dc46..aae68a97d87 100644--- a/modules/storages/spec/features/create_file_links_spec.rb+++ b/modules/storages/spec/features/create_file_links_spec.rb@@ -41,15 +41,6 @@ describe 'Managing file links in work package', js: true, webmock: true dolet(:project_storage) { create(:project_storage, project:, storage:, project_folder_id: nil, project_folder_mode: 'inactive') }let(:file_link) { create(:file_link, container: work_package, storage:, origin_id: '22', origin_name: 'jingle.ogg') }- let(:connection_manager) do- connection_manager = instance_double(OAuthClients::ConnectionManager)- allow(connection_manager).to receive(:refresh_token).and_return(ServiceResult.success(result: oauth_client_token))- allow(connection_manager).to receive(:get_access_token).and_return(ServiceResult.success(result: oauth_client_token))- allow(connection_manager).to receive(:authorization_state).and_return(:connected)- allow(connection_manager).to receive(:request_with_token_refresh).and_yield(oauth_client_token)- connection_manager- end-let(:root_xml_response) { create(:webdav_data) }let(:folder1_xml_response) { create(:webdav_data_folder) }@@ -66,10 +57,18 @@ describe 'Managing file links in work package', js: true, webmock: true dolet(:confirmation_dialog) { Components::ConfirmationDialog.new }before do- allow(OAuthClients::ConnectionManager).to receive(:new).and_return(connection_manager)allow(Storages::FileLinkSyncService).to receive(:new).and_return(sync_service)- stub_request(:propfind, "#{storage.host}/remote.php/dav/files/#{oauth_client_token.origin_user_id}")+ stub_request(:get, "https://host1.example.com/ocs/v1.php/cloud/user").+ with(+ headers: {+ 'Authorization'=>'Bearer 1234567890-1',+ 'Host'=>'host1.example.com',+ 'Ocs-Apirequest'=>'true',+ 'Accept' => "application/json"+ }).+ to_return(status: 200, body: "", headers: {})+ stub_request(:propfind, "#{storage.host}/remote.php/dav/files/#{oauth_client_token.origin_user_id}/").to_return(status: 207, body: root_xml_response, headers: {})stub_request(:propfind, "#{storage.host}/remote.php/dav/files/#{oauth_client_token.origin_user_id}/Folder1").to_return(status: 207, body: folder1_xml_response, headers: {})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 f27c656d6bd..928433eba06 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@@ -631,18 +631,10 @@ describe 'API v3 file links resource' doenddescribe 'with query failed' do- let(:download_link_query) do- Struct.new('DownloadLinkQuery', :error) do- def query(_)- ServiceResult.failure(result: error, errors: Storages::StorageError.new(code: error))- end- end.new(error)- end-before do- storage_queries = instance_double(Storages::Peripherals::StorageInteraction::StorageQueries)- allow(storage_queries).to receive(:download_link_query).and_return(ServiceResult.success(result: download_link_query))- allow(Storages::Peripherals::StorageInteraction::StorageQueries).to receive(:new).and_return(storage_queries)+ allow_any_instance_of(+ Storages::Peripherals::StorageInteraction::Nextcloud::DownloadLinkQuery+ ).to receive(:call).and_return(ServiceResult.failure(result: error, errors: Storages::StorageError.new(code: error)))get pathenddiff --git a/modules/storages/spec/requests/api/v3/storages/storage_files_spec.rb b/modules/storages/spec/requests/api/v3/storages/storage_files_spec.rbindex 71985d1b6d5..22915a05c1e 100644--- a/modules/storages/spec/requests/api/v3/storages/storage_files_spec.rb+++ b/modules/storages/spec/requests/api/v3/storages/storage_files_spec.rb@@ -156,21 +156,10 @@ describe 'API v3 storage files', content_type: :json, webmock: true doenddescribe 'with query failed' do- let(:files_query) do- Struct.new('FilesQuery', :error) do- def query(_)- ServiceResult.failure(- result: error,- errors: Storages::StorageError.new(code: error)- )- end- end.new(error)- end-before do- storage_queries = instance_double(Storages::Peripherals::StorageInteraction::StorageQueries)- allow(storage_queries).to receive(:files_query).and_return(ServiceResult.success(result: files_query))- allow(Storages::Peripherals::StorageInteraction::StorageQueries).to receive(:new).and_return(storage_queries)+ allow_any_instance_of(+ Storages::Peripherals::StorageInteraction::Nextcloud::FilesQuery+ ).to receive(:call).and_return(ServiceResult.failure(result: error, errors: Storages::StorageError.new(code: error)))enddescribe 'due to authorization failure' dodiff --git a/modules/storages/spec/workers/manage_nextcloud_integration_job_spec.rb b/modules/storages/spec/workers/manage_nextcloud_integration_job_spec.rbnew file mode 100644index 00000000000..d99a23db171--- /dev/null+++ b/modules/storages/spec/workers/manage_nextcloud_integration_job_spec.rb@@ -0,0 +1,445 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2023 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.+#++++require 'spec_helper'++describe ManageNextcloudIntegrationJob, type: :job, webmock: true do+ let(:group_users_response_body) do+ <<~XML+ <?xml version="1.0"?>+ <ocs>+ <meta>+ <status>ok</status>+ <statuscode>100</statuscode>+ <message>OK</message>+ <totalitems></totalitems>+ <itemsperpage></itemsperpage>+ </meta>+ <data>+ <users>+ <element>Darth Maul</element>+ </users>+ </data>+ </ocs>+ XML+ end+ let(:set_permissions_response_body1) do+ <<~XML+ <?xml version="1.0"?>+ <d:multistatus+ xmlns:d="DAV:"+ xmlns:s="http://sabredav.org/ns"+ xmlns:oc="http://owncloud.org/ns"+ xmlns:nc="http://nextcloud.org/ns">+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject</d:href>+ <d:propstat>+ <d:prop>+ <nc:acl-list/>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ </d:multistatus>+ XML+ end+ let(:set_permissions_request_body1) do+ <<~XML+ <?xml version="1.0"?>+ <d:propertyupdate xmlns:d="DAV:" xmlns:nc="http://nextcloud.org/ns">+ <d:set>+ <d:prop>+ <nc:acl-list>+ <nc:acl>+ <nc:acl-mapping-type>group</nc:acl-mapping-type>+ <nc:acl-mapping-id>OpenProject</nc:acl-mapping-id>+ <nc:acl-mask>31</nc:acl-mask>+ <nc:acl-permissions>1</nc:acl-permissions>+ </nc:acl>+ <nc:acl>+ <nc:acl-mapping-type>user</nc:acl-mapping-type>+ <nc:acl-mapping-id>OpenProject</nc:acl-mapping-id>+ <nc:acl-mask>31</nc:acl-mask>+ <nc:acl-permissions>31</nc:acl-permissions>+ </nc:acl>+ </nc:acl-list>+ </d:prop>+ </d:set>+ </d:propertyupdate>+ XML+ end+ let(:propfind_request_body) do+ <<~XML+ <?xml version="1.0"?>+ <d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">+ <d:prop>+ <oc:fileid/>+ </d:prop>+ </d:propfind>+ XML+ end+ let(:propfind_response_body1) do+ <<~XML+ <?xml version="1.0"?>+ <d:multistatus+ xmlns:d="DAV:"+ xmlns:s="http://sabredav.org/ns"+ xmlns:oc="http://owncloud.org/ns"+ xmlns:nc="http://nextcloud.org/ns">+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/</d:href>+ <d:propstat>+ <d:prop>+ <oc:fileid>349</oc:fileid>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/Lost%20Jedi%20Project%20Folder%20%232/</d:href>+ <d:propstat>+ <d:prop>+ <oc:fileid>783</oc:fileid>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/Lost%20Jedi%20Project%20Folder%20%233/</d:href>+ <d:propstat>+ <d:prop>+ <oc:fileid>123</oc:fileid>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ </d:multistatus>+ XML+ end+ let(:propfind_response_body2) do+ <<~XML+ <?xml version="1.0"?>+ <d:multistatus+ xmlns:d="DAV:"+ xmlns:s="http://sabredav.org/ns"+ xmlns:oc="http://owncloud.org/ns"+ xmlns:nc="http://nextcloud.org/ns">+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/%5bSample%5d%20Project%20Name%20%7c%20Ehuu(#{project1.id})/</d:href>+ <d:propstat>+ <d:prop>+ <oc:fileid>819</oc:fileid>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ </d:multistatus>+ XML+ end+ let(:add_user_to_group_response_body) do+ <<~XML+ <?xml version="1.0"?>+ <ocs>+ <meta>+ <status>ok</status>+ <statuscode>100</statuscode>+ <message>OK</message>+ <totalitems></totalitems>+ <itemsperpage></itemsperpage>+ </meta>+ <data/>+ </ocs>+ XML+ end+ let(:set_permissions_request_body2) do+ <<~XML+ <?xml version="1.0"?>+ <d:propertyupdate xmlns:d="DAV:" xmlns:nc="http://nextcloud.org/ns">+ <d:set>+ <d:prop>+ <nc:acl-list>+ <nc:acl>+ <nc:acl-mapping-type>group</nc:acl-mapping-type>+ <nc:acl-mapping-id>OpenProject</nc:acl-mapping-id>+ <nc:acl-mask>31</nc:acl-mask>+ <nc:acl-permissions>0</nc:acl-permissions>+ </nc:acl>+ <nc:acl>+ <nc:acl-mapping-type>user</nc:acl-mapping-type>+ <nc:acl-mapping-id>OpenProject</nc:acl-mapping-id>+ <nc:acl-mask>31</nc:acl-mask>+ <nc:acl-permissions>31</nc:acl-permissions>+ </nc:acl>+ <nc:acl>+ <nc:acl-mapping-type>user</nc:acl-mapping-type>+ <nc:acl-mapping-id>Obi-Wan</nc:acl-mapping-id>+ <nc:acl-mask>31</nc:acl-mask>+ <nc:acl-permissions>3</nc:acl-permissions>+ </nc:acl>+ </nc:acl-list>+ </d:prop>+ </d:set>+ </d:propertyupdate>+ XML+ end+ let(:set_permissions_response_body2) do+ <<~XML+ <?xml version="1.0"?>+ <d:multistatus+ xmlns:d="DAV:"+ xmlns:s="http://sabredav.org/ns"+ xmlns:oc="http://owncloud.org/ns"+ xmlns:nc="http://nextcloud.org/ns">+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/%5bSample%5d%20Project%20Name%20%7c%20Ehuu(#{project1.id})</d:href>+ <d:propstat>+ <d:prop>+ <nc:acl-list/>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ </d:multistatus>+ XML+ end+ let(:remove_user_from_group_response) do+ <<~XML+ <?xml version="1.0"?>+ <ocs>+ <meta>+ <status>ok</status>+ <statuscode>100</statuscode>+ <message>OK</message>+ <totalitems></totalitems>+ <itemsperpage></itemsperpage>+ </meta>+ <data/>+ </ocs>+ XML+ end+ let(:set_permissions_request_body3) do+ <<~XML+ <?xml version="1.0"?>+ <d:propertyupdate xmlns:d="DAV:" xmlns:nc="http://nextcloud.org/ns">+ <d:set>+ <d:prop>+ <nc:acl-list>+ <nc:acl>+ <nc:acl-mapping-type>group</nc:acl-mapping-type>+ <nc:acl-mapping-id>OpenProject</nc:acl-mapping-id>+ <nc:acl-mask>31</nc:acl-mask>+ <nc:acl-permissions>0</nc:acl-permissions>+ </nc:acl>+ <nc:acl>+ <nc:acl-mapping-type>user</nc:acl-mapping-type>+ <nc:acl-mapping-id>OpenProject</nc:acl-mapping-id>+ <nc:acl-mask>31</nc:acl-mask>+ <nc:acl-permissions>31</nc:acl-permissions>+ </nc:acl>+ </nc:acl-list>+ </d:prop>+ </d:set>+ </d:propertyupdate>+ XML+ end+ let(:set_permissions_response_body3) do+ <<~XML+ <?xml version="1.0"?>+ <d:multistatus+ xmlns:d="DAV:"+ xmlns:s="http://sabredav.org/ns"+ xmlns:oc="http://owncloud.org/ns"+ xmlns:nc="http://nextcloud.org/ns">+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/Lost%20Jedi%20Project%20Folder%20%232</d:href>+ <d:propstat>+ <d:prop>+ <nc:acl-list/>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ </d:multistatus>+ XML+ end+ let(:set_permissions_response_body4) do+ <<~XML+ <?xml version="1.0"?>+ <d:multistatus+ xmlns:d="DAV:"+ xmlns:s="http://sabredav.org/ns"+ xmlns:oc="http://owncloud.org/ns"+ xmlns:nc="http://nextcloud.org/ns">+ <d:response>+ <d:href>/remote.php/dav/files/OpenProject/OpenProject/Jedi%20Project%20Folder%20%7C%7C%7C%28#{project2.id}%29</d:href>+ <d:propstat>+ <d:prop>+ <nc:acl-list/>+ </d:prop>+ <d:status>HTTP/1.1 200 OK</d:status>+ </d:propstat>+ </d:response>+ </d:multistatus>+ XML+ end++ let(:project1) { create(:project, name: '[Sample] Project Name / Ehuu', members: { user => role }) }+ let(:project2) { create(:project, name: 'Jedi Project Folder ///', members: { user => role }) }+ let(:user) { create(:user) }+ let(:role) { create(:role, permissions: %w[read_files write_files]) }++ it 'has a schedule set' do+ expect(described_class.cron_expression).to eq('*/5 * * * *')+ end++ it 'does the job' do+ storage = create(:storage,+ host: 'https://example.com',+ has_managed_project_folders: true,+ password: '12345678')+ projects_storage1 = create(:project_storage,+ project_folder_mode: 'automatic',+ project: project1,+ storage:)++ projects_storage2 = create(:project_storage,+ project_folder_mode: 'automatic',+ project: project2,+ storage:,+ project_folder_id: '123')++ oauth_client = create(:oauth_client, integration: storage)+ create(:oauth_client_token,+ origin_user_id: 'Obi-Wan',+ user:,+ oauth_client:)++ request_stubs = []+ request_stubs << stub_request(:get, "https://example.com/ocs/v1.php/cloud/groups/#{storage.group}")+ .with(+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg=',+ 'OCS-APIRequest' => 'true'+ }+ ).to_return(status: 200, body: group_users_response_body, headers: {})+ request_stubs << stub_request(:proppatch, "https://example.com/remote.php/dav/files/OpenProject/OpenProject")+ .with(+ body: set_permissions_request_body1,+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg='+ }+ )+ .to_return(status: 207, body: set_permissions_response_body1, headers: {})+ request_stubs << stub_request(:propfind, "https://example.com/remote.php/dav/files/OpenProject/OpenProject")+ .with(+ body: propfind_request_body,+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg=',+ 'Depth' => '1'+ }+ )+ .to_return(status: 207, body: propfind_response_body1, headers: {})+ request_stubs << stub_request(+ :mkcol,+ "https://example.com/remote.php/dav/files/OpenProject/OpenProject/%5BSample%5D%20Project%20Name%20%7C%20Ehuu(#{project1.id})"+ ).with(+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg='+ }+ ).to_return(status: 201, body: "", headers: {})+ request_stubs << stub_request(:propfind, "https://example.com/remote.php/dav/files/OpenProject/OpenProject/%5BSample%5D%20Project%20Name%20%7C%20Ehuu(#{project1.id})")+ .with(+ body: propfind_request_body,+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg=',+ 'Depth' => '0'+ }+ )+ .to_return(status: 207, body: propfind_response_body2, headers: {})+ request_stubs << stub_request(:post, "https://example.com/ocs/v1.php/cloud/users/Obi-Wan/groups")+ .with(+ body: "groupid=OpenProject",+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg=',+ 'Ocs-Apirequest' => 'true'+ }+ ).to_return(status: 200, body: add_user_to_group_response_body, headers: {})+ request_stubs << stub_request(:proppatch, "https://example.com/remote.php/dav/files/OpenProject/OpenProject/%5BSample%5D%20Project%20Name%20%7C%20Ehuu(#{project1.id})")+ .with(+ body: set_permissions_request_body2,+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg='+ }+ )+ .to_return(status: 207, body: set_permissions_response_body2, headers: {})+ request_stubs << stub_request(:move, "https://example.com/remote.php/dav/files/OpenProject/OpenProject/Lost%20Jedi%20Project%20Folder%20%233")+ .with(+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg=',+ 'Destination' => "/remote.php/dav/files/OpenProject/OpenProject/Jedi%20Project%20Folder%20%7C%7C%7C%28#{project2.id}%29"+ }+ )+ .to_return(status: 201, body: "", headers: {})+ request_stubs << stub_request(:proppatch, "https://example.com/remote.php/dav/files/OpenProject/OpenProject/Jedi%20Project%20Folder%20%7C%7C%7C%28#{project2.id}%29")+ .with(+ body: set_permissions_request_body2,+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg='+ }+ )+ .to_return(status: 207, body: set_permissions_response_body4, headers: {})+ request_stubs << stub_request(:delete, "https://example.com/ocs/v1.php/cloud/users/Darth%20Maul/groups?groupid=OpenProject")+ .with(+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg=',+ 'Ocs-Apirequest' => 'true'+ }+ )+ .to_return(status: 200, body: remove_user_from_group_response, headers: {})+ request_stubs << stub_request(:proppatch, "https://example.com/remote.php/dav/files/OpenProject/OpenProject/Lost%20Jedi%20Project%20Folder%20%232")+ .with(+ body: set_permissions_request_body3,+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg='+ }+ )+ .to_return(status: 207, body: set_permissions_response_body3, headers: {})++ expect(projects_storage1.project_folder_id).to be_nil+ expect(projects_storage2.project_folder_id).to eq('123')++ described_class.new.perform++ projects_storage1.reload+ projects_storage2.reload+ expect(projects_storage1.project_folder_id).to eq('819')+ expect(projects_storage2.project_folder_id).to eq('123')++ expect(request_stubs).to all have_been_requested+ end+end