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
[37866] Add attachment_created event and webhook (#9418)
Oliver Güntherd2ce834e23c1
diff --git a/app/models/attachment.rb b/app/models/attachment.rbindex ac8ad1a631e..15f32c7810e 100644--- a/app/models/attachment.rb+++ b/app/models/attachment.rb@@ -175,7 +175,9 @@ class Attachment < ApplicationRecordenddef set_content_type(file)- self.content_type = self.class.content_type_for(file.path) if content_type.blank?+ return if content_type.present?++ self.content_type = file.try(:content_type) || self.class.content_type_for(file.path)enddef set_digest(file)diff --git a/app/models/mail_handler.rb b/app/models/mail_handler.rbindex 0ebbe8999e8..d421d6cc1fc 100644--- a/app/models/mail_handler.rb+++ b/app/models/mail_handler.rb@@ -254,34 +254,27 @@ class MailHandler < ActionMailer::Baseendend- def add_attachments(obj)- create_attachments_from_mail(obj)- .each do |attachment|- obj.attachments << attachment- end- end-- def create_attachments_from_mail(container = nil)+ def add_attachments(container)return [] unless email.attachments&.present?.attachments.reject { |attachment| ignored_filename?(attachment.filename) }- .map do |attachment|- file = OpenProject::Files.create_uploaded_file(- name: attachment.filename,- content_type: attachment.mime_type,- content: attachment.decoded,- binary: true- )+ .map { |attachment| create_attachment(attachment, container) }+ .compact+ end- Attachment.create(- container: container,- file: file,- author: user,- content_type: attachment.mime_type- )- end+ def create_attachment(attachment, container)+ file = OpenProject::Files.create_uploaded_file(+ name: attachment.filename,+ content_type: attachment.mime_type,+ content: attachment.decoded,+ binary: true+ )++ ::Attachments::CreateService+ .new(container, author: user)+ .call(uploaded_file: file, description: nil)end# Adds To and Cc as watchers of the given object if the sender has the@@ -552,7 +545,7 @@ class MailHandler < ActionMailer::Basedef update_work_package(work_package)attributes = collect_wp_attributes_from_email_on_update(work_package)- attributes[:attachment_ids] = work_package.attachment_ids + create_attachments_from_mail.map(&:id)+ attributes[:attachment_ids] = work_package.attachment_ids + add_attachments(work_package).map(&:id)service_call = WorkPackages::UpdateService.new(user: user,diff --git a/app/services/attachments/create_service.rb b/app/services/attachments/create_service.rbindex 806d8f1d273..0671dc65a22 100644--- a/app/services/attachments/create_service.rb+++ b/app/services/attachments/create_service.rb@@ -42,8 +42,15 @@ class Attachments::CreateService## An ActiveRecord::RecordInvalid error is raised if any record can't be saved.def call(uploaded_file:, description:)+ create_attachment(uploaded_file, description)+ .tap(&method(:created_event))+ end++ private++ def create_attachment(uploaded_file, description)if container.nil?- create_attachment(uploaded_file, description)+ save_attachment(uploaded_file, description)elsif container.class.journaled?create_journalized(uploaded_file, description)else@@ -51,11 +58,9 @@ class Attachments::CreateServiceendend- private-def create_journalized(uploaded_file, description)OpenProject::Mutex.with_advisory_lock_transaction(container) do- create_attachment(uploaded_file, description).tap do+ save_attachment(uploaded_file, description).tap do# Get the latest attachments to ensure having them all for journalization.# We just created an attachment and a different worker might have added attachments# in the meantime, e.g when bulk uploading.@@ -67,12 +72,12 @@ class Attachments::CreateServiceenddef create_unjournalized(uploaded_file, description)- create_attachment(uploaded_file, description).tap do+ save_attachment(uploaded_file, description).tap dotouch(container)endend- def create_attachment(uploaded_file, description)+ def save_attachment(uploaded_file, description)attachment = Attachment.new(file: uploaded_file,container: container,description: description,@@ -83,6 +88,16 @@ class Attachments::CreateServiceenddef build_attachment(uploaded_file, description)- container.attachments.build(file: uploaded_file, description: description, author: author)+ container.attachments.build(file: uploaded_file,+ description: description,+ content_type: uploaded_file.content_type,+ author: author)+ end++ def created_event(attachment)+ OpenProject::Notifications.send(+ OpenProject::Events::ATTACHMENT_CREATED,+ attachment: attachment+ )endenddiff --git a/lib/open_project/events.rb b/lib/open_project/events.rbindex 732373c6ba4..29aed7ee3cb 100644--- a/lib/open_project/events.rb+++ b/lib/open_project/events.rb@@ -40,6 +40,8 @@ module OpenProjectAGGREGATED_WORK_PACKAGE_JOURNAL_READY = "aggregated_work_package_journal_ready".freezeAGGREGATED_WIKI_JOURNAL_READY = "aggregated_wiki_journal_ready".freeze+ ATTACHMENT_CREATED = 'attachment_created'.freeze+JOURNAL_CREATED = 'journal_created'.freezeMEMBER_CREATED = 'member_created'.freezediff --git a/modules/bim/app/controllers/bim/bcf/issues_controller.rb b/modules/bim/app/controllers/bim/bcf/issues_controller.rbindex 9ed76963e8c..d8bedcce891 100644--- a/modules/bim/app/controllers/bim/bcf/issues_controller.rb+++ b/modules/bim/app/controllers/bim/bcf/issues_controller.rb@@ -204,9 +204,7 @@ module Bimenddef persist_file- @bcf_attachment = Attachment.create!(file: params[:bcf_file],- description: params[:bcf_file].original_filename,- author: current_user)+ @bcf_attachment = create_attachment@bcf_xml_file = File.new(@bcf_attachment.local_path)session[:bcf_file_id] = @bcf_attachment.idrescue StandardError => e@@ -214,6 +212,12 @@ module Bimredirect_to action: :uploadend+ def create_attachment+ Attachments::CreateService+ .new(nil, author: current_user)+ .call(uploaded_file: params[:bcf_file], description: params[:bcf_file].original_filename)+ end+def check_file_parampath = params[:bcf_file]&.pathunless path && File.readable?(path)diff --git a/modules/webhooks/app/workers/attachment_webhook_job.rb b/modules/webhooks/app/workers/attachment_webhook_job.rbnew file mode 100644index 00000000000..5715a9dc387--- /dev/null+++ b/modules/webhooks/app/workers/attachment_webhook_job.rb@@ -0,0 +1,49 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++class AttachmentWebhookJob < RepresentedWebhookJob+ def payload_key+ :attachment+ end++ def accepted_in_project?+ project = resource.container.try(:project)+ return true if project.nil?++ webhook.enabled_for_project?(project.id)+ end++ def payload_representer+ User.system.run_given do |user|+ ::API::V3::Attachments::AttachmentRepresenter+ .create(resource, current_user: user, embed_links: true)+ end+ end+enddiff --git a/modules/webhooks/lib/open_project/webhooks/event_resources.rb b/modules/webhooks/lib/open_project/webhooks/event_resources.rbindex 7aa065f3585..705b8d585bb 100644--- a/modules/webhooks/lib/open_project/webhooks/event_resources.rb+++ b/modules/webhooks/lib/open_project/webhooks/event_resources.rb@@ -33,7 +33,7 @@ module OpenProject::Webhooksenddef resources- %i(project work_package time_entry)+ %i(project work_package time_entry attachment)endendenddiff --git a/modules/webhooks/lib/open_project/webhooks/event_resources/attachment.rb b/modules/webhooks/lib/open_project/webhooks/event_resources/attachment.rbnew file mode 100644index 00000000000..cde2ea91e38--- /dev/null+++ b/modules/webhooks/lib/open_project/webhooks/event_resources/attachment.rb@@ -0,0 +1,32 @@+require_relative 'base'++module OpenProject::Webhooks::EventResources+ class Attachment < Base+ class << self+ def notification_names+ [+ OpenProject::Events::ATTACHMENT_CREATED+ ]+ end++ def available_actions+ %i(created)+ end++ def resource_name+ I18n.t :'attributes.attachments'+ end++ protected++ def handle_notification(payload, event_name)+ action = event_name.split('_').last+ event_name = prefixed_event_name(action)++ active_webhooks.with_event_name(event_name).pluck(:id).each do |id|+ AttachmentWebhookJob.perform_later(id, payload[:attachment], event_name)+ end+ end+ end+ end+enddiff --git a/modules/webhooks/spec/workers/attachment_webhook_job_spec.rb b/modules/webhooks/spec/workers/attachment_webhook_job_spec.rbnew file mode 100644index 00000000000..e001898c67f--- /dev/null+++ b/modules/webhooks/spec/workers/attachment_webhook_job_spec.rb@@ -0,0 +1,140 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++require 'spec_helper'++describe AttachmentWebhookJob, type: :job, webmock: true do+ shared_let(:user) { FactoryBot.create :admin }+ shared_let(:request_url) { "http://example.net/test/42" }+ shared_let(:project) { FactoryBot.create :project, name: 'Foo Bar' }+ shared_let(:container) { FactoryBot.create :work_package, project: project }+ shared_let(:attachment) { FactoryBot.create :attachment, container: container }+ shared_let(:webhook) { FactoryBot.create :webhook, all_projects: true, url: request_url, secret: nil }+ let(:event) { "attachment:created" }+ let(:job) { described_class.perform_now(webhook.id, attachment, event) }+ let(:stubbed_url) { request_url }++ let(:request_headers) do+ { content_type: "application/json", accept: "application/json" }+ end++ let(:response_code) { 200 }+ let(:response_body) { "hook called" }+ let(:response_headers) do+ { content_type: "text/plain", x_spec: "foobar" }+ end++ let(:stub) do+ stub_request(:post, stubbed_url.sub("http://", ""))+ .with(+ body: hash_including(+ "action" => event,+ "attachment" => hash_including(+ "_type" => "Attachment",+ 'id' => attachment.id+ )+ ),+ headers: request_headers+ )+ .to_return(+ status: response_code,+ body: response_body,+ headers: response_headers+ )+ end++ subject do+ job+ rescue StandardError+ # ignoring it as it's expected to throw exceptions in certain scenarios+ nil+ end++ before do+ allow(::Webhooks::Webhook).to receive(:find).with(webhook.id).and_return(webhook)+ login_as user+ stub+ end++ describe "attachment webhook call" do+ it 'requests with all projects' do+ allow(webhook)+ .to receive(:enabled_for_project?).with(project.id)+ .and_call_original++ subject+ expect(stub).to have_been_requested+ end++ it 'does not request when project does not match unless create case' do+ allow(webhook)+ .to receive(:enabled_for_project?).with(project.id)+ .and_return(false)++ subject+ expect(stub).not_to have_been_requested+ end++ context 'with uncontainered' do+ shared_let(:attachment) { FactoryBot.create :attachment, container: nil }++ it 'does requests even if project nil' do+ allow(webhook)+ .to receive(:enabled_for_project?).with(project.id)+ .and_return(false)++ subject+ expect(stub).to have_been_requested+ end+ end++ describe 'successful flow' do+ before do+ subject+ end++ it "calls the webhook url" do+ expect(stub).to have_been_requested+ end++ it "creates a log for the call" do+ log = Webhooks::Log.last++ expect(log.webhook).to eq webhook+ expect(log.url).to eq webhook.url+ expect(log.event_name).to eq event+ expect(log.request_headers).to eq request_headers+ expect(log.response_code).to eq response_code+ expect(log.response_body).to eq response_body+ expect(log.response_headers).to eq response_headers+ end+ end+ end+enddiff --git a/modules/webhooks/spec/workers/project_webhook_job.rb b/modules/webhooks/spec/workers/project_webhook_job_spec.rbsimilarity index 96%rename from modules/webhooks/spec/workers/project_webhook_job.rbrename to modules/webhooks/spec/workers/project_webhook_job_spec.rbindex 4d0f1e107c9..efa5fea07f9 100644--- a/modules/webhooks/spec/workers/project_webhook_job.rb+++ b/modules/webhooks/spec/workers/project_webhook_job_spec.rb@@ -33,12 +33,12 @@ require 'spec_helper'describe ProjectWebhookJob, type: :job, webmock: true doshared_let(:user) { FactoryBot.create :admin }shared_let(:request_url) { "http://example.net/test/42" }- shared_let(:project) { FactoryBot.create :project, name: 'Foo Bar', hours: 10 }+ shared_let(:project) { FactoryBot.create :project, name: 'Foo Bar' }shared_let(:webhook) { FactoryBot.create :webhook, all_projects: true, url: request_url, secret: nil }shared_examples "a project webhook call" dolet(:event) { "project:created" }- let(:job) { TimeEntryWebhookJob.perform_now(webhook.id, project, event) }+ let(:job) { ProjectWebhookJob.perform_now(webhook.id, project, event) }let(:stubbed_url) { request_url }@@ -57,7 +57,7 @@ describe ProjectWebhookJob, type: :job, webmock: true do.with(body: hash_including("action" => event,- "poroject" => hash_including(+ "project" => hash_including("_type" => "Project","name" => 'Foo Bar')@@ -99,7 +99,7 @@ describe ProjectWebhookJob, type: :job, webmock: true do.and_return(false)subject- if event_name == 'project:created'+ if event == 'project:created'expect(stub).to have_been_requestedelseexpect(stub).not_to have_been_requesteddiff --git a/modules/webhooks/spec/workers/time_entry_webhook_job.rb b/modules/webhooks/spec/workers/time_entry_webhook_job_spec.rbsimilarity index 100%rename from modules/webhooks/spec/workers/time_entry_webhook_job.rbrename to modules/webhooks/spec/workers/time_entry_webhook_job_spec.rbdiff --git a/modules/webhooks/spec/workers/work_package_webhook_job.rb b/modules/webhooks/spec/workers/work_package_webhook_job_spec.rbsimilarity index 94%rename from modules/webhooks/spec/workers/work_package_webhook_job.rbrename to modules/webhooks/spec/workers/work_package_webhook_job_spec.rbindex 12c9edd8e28..55b80f40ea2 100644--- a/modules/webhooks/spec/workers/work_package_webhook_job.rb+++ b/modules/webhooks/spec/workers/work_package_webhook_job_spec.rb@@ -39,7 +39,7 @@ describe WorkPackageWebhookJob, type: :model, webmock: true doshared_examples "a work package webhook call" dolet(:event) { "work_package:created" }- let(:job) { WorkPackageWebhookJob.new webhook.id, work_package.journals.last.id, event }+ let(:job) { described_class.perform_now webhook.id, work_package, event }let(:stubbed_url) { request_url }@@ -72,12 +72,7 @@ describe WorkPackageWebhookJob, type: :model, webmock: true do)end- subject do- job.perform- rescue StandardError- # ignoring it as it's expected to throw exceptions in certain scenarios- nil- end+ subject { job }before doallow(::Webhooks::Webhook).to receive(:find).with(webhook.id).and_return(webhook)diff --git a/spec/models/attachment_spec.rb b/spec/models/attachment_spec.rbindex 9d9d49611fa..3a8b70d157c 100644--- a/spec/models/attachment_spec.rb+++ b/spec/models/attachment_spec.rb@@ -157,14 +157,6 @@ describe Attachment, type: :model doexpect(attachment.content_type).to eq 'image/jpeg'end- context 'with wrong content-type' do- let(:file) { FactoryBot.create :uploaded_jpg, content_type: 'text/html' }-- it 'detects the correct content-type' do- expect(attachment.content_type).to eq 'image/jpeg'- end- end-it 'has the correct filesize' doexpect(attachment.filesize).to eql file.size