Read about our upcoming Code of Conduct on this issue

pipelines_email_service.rb 1.79 KB
Newer Older
1
2
# frozen_string_literal: true

3
4
5
class PipelinesEmailService < Service
  prop_accessor :recipients
  boolean_accessor :notify_only_broken_pipelines
James Lopez's avatar
James Lopez committed
6
  validates :recipients, presence: true, if: :valid_recipients?
7
8

  def initialize_properties
9
    self.properties ||= { notify_only_broken_pipelines: true }
10
11
12
13
14
15
16
17
18
19
  end

  def title
    'Pipelines emails'
  end

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

20
  def self.to_param
21
22
23
    'pipelines_email'
  end

24
  def self.supported_events
25
26
27
    %w[pipeline]
  end

Lin Jen-Shin's avatar
Lin Jen-Shin committed
28
  def execute(data, force: false)
29
    return unless supported_events.include?(data[:object_kind])
30
    return unless force || should_pipeline_be_notified?(data)
31
32
33
34
35

    all_recipients = retrieve_recipients(data)

    return unless all_recipients.any?

36
    pipeline_id = data[:object_attributes][:id]
37
    PipelineNotificationWorker.new.perform(pipeline_id, all_recipients)
38
39
40
  end

  def can_test?
41
    project.ci_pipelines.any?
42
43
44
  end

  def test_data(project, user)
45
    data = Gitlab::DataBuilder::Pipeline.build(project.ci_pipelines.last)
46
47
48
49
50
51
52
53
    data[:user] = user.hook_attrs
    data
  end

  def fields
    [
      { type: 'textarea',
        name: 'recipients',
54
55
        placeholder: 'Emails separated by comma',
        required: true },
56
      { type: 'checkbox',
57
        name: 'notify_only_broken_pipelines' }
58
59
60
61
    ]
  end

  def test(data)
Lin Jen-Shin's avatar
Lin Jen-Shin committed
62
    result = execute(data, force: true)
63
64
65
66
67
68

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

69
  def should_pipeline_be_notified?(data)
70
71
72
    case data[:object_attributes][:status]
    when 'success'
      !notify_only_broken_pipelines?
73
74
    when 'failed'
      true
75
76
77
78
79
80
    else
      false
    end
  end

  def retrieve_recipients(data)
81
    recipients.to_s.split(/[,(?:\r?\n) ]+/).reject(&:empty?)
82
83
  end
end