BigW Consortium Gitlab

emails_on_push_worker.rb 2.47 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
      compare = CompareService.new.execute(project, after_sha, project, before_sha)
37
      diff_refs = compare.diff_refs
38

39
      return false if compare.same
40

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

45
        reverse_compare = true
46

47 48
        return false if compare.commits.empty?
      end
49
    end
50

51
    recipients.split.each do |recipient|
52
      begin
53
        send_email(
54
          recipient,
55
          project_id,
56 57 58 59 60 61 62 63
          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
64 65
        )

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

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