summaryrefslogtreecommitdiff
path: root/app/models/project_services/pipelines_email_service.rb
blob: 9d37184be2ce1cd9b111d743cc1572af013c66a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class PipelinesEmailService < Service
  prop_accessor :recipients
  boolean_accessor :notify_only_broken_pipelines
  validates :recipients, presence: true, if: :activated?

  def initialize_properties
    self.properties ||= { notify_only_broken_pipelines: true }
  end

  def title
    'Pipelines emails'
  end

  def description
    'Email the pipelines status to a list of recipients.'
  end

  def self.to_param
    'pipelines_email'
  end

  def self.supported_events
    %w[pipeline]
  end

  def execute(data, force: false)
    return unless supported_events.include?(data[:object_kind])
    return unless force || should_pipeline_be_notified?(data)

    all_recipients = retrieve_recipients(data)

    return unless all_recipients.any?

    pipeline_id = data[:object_attributes][:id]
    PipelineNotificationWorker.new.perform(pipeline_id, all_recipients)
  end

  def can_test?
    project.pipelines.any?
  end

  def disabled_title
    'Please setup a pipeline on your repository.'
  end

  def test_data(project, user)
    data = Gitlab::DataBuilder::Pipeline.build(project.pipelines.last)
    data[:user] = user.hook_attrs
    data
  end

  def fields
    [
      { type: 'textarea',
        name: 'recipients',
        placeholder: 'Emails separated by comma',
        required: true },
      { type: 'checkbox',
        name: 'notify_only_broken_pipelines' }
    ]
  end

  def test(data)
    result = execute(data, force: true)

    { success: true, result: result }
  rescue StandardError => error
    { success: false, result: error }
  end

  def should_pipeline_be_notified?(data)
    case data[:object_attributes][:status]
    when 'success'
      !notify_only_broken_pipelines?
    when 'failed'
      true
    else
      false
    end
  end

  def retrieve_recipients(data)
    recipients.to_s.split(',').reject(&:blank?)
  end
end