BigW Consortium Gitlab

sent_notification.rb 1.86 KB
Newer Older
Stan Hu committed
1 2 3 4 5 6 7 8 9 10
# == Schema Information
#
# Table name: sent_notifications
#
#  id            :integer          not null, primary key
#  project_id    :integer
#  noteable_id   :integer
#  noteable_type :string(255)
#  recipient_id  :integer
#  commit_id     :string(255)
11
#  line_code     :string(255)
Stan Hu committed
12 13 14
#  reply_key     :string(255)      not null
#

Douwe Maan committed
15 16 17 18 19 20 21 22
class SentNotification < ActiveRecord::Base
  belongs_to :project
  belongs_to :noteable, polymorphic: true
  belongs_to :recipient, class_name: "User"

  validate :project, :recipient, :reply_key, presence: true
  validate :reply_key, uniqueness: true

Douwe Maan committed
23 24
  validates :noteable_id, presence: true, unless: :for_commit?
  validates :commit_id, presence: true, if: :for_commit?
25
  validates :line_code, format: { with: /\A[a-z0-9]+_\d+_\d+\Z/ }, allow_blank: true
Douwe Maan committed
26

27
  class << self
28 29 30 31 32 33
    def reply_key
      return nil unless Gitlab::IncomingEmail.enabled?

      SecureRandom.hex(16)
    end

34 35 36 37
    def for(reply_key)
      find_by(reply_key: reply_key)
    end

38
    def record(noteable, recipient_id, reply_key, params = {})
39 40 41 42 43 44 45 46 47 48
      return unless reply_key

      noteable_id = nil
      commit_id = nil
      if noteable.is_a?(Commit)
        commit_id = noteable.id
      else
        noteable_id = noteable.id
      end

49
      params.reverse_merge!(
50 51 52 53 54 55 56
        project:        noteable.project,
        noteable_type:  noteable.class.name,
        noteable_id:    noteable_id,
        commit_id:      commit_id,
        recipient_id:   recipient_id,
        reply_key:      reply_key
      )
57 58 59 60 61 62 63 64

      create(params)
    end

    def record_note(note, recipient_id, reply_key, params = {})
      params[:line_code] = note.line_code
      
      record(note.noteable, recipient_id, reply_key, params)
65
    end
Douwe Maan committed
66 67 68 69 70 71 72 73
  end

  def for_commit?
    noteable_type == "Commit"
  end

  def noteable
    if for_commit?
Douwe Maan committed
74
      project.commit(commit_id) rescue nil
Douwe Maan committed
75 76 77 78 79
    else
      super
    end
  end
end