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
[#48353] Implement triggers to run background job
Pavel Balashou32782fc12ea7
diff --git a/lib/open_project/mutex.rb b/lib/open_project/mutex.rbindex 8e5b8282ff2..962b95e3d43 100644--- a/lib/open_project/mutex.rb+++ b/lib/open_project/mutex.rb@@ -54,18 +54,19 @@ module OpenProject# attachable journals for the attachment added by themselves. To the user this will look as if one of the actions# deleted the other attachment. The next action, Action 3, will then seem to have readded the attachment,# seemingly removed before.- def with_advisory_lock_transaction(entry, suffix = nil, &)+ def with_advisory_lock_transaction(entry, suffix = nil, options = {}, &)lock_name = "mutex_on_#{entry.class.name}_#{entry.id}"lock_name << "_#{suffix}" if suffixActiveRecord::Base.transaction do- with_advisory_lock(entry.class, lock_name, &)+ with_advisory_lock(entry.class, lock_name, options, &)endend- def with_advisory_lock(resource_class, lock_name)+ def with_advisory_lock(resource_class, lock_name, options = {})debug_log("Attempting to fetched advisory lock", lock_name)- result = resource_class.with_advisory_lock(lock_name, transaction: true) do+ options[:transaction] ||= true+ result = resource_class.with_advisory_lock(lock_name, options) dodebug_log("Fetched advisory lock", lock_name)yieldenddiff --git a/modules/storages/app/models/storages/nextcloud_storage.rb b/modules/storages/app/models/storages/nextcloud_storage.rbindex 7604cf73478..4367cb533fb 100644--- a/modules/storages/app/models/storages/nextcloud_storage.rb+++ b/modules/storages/app/models/storages/nextcloud_storage.rb@@ -36,6 +36,18 @@ class Storages::NextcloudStorage < Storages::Storagealias_method :has_managed_project_folders?, :has_managed_project_folders+ def self.sync_all_group_folders+ # Returns false if lock cannot be acquired, block is not executed then.+ OpenProject::Mutex.with_advisory_lock(self.class, 'sync_all_group_folders', timeout_seconds: 0) do+ where("provider_fields->>'has_managed_project_folders' = 'true'")+ .includes(:oauth_client)+ .each do |storage|+ Storages::GroupFolderPropertiesSyncService.new(storage).call+ end+ true+ end+ end+def groupsuper || "OpenProject"enddiff --git a/modules/storages/app/services/storages/group_folder_properties_sync_service.rb b/modules/storages/app/services/storages/group_folder_properties_sync_service.rbnew file mode 100644index 00000000000..9b2392945a7--- /dev/null+++ b/modules/storages/app/services/storages/group_folder_properties_sync_service.rb@@ -0,0 +1,245 @@+#-- 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 Storages::GroupFolderPropertiesSyncService+ using ::Storages::Peripherals::ServiceResultRefinements++ PERMISSIONS_MAP = {+ read_files: 1,+ write_files: 2,+ create_files: 4,+ delete_files: 8,+ share_files: 16+ }.freeze+ ALL_PERMISSIONS = PERMISSIONS_MAP.values.sum+ NO_PERMISSIONS = 0++ def initialize(storage)+ @storage = storage+ @nextcloud_system_user = storage.username+ @group = storage.group+ @group_folder = storage.group_folder+ @requests = Storages::Peripherals::StorageRequests.new(storage:)+ end++ # rubocop:disable Metrics/AbcSize+ def call+ # we have to flush state to be able to reuse the instace of the class+ @nextcloud_usernames_used_in_openproject = Set.new+ @project_folder_ids_used_in_openproject = Set.new+ @file_ids = nil+ @folders_properties = nil+ @group_users = nil++ set_group_folder_root_permissions++ @storage.projects_storages+ .automatic+ .includes(project: %i[users enabled_modules])+ .each do |project_storage|+ project = project_storage.project+ project_folder_path = project_folder_path(project)+ @project_folder_ids_used_in_openproject << ensure_project_folder(project_storage:, project_folder_path:)++ set_project_folder_permissions(path: project_folder_path, project:)+ end++ add_active_users_to_group+ remove_inactive_users_from_group+ hide_inactive_project_folders+ end+ # rubocop:enable Metrics/AbcSize++ private++ def set_group_folder_root_permissions+ permissions = {+ users: { @nextcloud_system_user.to_sym => ALL_PERMISSIONS },+ groups: { @group.to_sym => PERMISSIONS_MAP[:read_files] }+ }+ @requests+ .set_permissions_command+ .call(path: @group_folder, permissions:)+ .on_failure do |r|+ raise "set_permissions_command(path: #{@group_folder}, permissions: #{permissions}) failed: #{r.inspect}"+ end+ end++ def project_folder_path(project)+ "#{@group_folder}/#{project.name.gsub('/', '|')} (#{project.id})/"+ end++ # rubocop:disable Metrics/AbcSize+ def ensure_project_folder(project_storage:, project_folder_path:)+ project_folder_id = project_storage.project_folder_id+ project_storage.project++ if project_folder_id.present? && file_ids.include?(project_folder_id)+ source = folders_properties.find { |_k, v| v['fileid'] == project_folder_id }.first+ rename_folder(source:, target: project_folder_path) if source != project_folder_path+ else+ create_folder(path: project_folder_path, project_storage:) >> obtain_file_id >> save_file_id+ end+ # local variable is not used due to possible update_columns call+ # then the value inside the local variable will not be updated+ project_storage.project_folder_id+ end+ # rubocop:enable Metrics/AbcSize++ def file_ids+ @file_ids ||= folders_properties.map { |_path, props| props['fileid'] }+ end++ def folders_properties+ @folders_properties ||= @requests+ .propfind_query+ .call(depth: '1', path: @group_folder, props: %w[oc:fileid])+ .on_failure do |r|+ raise "propfind_query(depth: 1, path: #{@group_folder}, props: #{%w[oc:fileid]}) failed: #{r.inspect}"+ end.result+ end++ def rename_folder(source:, target:)+ @requests.rename_file_command.call(source:, target:).on_failure do |r|+ raise "rename_file_command failed(source: #{source} target: #{target}) failed: #{r.inspect}"+ end+ end++ def create_folder(path:, project_storage:)+ @requests.create_folder_command.call(folder_path: path)+ .match(+ on_success: ->(_) { ServiceResult.success(result: [project_storage, path]) },+ on_failure: ->(r) { raise "create_folder_command(folder_path: #{path}) failed: #{r.inspect}, " }+ )+ end++ def save_file_id+ ->((project_storage, file_id)) do+ project_storage.update_columns(project_folder_id: file_id, updated_at: Time.current)+ end+ end++ def obtain_file_id+ ->((project_storage, path)) do+ @requests+ .propfind_query+ .call(depth: '0', path:, props: %w[oc:fileid])+ .match(+ on_success: ->(result) { ServiceResult.success(result: [project_storage, result.dig(path, 'fileid')]) },+ on_failure: ->(_result) { raise "propfind_query failed: #{r}, depth: 0, path: #{path}" }+ )+ 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 |permissions_sum, (permission, allowed)|+ if allowed+ permissions_sum + PERMISSIONS_MAP[permission]+ else+ permissions_sum+ end+ end+ end++ def set_project_folder_permissions(path:, project:)+ permissions = project_folder_permissions(project:)+ @requests.set_permissions_command.call(path:, permissions:).on_failure do |r|+ raise "set_permissions_command path(#{path}, permissions: #{permissions}) failed: #{r.inspect}"+ end+ end++ def group_users+ @group_users ||= @requests.group_users_query.call(group: @group).on_failure do |r|+ raise "group_users_query(group: #{@group}) failed: #{r.inspect}"+ end.result+ end++ def project_folder_permissions(project:)+ OAuthClientToken+ .where(oauth_client: @storage.oauth_client, users: project.users)+ .includes(:user)+ .each_with_object({+ users: { "#{@nextcloud_system_user}": ALL_PERMISSIONS },+ groups: { "#{@group}": NO_PERMISSIONS }+ }) do |token, permissions|+ nextcloud_username = token.origin_user_id+ permissions[:users][nextcloud_username.to_sym] = calculate_permissions(user: token.user, project:)+ @nextcloud_usernames_used_in_openproject << nextcloud_username+ end+ end++ def add_active_users_to_group+ @nextcloud_usernames_used_in_openproject.each do |nextcloud_username|+ if group_users.exclude?(nextcloud_username)+ @requests.add_user_to_group_command.call(user: nextcloud_username).on_failure do |r|+ raise "add_user_to_group_command(user: #{netcloud_username}) failed: #{r.inspect}, "+ end+ end+ end+ end++ def remove_inactive_users_from_group+ (group_users - @nextcloud_usernames_used_in_openproject.to_a - [@nextcloud_system_user]).each do |user|+ remove_user_from_group(user)+ end+ end++ def remove_user_from_group(user)+ @requests+ .remove_user_from_group_command+ .call(user:)+ .on_failure { |r| raise "remove_user_from_group_command(user: #{user}) failed: #{r.inspect}" }+ end++ def hide_inactive_project_folders+ inactive_project_folder_paths.each { |folder| hide_folder(folder) }+ end++ def inactive_project_folder_paths+ folders_properties.except("#{@group_folder}/").each_with_object([]) do |(path, attrs), paths|+ paths.push(path) if @project_folder_ids_used_in_openproject.exclude?(attrs['fileid'])+ end+ end++ def hide_folder(path)+ permissions = {+ users: { "#{@nextcloud_system_user}": ALL_PERMISSIONS },+ groups: { "#{@group}": NO_PERMISSIONS }+ }+ @requests+ .set_permissions_command+ .call(path:, permissions:)+ .on_failure { |r| raise "set_permissions_command(path: #{path}, permissions: #{permissions}) failed: #{r.inspect}" }+ end+enddiff --git a/modules/storages/app/workers/storages/manage_nextcloud_integration_cron_job.rb b/modules/storages/app/workers/storages/manage_nextcloud_integration_cron_job.rbnew file mode 100644index 00000000000..6df63e019e0--- /dev/null+++ b/modules/storages/app/workers/storages/manage_nextcloud_integration_cron_job.rb@@ -0,0 +1,40 @@+#-- 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 Storages::ManageNextcloudIntegrationCronJob < Cron::CronJob+ using ::Storages::Peripherals::ServiceResultRefinements++ queue_with_priority :low++ self.cron_expression = '*/5 * * * *'++ def perform+ result = Storages::NextcloudStorage.sync_all_group_folders+ raise 'Synchronization is being progressed by another process' if result == false+ end+enddiff --git a/modules/storages/app/workers/storages/manage_nextcloud_integration_events_job.rb b/modules/storages/app/workers/storages/manage_nextcloud_integration_events_job.rbnew file mode 100644index 00000000000..6ba3427735d--- /dev/null+++ b/modules/storages/app/workers/storages/manage_nextcloud_integration_events_job.rb@@ -0,0 +1,45 @@+#-- 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 Storages::ManageNextcloudIntegrationEventsJob < ApplicationJob+ def self.debounce+ debounce_time = 20.seconds+ count = Delayed::Job+ .where("handler LIKE ?", "%job_class: #{self}%")+ .where(locked_at: nil)+ .where('run_at <= ?', debounce_time.from_now)+ .delete_all+ Rails.logger.info("deleted: #{count} jobs")+ set(wait: debounce_time).perform_later+ end++ def perform+ result = Storages::NextcloudStorage.sync_all_group_folders+ raise 'Synchronization is being progressed by another process' if result == false+ end+enddiff --git a/modules/storages/app/workers/storages/manage_nextcloud_integration_job.rb b/modules/storages/app/workers/storages/manage_nextcloud_integration_job.rbdeleted file mode 100644index e8c0d93a8b4..00000000000--- a/modules/storages/app/workers/storages/manage_nextcloud_integration_job.rb+++ /dev/null@@ -1,259 +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.-#++--class Storages::ManageNextcloudIntegrationJob < Cron::CronJob- using ::Storages::Peripherals::ServiceResultRefinements-- queue_with_priority :low-- self.cron_expression = '*/5 * * * *'-- def perform- Storages::NextcloudStorage- .where("provider_fields->>'has_managed_project_folders' = 'true'")- .includes(:oauth_client)- .each do |storage|- GroupFolderPropertiesSynchronization.new(storage).call- end- end-- class GroupFolderPropertiesSynchronization- PERMISSIONS_MAP = {- read_files: 1,- write_files: 2,- create_files: 4,- delete_files: 8,- share_files: 16- }.freeze- ALL_PERMISSIONS = PERMISSIONS_MAP.values.sum- NO_PERMISSIONS = 0-- def initialize(storage)- @storage = storage- @nextcloud_system_user = storage.username- @group = storage.group- @group_folder = storage.group_folder- @requests = Storages::Peripherals::StorageRequests.new(storage:)- end-- # rubocop:disable Metrics/AbcSize- def call- # we have to flush state to be able to reuse the instace of the class- @nextcloud_usernames_used_in_openproject = Set.new- @project_folder_ids_used_in_openproject = Set.new- @file_ids = nil- @folders_properties = nil- @group_users = nil-- set_group_folder_root_permissions-- @storage.projects_storages- .automatic- .includes(project: %i[users enabled_modules])- .each do |project_storage|- project = project_storage.project- project_folder_path = project_folder_path(project)- @project_folder_ids_used_in_openproject << ensure_project_folder(project_storage:, project_folder_path:)-- set_project_folder_permissions(path: project_folder_path, project:)- end-- add_active_users_to_group- remove_inactive_users_from_group- hide_inactive_project_folders- end- # rubocop:enable Metrics/AbcSize-- private-- def set_group_folder_root_permissions- permissions = {- users: { @nextcloud_system_user.to_sym => ALL_PERMISSIONS },- groups: { @group.to_sym => PERMISSIONS_MAP[:read_files] }- }- @requests- .set_permissions_command- .call(path: @group_folder, permissions:)- .on_failure do |r|- raise "set_permissions_command(path: #{@group_folder}, permissions: #{permissions}) failed: #{r.inspect}"- end- end-- def project_folder_path(project)- "#{@group_folder}/#{project.name.gsub('/', '|')} (#{project.id})/"- end-- # rubocop:disable Metrics/AbcSize- def ensure_project_folder(project_storage:, project_folder_path:)- project_folder_id = project_storage.project_folder_id- project_storage.project-- if project_folder_id.present? && file_ids.include?(project_folder_id)- source = folders_properties.find { |_k, v| v['fileid'] == project_folder_id }.first- rename_folder(source:, target: project_folder_path) if source != project_folder_path- else- create_folder(path: project_folder_path, project_storage:) >> obtain_file_id >> save_file_id- end- # local variable is not used due to possible update_columns call- # then the value inside the local variable will not be updated- project_storage.project_folder_id- end- # rubocop:enable Metrics/AbcSize-- def file_ids- @file_ids ||= folders_properties.map { |_path, props| props['fileid'] }- end-- def folders_properties- @folders_properties ||= @requests- .propfind_query- .call(depth: '1', path: @group_folder, props: %w[oc:fileid])- .on_failure do |r|- raise "propfind_query(depth: 1, path: #{@group_folder}, props: #{%w[oc:fileid]}) failed: #{r.inspect}"- end.result- end-- def rename_folder(source:, target:)- @requests.rename_file_command.call(source:, target:).on_failure do |r|- raise "rename_file_command failed(source: #{source} target: #{target}) failed: #{r.inspect}"- end- end-- def create_folder(path:, project_storage:)- @requests.create_folder_command.call(folder_path: path)- .match(- on_success: ->(_) { ServiceResult.success(result: [project_storage, path]) },- on_failure: ->(r) { raise "create_folder_command(folder_path: #{target}) failed: #{r.inspect}, " }- )- end-- def save_file_id- ->((project_storage, file_id)) do- project_storage.update_columns(project_folder_id: file_id, updated_at: Time.current)- end- end-- def obtain_file_id- ->((project_storage, path)) do- @requests- .propfind_query- .call(depth: '0', path:, props: %w[oc:fileid])- .match(- on_success: ->(result) { ServiceResult.success(result: [project_storage, result.dig(path, 'fileid')]) },- on_failure: ->(_result) { raise "propfind_query failed: #{r}, depth: 0, path: #{path}" }- )- 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 |permissions_sum, (permission, allowed)|- if allowed- permissions_sum + PERMISSIONS_MAP[permission]- else- permissions_sum- end- end- end-- def set_project_folder_permissions(path:, project:)- @requests.set_permissions_command.call(path:, permissions: project_folder_permissions(project:)).on_failure do |r|- raise "set_permissions_command path(#{target}, permissions: #{permissions}) failed: #{r.inspect}"- end- end-- def group_users- @group_users ||= @requests.group_users_query.call(group: @group).on_failure do |r|- raise "group_users_query(group: #{@group}) failed: #{r.inspect}"- end.result- end-- def project_folder_permissions(project:)- OAuthClientToken- .where(oauth_client: @storage.oauth_client, users: project.users)- .includes(:user)- .each_with_object({- users: { "#{@nextcloud_system_user}": ALL_PERMISSIONS },- groups: { "#{@group}": NO_PERMISSIONS }- }) do |token, permissions|- nextcloud_username = token.origin_user_id- permissions[:users][nextcloud_username.to_sym] = calculate_permissions(user: token.user, project:)- @nextcloud_usernames_used_in_openproject << nextcloud_username- end- end-- def add_active_users_to_group- @nextcloud_usernames_used_in_openproject.each do |nextcloud_username|- if group_users.exclude?(nextcloud_username)- @requests.add_user_to_group_command.call(user: nextcloud_username).on_failure do |r|- raise "add_user_to_group_command(user: #{netcloud_username}) failed: #{r.inspect}, "- end- end- end- end-- def remove_inactive_users_from_group- (group_users - @nextcloud_usernames_used_in_openproject.to_a - [@nextcloud_system_user]).each do |user|- remove_user_from_group(user)- end- end-- def remove_user_from_group(user)- @requests- .remove_user_from_group_command- .call(user:)- .on_failure { |r| raise "remove_user_from_group_command(user: #{user}) failed: #{r.inspect}" }- end-- def hide_inactive_project_folders- inactive_project_folder_paths.each { |folder| hide_folder(folder) }- end-- def inactive_project_folder_paths- folders_properties.except("#{@group_folder}/").each_with_object([]) do |(path, attrs), paths|- paths.push(path) if @project_folder_ids_used_in_openproject.exclude?(attrs['fileid'])- end- end-- def hide_folder(path)- permissions = {- users: { "#{@nextcloud_system_user}": ALL_PERMISSIONS },- groups: { "#{@group}": NO_PERMISSIONS }- }- @requests- .set_permissions_command- .call(path:, permissions:)- .on_failure { |r| raise "set_permissions_command(path: #{path}, permissions: #{permissions}) failed: #{r.inspect}" }- end- end-enddiff --git a/modules/storages/lib/open_project/storages/engine.rb b/modules/storages/lib/open_project/storages/engine.rbindex fc61a44ee02..48df2396194 100644--- a/modules/storages/lib/open_project/storages/engine.rb+++ b/modules/storages/lib/open_project/storages/engine.rb@@ -46,6 +46,25 @@ module OpenProject::StoragesOpenProject::FeatureDecisions.add :managed_project_foldersend+ initializer 'openproject_storages.event_subscriptions' do+ Rails.application.config.after_initialize do+ if OpenProject::FeatureDecisions.managed_project_folders_active?+ [+ OpenProject::Events::MEMBER_CREATED,+ OpenProject::Events::MEMBER_UPDATED,+ OpenProject::Events::MEMBER_DESTROYED,+ OpenProject::Events::PROJECT_CREATED,+ OpenProject::Events::PROJECT_UPDATED,+ OpenProject::Events::PROJECT_RENAMED+ ].each do |event|+ OpenProject::Notifications.subscribe(event) do |_payload|+ ManageNextcloudIntegrationEventsJob.debounce+ end+ end+ end+ end+ end+# For documentation see the definition of register in "ActsAsOpEngine"# This corresponds to the openproject-storage.gemspec# Pass a block to the plugin (for defining permissions, menu items and the like)@@ -230,7 +249,7 @@ module OpenProject::StoragesStorages::CleanupUncontaineredFileLinksJob].tap do |cron_jobs|if OpenProject::FeatureDecisions.managed_project_folders_active?- cron_jobs << Storages::ManageNextcloudIntegrationJob+ cron_jobs << Storages::ManageNextcloudIntegrationCronJobendendenddiff --git a/modules/storages/spec/models/nextcloud_storage_spec.rb b/modules/storages/spec/models/nextcloud_storage_spec.rbnew file mode 100644index 00000000000..67c89b8d973--- /dev/null+++ b/modules/storages/spec/models/nextcloud_storage_spec.rb@@ -0,0 +1,63 @@+#-- 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_relative '../spec_helper'++RSpec.describe Storages::NextcloudStorage do+ describe '.sync_all_group_folders' do+ subject { described_class.sync_all_group_folders }++ context 'when lock is free' do+ it 'responds with true' do+ expect(subject).to be(true)+ end++ it 'calls GroupFolderPropertiesSyncService for each appropriate storage' do+ storage1 = create(:storage, has_managed_project_folders: true)+ storage2 = create(:storage, has_managed_project_folders: false)+ allow(Storages::GroupFolderPropertiesSyncService).to receive(:new).and_call_original+ # rubocop:disable RSpec/AnyInstance+ allow_any_instance_of(Storages::GroupFolderPropertiesSyncService).to receive(:call).and_return(nil)+ # rubocop:enable RSpec/AnyInstance++ expect(subject).to be(true)+ expect(Storages::GroupFolderPropertiesSyncService).to have_received(:new).with(storage1).once+ expect(Storages::GroupFolderPropertiesSyncService).not_to have_received(:new).with(storage2)+ end+ end++ context 'when lock is unfree' do+ it 'responds with false' do+ allow(ApplicationRecord).to receive(:with_advisory_lock).and_return(false)++ expect(subject).to be(false)+ expect(ApplicationRecord).to have_received(:with_advisory_lock).with('nextcloud_storages_sync', timeout_seconds: 0).once+ end+ end+ end+enddiff --git a/modules/storages/spec/workers/storages/manage_nextcloud_integration_job_spec.rb b/modules/storages/spec/services/storages/group_folder_properties_sync_service_spec.rbsimilarity index 64%rename from modules/storages/spec/workers/storages/manage_nextcloud_integration_job_spec.rbrename to modules/storages/spec/services/storages/group_folder_properties_sync_service_spec.rbindex 46dd5649c27..780308ae093 100644--- a/modules/storages/spec/workers/storages/manage_nextcloud_integration_job_spec.rb+++ b/modules/storages/spec/services/storages/group_folder_properties_sync_service_spec.rb@@ -28,7 +28,7 @@require 'spec_helper'-RSpec.describe Storages::ManageNextcloudIntegrationJob, type: :job, webmock: true do+RSpec.describe Storages::GroupFolderPropertiesSyncService, webmock: true do# rubocop:disable RSpec/IndexedLetlet(:group_users_response_body) do<<~XML@@ -50,26 +50,6 @@ RSpec.describe Storages::ManageNextcloudIntegrationJob, type: :job, webmock: tru</ocs>XMLend- 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- endlet(:set_permissions_request_body1) do<<~XML<?xml version="1.0"?>@@ -95,6 +75,26 @@ RSpec.describe Storages::ManageNextcloudIntegrationJob, type: :job, webmock: tru</d:propertyupdate>XMLend+ 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+ endlet(:propfind_request_body) do<<~XML<?xml version="1.0"?>@@ -316,146 +316,142 @@ RSpec.describe Storages::ManageNextcloudIntegrationJob, type: :job, webmock: trulet(:role) { create(:role, permissions: %w[read_files write_files]) }# rubocop:enable RSpec/IndexedLet- it 'has a schedule set' do- expect(described_class.cron_expression).to eq('*/5 * * * *')- end-# rubocop:disable RSpec/ExampleLength- 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:)+ describe '#call' do+ it 'sets properties for project folders' 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')+ 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:)+ 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(+ 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%20(#{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%20(#{project1.id})"+ ).with(+ body: propfind_request_body,headers: {'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg=',- 'OCS-APIRequest' => 'true'+ '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%20(#{project1.id})"+ ).with(+ body: set_permissions_request_body2,+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg='}- ).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%20(#{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%20(#{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",+ ).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=',- 'Ocs-Apirequest' => 'true'+ 'Destination' => "/remote.php/dav/files/OpenProject/OpenProject/" \+ "Jedi%20Project%20Folder%20%7C%7C%7C%20%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%20%28#{project2.id}%29"+ ).with(+ body: set_permissions_request_body2,+ headers: {+ 'Authorization' => 'Basic T3BlblByb2plY3Q6MTIzNDU2Nzg='}- ).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%20(#{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%20%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%20%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(+ ).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: {})+ 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')+ expect(projects_storage1.project_folder_id).to be_nil+ expect(projects_storage2.project_folder_id).to eq('123')- described_class.new.perform+ described_class.new(storage).call- expect(request_stubs).to all have_been_requested- 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+ projects_storage1.reload+ projects_storage2.reload+ expect(projects_storage1.project_folder_id).to eq('819')+ expect(projects_storage2.project_folder_id).to eq('123')+ end+ # rubocop:enable RSpec/ExampleLengthend- # rubocop:enable RSpec/ExampleLengthenddiff --git a/modules/storages/spec/workers/manage_nextcloud_integration_cron_job_spec.rb b/modules/storages/spec/workers/manage_nextcloud_integration_cron_job_spec.rbnew file mode 100644index 00000000000..6b53795364e--- /dev/null+++ b/modules/storages/spec/workers/manage_nextcloud_integration_cron_job_spec.rb@@ -0,0 +1,49 @@+#-- 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'++RSpec.describe ManageNextcloudIntegrationCronJob, type: :job do+ it 'has a schedule set' do+ expect(described_class.cron_expression).to eq('*/5 * * * *')+ end++ describe '#perform' do+ subject { described_class.new.perform }++ it 'works out silently' do+ allow(Storages::NextcloudStorage).to receive(:sync_all_group_folders).and_return(true)+ subject+ end++ it 'fails itself when sync has been started by another process' do+ allow(Storages::NextcloudStorage).to receive(:sync_all_group_folders).and_return(false)+ expect { subject }.to raise_error('Synchronization is being progressed by another process')+ end+ end+enddiff --git a/modules/storages/spec/workers/manage_nextcloud_integration_events_job_spec.rb b/modules/storages/spec/workers/manage_nextcloud_integration_events_job_spec.rbnew file mode 100644index 00000000000..c1d22b3d513--- /dev/null+++ b/modules/storages/spec/workers/manage_nextcloud_integration_events_job_spec.rb@@ -0,0 +1,77 @@+#-- 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'++RSpec.describe ManageNextcloudIntegrationEventsJob, type: :job do+ describe '.debounce' do+ it 'debounces job with 1 minute timeframe' do+ ActiveJob::Base.disable_test_adapter++ other_handler = ManageNextcloudIntegrationCronJob.perform_later.provider_job_id+ same_handler_within_timeframe1 = described_class.set(wait: 10.seconds).perform_later.provider_job_id+ same_handler_within_timeframe2 = described_class.set(wait: 30.seconds).perform_later.provider_job_id+ same_handler_within_timeframe3 = described_class.set(wait: 50.seconds).perform_later.provider_job_id+ same_handler_out_of_timeframe = described_class.set(wait: 5.minutes).perform_later.provider_job_id+ same_handler_within_timeframe_in_progress = described_class.set(wait: 55.seconds).perform_later.tap do |job|+ # simulate in progress state+ Delayed::Job.where(id: job.provider_job_id).update_all(locked_at: Time.current, locked_by: "test_process #{Process.pid}")+ end.provider_job_id++ expect(Delayed::Job.count).to eq(6)++ described_class.debounce++ expect(Delayed::Job.count).to eq(4)+ expect(Delayed::Job.pluck(:id)).to include(other_handler, same_handler_out_of_timeframe,+ same_handler_within_timeframe_in_progress)+ expect(Delayed::Job.pluck(:id)).not_to include(same_handler_within_timeframe1, same_handler_within_timeframe2,+ same_handler_within_timeframe3)+ expect(+ Delayed::Job+ .where("handler LIKE ?", "%job_class: #{described_class}%")+ .last+ .run_at+ ).to be_within(3.seconds).of(1.minute.from_now)+ end+ end++ describe '#perform' do+ subject { described_class.new.perform }++ it 'works out silently' do+ allow(Storages::NextcloudStorage).to receive(:sync_all_group_folders).and_return(true)+ subject+ end++ it 'fails itself when sync has been started by another process' do+ allow(Storages::NextcloudStorage).to receive(:sync_all_group_folders).and_return(false)+ expect { subject }.to raise_error('Synchronization is being progressed by another process')+ end+ end+end