BigW Consortium Gitlab

note.rb 9.66 KB
Newer Older
1 2 3
# A note on the root of an issue, merge request, commit, or snippet.
#
# A note of this type is never resolvable.
gitlabhq committed
4
class Note < ActiveRecord::Base
5
  extend ActiveModel::Naming
6
  include Gitlab::CurrentSettings
7
  include Participable
8
  include Mentionable
9
  include Awardable
10
  include Importable
11
  include FasterCacheKeys
12
  include CacheMarkdownField
13
  include AfterCommitQueue
14
  include ResolvableNote
15
  include IgnorableColumn
16
  include Editable
17 18

  ignore_column :original_discussion_id
19

20
  cache_markdown_field :note, pipeline: :note, issuable_state_filter_enabled: true
21

22 23
  # Aliases to make application_helper#edited_time_ago_with_tooltip helper work properly with notes.
  # See https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/10392/diffs#note_28719102
24 25 26
  alias_attribute :last_edited_at, :updated_at
  alias_attribute :last_edited_by, :updated_by

27 28
  # Attribute containing rendered and redacted Markdown as generated by
  # Banzai::ObjectRenderer.
29
  attr_accessor :redacted_note_html
30

31 32 33 34
  # An Array containing the number of visible references as generated by
  # Banzai::ObjectRenderer
  attr_accessor :user_visible_reference_count

35
  # Attribute used to store the attributes that have ben changed by quick actions.
36 37
  attr_accessor :commands_changes

38 39
  default_value_for :system, false

Yorick Peterse committed
40
  attr_mentionable :note, pipeline: :note
41
  participant :author
42

gitlabhq committed
43
  belongs_to :project
44
  belongs_to :noteable, polymorphic: true, touch: true # rubocop:disable Cop/PolymorphicAssociations
45
  belongs_to :author, class_name: "User"
46
  belongs_to :updated_by, class_name: "User"
47
  belongs_to :last_edited_by, class_name: 'User'
gitlabhq committed
48

49 50
  has_many :todos, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
  has_many :events, as: :target, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
51
  has_one :system_note_metadata
52

53
  delegate :gfm_reference, :local_reference, to: :noteable
54 55
  delegate :name, to: :project, prefix: true
  delegate :name, :email, to: :author, prefix: true
56
  delegate :title, to: :noteable, allow_nil: true
57

58 59
  validates :note, presence: true
  validates :project, presence: true, unless: :for_personal_snippet?
60

61 62
  # Attachments are deprecated and are handled by Markdown uploader
  validates :attachment, file_size: { maximum: :max_attachment_size }
gitlabhq committed
63

64
  validates :noteable_type, presence: true
65
  validates :noteable_id, presence: true, unless: [:for_commit?, :importing?]
66
  validates :commit_id, presence: true, if: :for_commit?
Valery Sizov committed
67
  validates :author, presence: true
68
  validates :discussion_id, presence: true, format: { with: /\A\h{40}\z/ }
69

70
  validate unless: [:for_commit?, :importing?, :for_personal_snippet?] do |note|
71
    unless note.noteable.try(:project) == note.project
Douwe Maan committed
72
      errors.add(:project, 'does not match noteable project')
73 74 75
    end
  end

76
  mount_uploader :attachment, AttachmentUploader
Andrey Kumanyaev committed
77 78

  # Scopes
79
  scope :for_commit_id, ->(commit_id) { where(noteable_type: "Commit", commit_id: commit_id) }
80 81 82 83 84 85 86
  scope :system, -> { where(system: true) }
  scope :user, -> { where(system: false) }
  scope :common, -> { where(noteable_type: ["", nil]) }
  scope :fresh, -> { order(created_at: :asc, id: :asc) }
  scope :updated_after, ->(time) { where('updated_at > ?', time) }
  scope :inc_author_project, -> { includes(:project, :author) }
  scope :inc_author, -> { includes(:author) }
87 88 89
  scope :inc_relations_for_view, -> do
    includes(:project, :author, :updated_by, :resolved_by, :award_emoji, :system_note_metadata)
  end
gitlabhq committed
90

91 92 93
  scope :diff_notes, -> { where(type: %w(LegacyDiffNote DiffNote)) }
  scope :new_diff_notes, -> { where(type: 'DiffNote') }
  scope :non_diff_notes, -> { where(type: ['Note', 'DiscussionNote', nil]) }
94

95
  scope :with_associations, -> do
96 97
    # FYI noteable cannot be loaded for LegacyDiffNote for commits
    includes(:author, :noteable, :updated_by,
98
             project: [:project_members, { group: [:group_members] }])
99
  end
gitlabhq committed
100

101
  after_initialize :ensure_discussion_id
102
  before_validation :nullify_blank_type, :nullify_blank_line_code
103
  before_validation :set_discussion_id, on: :create
104
  after_save :keep_around_commit, unless: :for_personal_snippet?
105
  after_save :expire_etag_cache
106
  after_destroy :expire_etag_cache
107

108
  class << self
109 110 111
    def model_name
      ActiveModel::Name.new(self, nil, 'note')
    end
112

113
    def discussions(context_noteable = nil)
114
      Discussion.build_collection(all.includes(:noteable).fresh, context_noteable)
115
    end
116

117 118 119 120 121
    def find_discussion(discussion_id)
      notes = where(discussion_id: discussion_id).fresh.to_a
      return if notes.empty?

      Discussion.build(notes)
122
    end
123

124
    def grouped_diff_discussions(diff_refs = nil)
Douwe Maan committed
125
      groups = {}
126 127

      diff_notes.fresh.discussions.each do |discussion|
Douwe Maan committed
128
        line_code = discussion.line_code_in_diffs(diff_refs)
129

Douwe Maan committed
130 131 132 133
        if line_code
          discussions = groups[line_code] ||= []
          discussions << discussion
        end
134 135 136
      end

      groups
137
    end
138 139

    def count_for_collection(ids, type)
140 141 142
      user.select('noteable_id', 'COUNT(*) as count')
        .group(:noteable_id)
        .where(noteable_type: type, noteable_id: ids)
143
    end
144
  end
145

146
  def cross_reference?
147
    system? && SystemNoteService.cross_reference?(note)
148 149
  end

150 151
  def diff_note?
    false
152 153
  end

154
  def active?
155
    true
156 157
  end

158 159
  def max_attachment_size
    current_application_settings.max_attachment_size.megabytes.to_i
160 161
  end

162 163
  def hook_attrs
    attributes
164 165 166 167 168 169
  end

  def for_commit?
    noteable_type == "Commit"
  end

Riyad Preukschas committed
170 171 172 173
  def for_issue?
    noteable_type == "Issue"
  end

174 175 176 177
  def for_merge_request?
    noteable_type == "MergeRequest"
  end

178
  def for_snippet?
179 180 181
    noteable_type == "Snippet"
  end

182
  def for_personal_snippet?
Jarka Kadlecova committed
183 184 185 186 187
    noteable.is_a?(PersonalSnippet)
  end

  def skip_project_check?
    for_personal_snippet?
188 189
  end

190 191 192
  # override to return commits, which are not active record
  def noteable
    if for_commit?
193
      @commit ||= project.commit(commit_id)
194
    else
195
      super
196
    end
197 198
  # Temp fix to prevent app crash
  # if note commit id doesn't exist
199
  rescue
200
    nil
201
  end
202

Andrew8xx8 committed
203
  # FIXME: Hack for polymorphic associations with STI
Steven Burgart committed
204
  #        For more information visit http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations
205 206
  def noteable_type=(noteable_type)
    super(noteable_type.to_s.classify.constantize.base_class.to_s)
Andrew8xx8 committed
207
  end
208

209
  def editable?
210
    !system?
211
  end
212

213
  def cross_reference_not_visible_for?(user)
214 215 216 217 218 219 220 221 222
    cross_reference? && !has_referenced_mentionables?(user)
  end

  def has_referenced_mentionables?(user)
    if user_visible_reference_count.present?
      user_visible_reference_count > 0
    else
      referenced_mentionables(user).any?
    end
223 224
  end

225
  def award_emoji?
226
    can_be_award_emoji? && contains_emoji_only?
227 228
  end

229 230 231 232
  def emoji_awardable?
    !system?
  end

233
  def can_be_award_emoji?
234
    noteable.is_a?(Awardable) && !part_of_discussion?
235 236
  end

237
  def contains_emoji_only?
238
    note =~ /\A#{Banzai::Filter::EmojiFilter.emoji_pattern}\s?\Z/
239 240
  end

Jarka Kadlecova committed
241 242 243 244
  def to_ability_name
    for_personal_snippet? ? 'personal_snippet' : noteable_type.underscore
  end

245
  def can_be_discussion_note?
246
    self.noteable.supports_discussions? && !part_of_discussion?
247 248
  end

249 250
  def discussion_class(noteable = nil)
    # When commit notes are rendered on an MR's Discussion page, they are
Douwe Maan committed
251 252
    # displayed in one discussion instead of individually.
    # See also `#discussion_id` and `Discussion.override_discussion_id`.
Douwe Maan committed
253 254
    if noteable && noteable != self.noteable
      OutOfContextDiscussion
255 256 257 258 259
    else
      IndividualNoteDiscussion
    end
  end

Douwe Maan committed
260
  # See `Discussion.override_discussion_id` for details.
261 262 263 264
  def discussion_id(noteable = nil)
    discussion_class(noteable).override_discussion_id(self) || super()
  end

Douwe Maan committed
265 266 267 268
  # Returns a discussion containing just this note.
  # This method exists as an alternative to `#discussion` to use when the methods
  # we intend to call on the Discussion object don't require it to have all of its notes,
  # and just depend on the first note or the type of discussion. This saves us a DB query.
269 270 271 272
  def to_discussion(noteable = nil)
    Discussion.build([self], noteable)
  end

Douwe Maan committed
273 274 275
  # Returns the entire discussion this note is part of.
  # Consider using `#to_discussion` if we do not need to render the discussion
  # and all its notes and if we don't care about the discussion's resolvability status.
276
  def discussion
Douwe Maan committed
277 278
    full_discussion = self.noteable.notes.find_discussion(self.discussion_id) if part_of_discussion?
    full_discussion || to_discussion
279 280 281
  end

  def part_of_discussion?
Douwe Maan committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    !to_discussion.individual_note?
  end

  def in_reply_to?(other)
    case other
    when Note
      if part_of_discussion?
        in_reply_to?(other.noteable) && in_reply_to?(other.to_discussion)
      else
        in_reply_to?(other.noteable)
      end
    when Discussion
      self.discussion_id == other.id
    when Noteable
      self.noteable == other
    else
      false
    end
300 301
  end

302
  def expire_etag_cache
Douwe Maan committed
303
    return unless noteable&.discussions_rendered_on_frontend?
304 305

    key = Gitlab::Routing.url_helpers.project_noteable_notes_path(
306
      project,
307
      target_type: noteable_type.underscore,
308
      target_id: noteable_id
309 310 311 312
    )
    Gitlab::EtagCaching::Store.new.touch(key)
  end

313 314 315 316 317
  private

  def keep_around_commit
    project.repository.keep_around(self.commit_id)
  end
318 319 320 321 322 323 324 325

  def nullify_blank_type
    self.type = nil if self.type.blank?
  end

  def nullify_blank_line_code
    self.line_code = nil if self.line_code.blank?
  end
326 327 328

  def ensure_discussion_id
    return unless self.persisted?
329 330
    # Needed in case the SELECT statement doesn't ask for `discussion_id`
    return unless self.has_attribute?(:discussion_id)
331 332 333 334 335 336 337
    return if self.discussion_id

    set_discussion_id
    update_column(:discussion_id, self.discussion_id)
  end

  def set_discussion_id
338
    self.discussion_id ||= discussion_class.discussion_id(self)
339
  end
gitlabhq committed
340
end