BigW Consortium Gitlab

pipelines_email_service.rb 2.11 KB
Newer Older
1 2 3 4 5 6 7 8 9
class PipelinesEmailService < Service
  prop_accessor :recipients
  boolean_accessor :add_pusher
  boolean_accessor :notify_only_broken_pipelines
  validates :recipients,
    presence: true,
    if: ->(s) { s.activated? && !s.add_pusher? }

  def initialize_properties
10
    self.properties ||= { notify_only_broken_pipelines: true }
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
  end

  def title
    'Pipelines emails'
  end

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

  def to_param
    'pipelines_email'
  end

  def supported_events
    %w[pipeline]
  end

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

    all_recipients = retrieve_recipients(data)

    return unless all_recipients.any?

37 38
    pipeline = Ci::Pipeline.find(data[:object_attributes][:id])
    Ci::SendPipelineNotificationService.new(pipeline).execute(all_recipients)
39 40 41
  end

  def can_test?
42
    project.pipelines.any?
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
  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' },
      { type: 'checkbox',
        name: 'add_pusher',
        label: 'Add pusher to recipients list' },
      { type: 'checkbox',
        name: 'notify_only_broken_pipelines' },
    ]
  end

  def test(data)
69
    result = execute(data, force: true)
70 71 72 73 74 75

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

76
  def should_pipeline_be_notified?(data)
77 78 79
    case data[:object_attributes][:status]
    when 'success'
      !notify_only_broken_pipelines?
80 81
    when 'failed'
      true
82 83 84 85 86 87 88 89 90 91 92
    else
      false
    end
  end

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

    if add_pusher? && data[:user].try(:[], :email)
      all_recipients << data[:user][:email]
    end
Lin Jen-Shin committed
93 94

    all_recipients
95 96
  end
end