summaryrefslogtreecommitdiff
path: root/app/models/project_services/ci/mail_service.rb
blob: bb961d069720defd4cc3f226eeff97dd41d6533c (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
# == Schema Information
#
# Table name: ci_services
#
#  id         :integer          not null, primary key
#  type       :string(255)
#  title      :string(255)
#  project_id :integer          not null
#  created_at :datetime
#  updated_at :datetime
#  active     :boolean          default(FALSE), not null
#  properties :text
#

module Ci
  class MailService < Ci::Service
    delegate :email_recipients, :email_recipients=,
             :email_add_pusher, :email_add_pusher=,
             :email_only_broken_builds, :email_only_broken_builds=, to: :project, prefix: false

    before_save :update_project

    default_value_for :active, true

    def title
      'Mail'
    end

    def description
      'Email notification'
    end

    def to_param
      'mail'
    end

    def fields
      [
        { type: 'text', name: 'email_recipients', label: 'Recipients', help: 'Whitespace-separated list of recipient addresses' },
        { type: 'checkbox', name: 'email_add_pusher', label: 'Add pusher to recipients list' },
        { type: 'checkbox', name: 'email_only_broken_builds', label: 'Notify only broken builds' }
      ]
    end

    def can_execute?(build)
      return if build.allow_failure?

      # it doesn't make sense to send emails for retried builds
      commit = build.commit
      return unless commit
      return unless commit.latest_builds.include?(build)

      case build.status.to_sym
      when :failed
        true
      when :success
        true unless email_only_broken_builds
      else
        false
      end
    end

    def execute(build)
      build.project_recipients.each do |recipient|
        case build.status.to_sym
        when :success
          mailer.build_success_email(build.id, recipient).deliver_later
        when :failed
          mailer.build_fail_email(build.id, recipient).deliver_later
        end
      end
    end

    private

    def update_project
      project.save!
    end

    def mailer
      Ci::Notify
    end
  end
end