emails_on_push_worker.rb 2.34 KB
Newer Older
1 2 3
class EmailsOnPushWorker
  include Sidekiq::Worker

4 5
  attr_reader :email, :skip_premailer

Douwe Maan's avatar
Douwe Maan committed
6 7 8
  def perform(project_id, recipients, push_data, options = {})
    options.symbolize_keys!
    options.reverse_merge!(
9
      send_from_committer_email:  false,
Douwe Maan's avatar
Douwe Maan committed
10 11 12 13 14
      disable_diffs:              false
    )
    send_from_committer_email = options[:send_from_committer_email]
    disable_diffs = options[:disable_diffs]

15 16 17
    project = Project.find(project_id)
    before_sha = push_data["before"]
    after_sha = push_data["after"]
18
    ref = push_data["ref"]
19 20
    author_id = push_data["user_id"]

21
    action =
22
      if Gitlab::Git.blank_ref?(before_sha)
23
        :create
24 25 26 27 28
      elsif Gitlab::Git.blank_ref?(after_sha)
        :delete
      else
        :push
      end
29

30 31 32 33
    compare = nil
    reverse_compare = false
    if action == :push
      compare = Gitlab::Git::Compare.new(project.repository.raw_repository, before_sha, after_sha)
34

35
      return false if compare.same
36

37 38
      if compare.commits.empty?
        compare = Gitlab::Git::Compare.new(project.repository.raw_repository, after_sha, before_sha)
39

40
        reverse_compare = true
41

42 43
        return false if compare.commits.empty?
      end
44
    end
45

46
    recipients.split.each do |recipient|
47
      begin
48
        send_email(
49
          recipient,
50
          project_id,
51 52 53 54 55 56 57
          author_id:                  author_id,
          ref:                        ref,
          action:                     action,
          compare:                    compare,
          reverse_compare:            reverse_compare,
          send_from_committer_email:  send_from_committer_email,
          disable_diffs:              disable_diffs
58 59
        )

60 61 62 63
      # These are input errors and won't be corrected even if Sidekiq retries
      rescue Net::SMTPFatalError, Net::SMTPSyntaxError => e
        logger.info("Failed to send e-mail for project '#{project.name_with_namespace}' to #{recipient}: #{e}")
      end
64
    end
65
  ensure
66
    @email = nil
67 68
    compare = nil
    GC.start
69
  end
70 71 72 73 74 75 76 77 78 79 80 81 82

  private

  def send_email(recipient, project_id, options)
    # Generating the body of this email can be expensive, so only do it once
    @skip_premailer ||= email.present?
    @email ||= Notify.repository_push_email(project_id, options)

    email.to = recipient
    email.add_message_id
    email.header[:skip_premailer] = true if skip_premailer
    email.deliver_now
  end
83
end