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
Refactored FileLinkSyncService to use FilesInfoQuery
Andreas Pfohl800708035edd
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/files_info_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/files_info_query.rbindex f961270f943..8ab27bd5c35 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/files_info_query.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/files_info_query.rb@@ -102,7 +102,7 @@ module Storages::Peripherals::StorageInteraction::Nextcloudresult: response_object.ocs.data.to_h.map do |_, value|::Storages::StorageFileInfo.new(value.status,- value.status_code,+ value.statuscode,value.id,value.name,Time.zone.at(value.mtime),diff --git a/modules/storages/app/services/storages/file_link_sync_service.rb b/modules/storages/app/services/storages/file_link_sync_service.rbindex 674253ee851..ee2626f346a 100644--- a/modules/storages/app/services/storages/file_link_sync_service.rb+++ b/modules/storages/app/services/storages/file_link_sync_service.rb@@ -26,205 +26,80 @@# See COPYRIGHT and LICENSE files for more details.#++-# Handle synchronization of FileLinks with external data store such as Storagesclass Storages::FileLinkSyncService- FILESINFO_URL_PATH = "/ocs/v1.php/apps/integration_openproject/filesinfo".freeze+ using Storages::Peripherals::ServiceResultRefinementsdef initialize(user:)@user = user- @service_result = ServiceResult.success(result: [])enddef call(file_links)- @file_links = file_links- storage_file_link_hash = @file_links.group_by(&:storage_id)- storage_file_link_hash.each do |storage_id, storage_file_links|- # Add new types of storages here. We currently only support Nextcloud- sync_nextcloud(storage_id, storage_file_links)+ file_links+ .group_by(&:storage_id)+ .map { |storage_id, storage_file_links| sync_nextcloud(storage_id, storage_file_links) }+ .reduce(ServiceResult.success(result: [])) do |state, sync_result|+ state >> ->(state_result) do+ sync_result.match(+ on_success: ->(sr) { ServiceResult.success(result: state_result + sr) },+ on_failure: ->(_) { ServiceResult.success(result: state_result) }+ )+ endend-- @service_resultendprivate- # Get the OAuthClientToken that will authenticate us against Nextcloud- def get_connection_manager(storage_id)- oauth_client = OAuthClient.find_by(integration_id: storage_id)- ::OAuthClients::ConnectionManager.new(user: @user, oauth_client:)+ def sync_nextcloud(storage_id, file_links)+ ::Storages::Peripherals::StorageRequests+ .new(storage: ::Storages::Storage.find(storage_id))+ .files_info_query+ .call(user: @user, file_ids: file_links.map(&:origin_id))+ .map(&to_hash) >> set_file_link_permissions(file_links)end- def get_oauth_client_token(connection_manager)- access_token_service_result = connection_manager.get_access_token # No scope for Nextcloud...- if access_token_service_result.failure?- return nil- end-- access_token_service_result.result+ def to_hash+ ->(file_infos) { file_infos.index_by { |file_info| file_info.id.to_s }.to_h }end- # Sync a Nextcloud storage- def sync_nextcloud(storage_id, file_links)- connection_manager = get_connection_manager(storage_id)- oauth_client_token = get_oauth_client_token(connection_manager)- if oauth_client_token.nil?- set_error_for_file_links(file_links)- return- end-- nextcloud_request_result = connection_manager.request_with_token_refresh(oauth_client_token) do |token|- response = request_files_info(token, file_links.map(&:origin_id))- Rails.logger.debug { "Got nextcloud filesinfo response: #{response.inspect}" }- # Parse HTTP response an return a ServiceResult with:- # success: result= Hash with Nextcloud filesinfo (name of endpoint) data- # failure: result= :error or :not_authorized- parse_files_info_response(response)- end- # Pass errors from Nextcloud into service result- @service_result.merge!(nextcloud_request_result)+ def set_file_link_permissions(file_links)+ ->(file_infos) do+ resulting_file_links = []- if nextcloud_request_result.failure?- set_error_for_file_links(file_links)- return- end+ file_links.each do |file_link|+ file_info = file_infos[file_link.origin_id]- set_file_link_permissions(file_links, nextcloud_request_result.result)- end+ case file_info.status_code+ when 200+ next if file_info.trashed- def set_file_link_permissions(file_links, parsed_response)- file_links.each do |file_link|- origin_file_info_hash = parsed_response[file_link.origin_id]+ update_file_link(file_link, file_info)- case origin_file_info_hash['statuscode']- when 200 # Successfully found - update infos- next if origin_file_info_hash['trashed'] # moved to trash in Nextcloud+ file_link.origin_permission = :view+ when 403+ file_link.origin_permission = :not_allowed+ when 404+ file_link.destroy+ next+ else+ file_link.origin_permission = :error+ end- sync_single_file(file_link, origin_file_info_hash)- file_link.origin_permission = :view- when 403 # Forbidden - file from other user- file_link.origin_permission = :not_allowed- when 404 # Not found - permanently deleted in Nextcloud- file_link.destroy- next # don't save and don't add file_link to result!- else- file_link.origin_permission = :error+ resulting_file_links << file_link+ file_link.saveend- @service_result.result << file_link- file_link.save # Only saves to database if some field has actually changed.+ ServiceResult.success(result: resulting_file_links)endend- # Write the updated information from Nextcloud to a single file- # @param storage Storage of the file- # @param origin_file_id Nextcloud ID of the file- # @param origin_file_info_hash Hash with updated information from Nextcloud- # "24" => {- # "id" : 24, # origin_file_id- # "ctime" : 0, # Linux epoch file creation +overwrite- # "mtime" : 1655301278, # Linux epoch file modification +overwrite- # "mimetype" : "application/pdf", # +overwrite- # "name" : "Nextcloud Manual.pdf", # "Canonical" name, could changed by owner +overwrite- # "owner_id" : "admin", # ID at Nextcloud side +overwrite- # "owner_name" : "admin", # Name at Nextcloud side +overwrite- # "size" : 12706214, # Not used yet in OpenProject +overwrite- # "status" : "OK", # Not used yet- # "statuscode" : 200, # Not used yet- # "trashed" : false # Exclude trashed files from result array of FileLinks- # }- # In case of permission errors (depending on the current user) we get:- # "24" => { "status" => "Forbidden", "statuscode" => 403 }- # In case of completely deleted file or other errors we might also get:- # "24" = { "status" => "Not Found", "statuscode" => 404 }- # rubocop:disable Metrics/AbcSize- def sync_single_file(file_link, origin_file_info_hash)- file_link.origin_mime_type = origin_file_info_hash["mimetype"]- file_link.origin_created_by_name = origin_file_info_hash["owner_name"]- file_link.origin_last_modified_by_name = origin_file_info_hash["modifier_name"]- file_link.origin_name = origin_file_info_hash["name"]- file_link.origin_created_at = Time.zone.at(origin_file_info_hash["ctime"])- file_link.origin_updated_at = Time.zone.at(origin_file_info_hash["mtime"])+ def update_file_link(file_link, file_info)+ file_link.origin_mime_type = file_info.mime_type+ file_link.origin_created_by_name = file_info.owner_name+ file_link.origin_last_modified_by_name = file_info.last_modified_by_name+ file_link.origin_name = file_info.name+ file_link.origin_created_at = file_info.created_at+ file_link.origin_updated_at = file_info.last_modified_atfile_linkend-- # rubocop:enable Metrics/AbcSize-- def set_error_for_file_links(storage_file_links)- @service_result.result += storage_file_links.each { |file_link| file_link.origin_permission = :error }- @service_result.success = false- end-- # Check the Nextcloud status of a list of files:- # The endpoint returns "canonical" infos per file. Canonical means that the attributes are the same- # as the owner sees them and not the current user. If it was the current user the file name could be- # different for that user as a shared file can be renamed.- # @param file_ids An array of Nextcloud IDs of files to check- # @return A HTTP response or an Exception object- #- # curl -H "Accept: application/json" -H "Content-Type:application/json" -H "OCS-APIRequest: true"- # -u USER:PASSWD http://my.nc.org/ocs/v1.php/apps/integration_openproject/filesinfo- # -X POST -d '{"fileIds":[FILE_ID_1,FILE_ID_2,...]}'- def request_files_info(token, file_ids)- host = token.oauth_client.integration.host- uri = URI.parse(File.join(host, FILESINFO_URL_PATH))- request = build_files_info_request(uri, token, file_ids)- opts = request_file_info_options.merge({ use_ssl: uri.scheme == 'https' })-- begin- Net::HTTP.start(uri.hostname, uri.port, opts) do |http|- http.request(request)- end- rescue StandardError => e- e- end- end-- # HTTP Request options: Keep the request short for the sake of the front-end- def request_file_info_options- {- max_retries: 0,- open_timeout: 5, # seconds- read_timeout: 3 # seconds- }- end-- def build_files_info_request(uri, token, file_ids)- request = Net::HTTP::Post.new(uri)- request.body = { fileIds: file_ids }.to_json- {- 'Content-Type': 'application/json',- 'OCS-APIRequest': 'true',- Accept: 'application/json',- Authorization: "Bearer #{token.access_token}"- }.each { |header, value| request[header] = value }-- request- end-- # Takes a response from querying Nextcloud file IDS (an Exception or a HTTP::Response),- # parses the returned JSON and- # @returns ServiceResult containing data in result and success=true,- # or success=false with result=:error or result=:not_authorized.- def parse_files_info_response(response)- return ServiceResult.failure(result: :error) if files_info_response_error?(response)- return ServiceResult.failure(result: :not_authorized) if ["401", "403"].include?(response.code)- return ServiceResult.failure(result: :error) unless response.code == "200"-- begin- response_hash = JSON.parse(response.body).dig('ocs', 'data')- rescue JSON::ParserError => e- return ServiceResult.failure(result: :error)- .errors.add(:base, "JSON parser error: #{e.message}")- end-- ServiceResult.success(result: response_hash)- end-- def files_info_response_error?(response)- response.nil? ||- response.is_a?(StandardError) ||- !response.key?('content-type') || # Reply without content-type can't be valid.- response['content-type'].split(';').first.strip.downcase != 'application/json'- endend