BigW Consortium Gitlab

emails_on_push_worker.rb 2.49 KB
Newer Older
1 2
class EmailsOnPushWorker
  include Sidekiq::Worker
3
  include DedicatedSidekiqQueue
4

5 6
  attr_reader :email, :skip_premailer

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

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

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

31
    diff_refs = nil
32 33
    compare = nil
    reverse_compare = false
34

35
    if action == :push
36 37
      compare = CompareService.new(project, after_sha)
        .execute(project, before_sha)
38
      diff_refs = compare.diff_refs
39

40
      return false if compare.same
41

42
      if compare.commits.empty?
43 44
        compare = CompareService.new(project, before_sha)
          .execute(project, after_sha)
45
        diff_refs = compare.diff_refs
46

47
        reverse_compare = true
48

49 50
        return false if compare.commits.empty?
      end
51
    end
52

53
    recipients.split.each do |recipient|
54
      begin
55
        send_email(
56
          recipient,
57
          project_id,
58 59 60 61 62 63 64 65
          author_id:                 author_id,
          ref:                       ref,
          action:                    action,
          compare:                   compare,
          reverse_compare:           reverse_compare,
          diff_refs:                 diff_refs,
          send_from_committer_email: send_from_committer_email,
          disable_diffs:             disable_diffs
66 67
        )

68 69 70 71
      # 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
72
    end
73
  ensure
74
    @email = nil
75 76
    compare = nil
    GC.start
77
  end
78 79 80 81 82 83 84 85 86 87 88 89 90

  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
91
end