BigW Consortium Gitlab

pipelines_email_service.rb 1.82 KB
Newer Older
1 2 3
class PipelinesEmailService < Service
  prop_accessor :recipients
  boolean_accessor :notify_only_broken_pipelines
4
  validates :recipients, presence: true, if: :activated?
5 6

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

  def title
    'Pipelines emails'
  end

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

18
  def self.to_param
19 20 21
    'pipelines_email'
  end

22
  def self.supported_events
23 24 25
    %w[pipeline]
  end

26
  def execute(data, force: false)
27
    return unless supported_events.include?(data[:object_kind])
28
    return unless force || should_pipeline_be_notified?(data)
29 30 31 32 33

    all_recipients = retrieve_recipients(data)

    return unless all_recipients.any?

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

  def can_test?
39
    project.pipelines.any?
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
  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',
56 57
        placeholder: 'Emails separated by comma',
        required: true },
58
      { type: 'checkbox',
59
        name: 'notify_only_broken_pipelines' }
60 61 62 63
    ]
  end

  def test(data)
64
    result = execute(data, force: true)
65 66 67 68 69 70

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

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

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