note.rb 10.1 KB
Newer Older
1
2
3
4
5
6
7
8
# == Schema Information
#
# Table name: notes
#
#  id            :integer          not null, primary key
#  note          :text
#  noteable_type :string(255)
#  author_id     :integer
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
9
10
#  created_at    :datetime
#  updated_at    :datetime
11
12
13
#  project_id    :integer
#  attachment    :string(255)
#  line_code     :string(255)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
14
15
#  commit_id     :string(255)
#  noteable_id   :integer
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
16
#  system        :boolean          default(FALSE), not null
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
17
#  st_diff       :text
Stan Hu's avatar
Stan Hu committed
18
#  updated_by_id :integer
Stan Hu's avatar
Stan Hu committed
19
#  is_award      :boolean          default(FALSE), not null
20
21
#

gitlabhq's avatar
gitlabhq committed
22
23
24
require 'carrierwave/orm/activerecord'

class Note < ActiveRecord::Base
25
  include Gitlab::CurrentSettings
26
  include Participable
27
  include Mentionable
28

29
30
  default_value_for :system, false

31
  attr_mentionable :note, cache: true, pipeline: :note
32
  participant :author
33

gitlabhq's avatar
gitlabhq committed
34
  belongs_to :project
35
  belongs_to :noteable, polymorphic: true, touch: true
Nihad Abbasov's avatar
Nihad Abbasov committed
36
  belongs_to :author, class_name: "User"
37
  belongs_to :updated_by, class_name: "User"
gitlabhq's avatar
gitlabhq committed
38

39
  has_many :todos, dependent: :destroy
40

41
  delegate :gfm_reference, :local_reference, to: :noteable
Nihad Abbasov's avatar
Nihad Abbasov committed
42
43
  delegate :name, to: :project, prefix: true
  delegate :name, :email, to: :author, prefix: true
44

45
  before_validation :set_award!
46
  before_validation :clear_blank_line_code!
47

Nihad Abbasov's avatar
Nihad Abbasov committed
48
  validates :note, :project, presence: true
Valery Sizov's avatar
Valery Sizov committed
49
  validates :note, uniqueness: { scope: [:author, :noteable_type, :noteable_id] }, if: ->(n) { n.is_award }
50
  validates :note, inclusion: { in: Emoji.emojis_names }, if: ->(n) { n.is_award }
Robert Speicher's avatar
Robert Speicher committed
51
  validates :line_code, line_code: true, allow_blank: true
52
53
  # Attachments are deprecated and are handled by Markdown uploader
  validates :attachment, file_size: { maximum: :max_attachment_size }
gitlabhq's avatar
gitlabhq committed
54

55
56
  validates :noteable_id, presence: true, if: ->(n) { n.noteable_type.present? && n.noteable_type != 'Commit' }
  validates :commit_id, presence: true, if: ->(n) { n.noteable_type == 'Commit' }
Valery Sizov's avatar
Valery Sizov committed
57
  validates :author, presence: true
58

Nihad Abbasov's avatar
Nihad Abbasov committed
59
  mount_uploader :attachment, AttachmentUploader
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
60
61

  # Scopes
Valery Sizov's avatar
Valery Sizov committed
62
63
  scope :awards, ->{ where(is_award: true) }
  scope :nonawards, ->{ where(is_award: false) }
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
64
  scope :for_commit_id, ->(commit_id) { where(noteable_type: "Commit", commit_id: commit_id) }
65
  scope :inline, ->{ where("line_code IS NOT NULL") }
66
  scope :not_inline, ->{ where(line_code: nil) }
67
  scope :system, ->{ where(system: true) }
68
  scope :user, ->{ where(system: false) }
69
  scope :common, ->{ where(noteable_type: ["", nil]) }
70
  scope :fresh, ->{ order(created_at: :asc, id: :asc) }
71
72
  scope :inc_author_project, ->{ includes(:project, :author) }
  scope :inc_author, ->{ includes(:author) }
gitlabhq's avatar
gitlabhq committed
73

74
  scope :with_associations, -> do
75
    includes(:author, :noteable, :updated_by,
Yorick Peterse's avatar
Yorick Peterse committed
76
             project: [:project_members, { group: [:group_members] }])
77
  end
gitlabhq's avatar
gitlabhq committed
78

79
  serialize :st_diff
80
  before_create :set_diff, if: ->(n) { n.line_code.present? }
81

82
83
84
85
86
87
88
89
90
  class << self
    def discussions_from_notes(notes)
      discussion_ids = []
      discussions = []

      notes.each do |note|
        next if discussion_ids.include?(note.discussion_id)

        # don't group notes for the main target
91
        if !note.for_diff_line? && note.for_merge_request?
92
93
94
95
96
97
98
99
100
101
102
          discussions << [note]
        else
          discussions << notes.select do |other_note|
            note.discussion_id == other_note.discussion_id
          end
          discussion_ids << note.discussion_id
        end
      end

      discussions
    end
103

104
105
106
107
    def build_discussion_id(type, id, line_code)
      [:discussion, type.try(:underscore), id, line_code].join("-").to_sym
    end

108
109
110
111
112
113
114
    # Searches for notes matching the given query.
    #
    # This method uses ILIKE on PostgreSQL and LIKE on MySQL.
    #
    # query - The search query as a String.
    #
    # Returns an ActiveRecord::Relation.
115
    def search(query)
116
      table   = arel_table
117
118
119
      pattern = "%#{query}%"

      where(table[:note].matches(pattern))
120
    end
Valery Sizov's avatar
Valery Sizov committed
121
122

    def grouped_awards
123
124
      notes = {}

Valery Sizov's avatar
Valery Sizov committed
125
      awards.select(:note).distinct.map do |note|
126
        notes[note.note] = where(note: note.note)
Valery Sizov's avatar
Valery Sizov committed
127
      end
128
129
130
131
132

      notes["thumbsup"] ||= Note.none
      notes["thumbsdown"] ||= Note.none

      notes
Valery Sizov's avatar
Valery Sizov committed
133
    end
134
  end
135

136
  def cross_reference?
137
    system && SystemNoteService.cross_reference?(note)
138
139
  end

140
141
142
143
  def max_attachment_size
    current_application_settings.max_attachment_size.megabytes.to_i
  end

144
  def find_diff
145
146
    return nil unless noteable
    return @diff if defined?(@diff)
147

148
149
    # Don't use ||= because nil is a valid value for @diff
    @diff = noteable.diffs(Commit.max_diff_options).find do |d|
150
      Digest::SHA1.hexdigest(d.new_path) == diff_file_index if d.new_path
151
    end
152
153
  end

154
155
156
157
  def hook_attrs
    attributes
  end

158
159
160
  def set_diff
    # First lets find notes with same diff
    # before iterating over all mr diffs
161
    diff = diff_for_line_code unless for_merge_request?
162
163
164
165
166
167
168
169
170
    diff ||= find_diff

    self.st_diff = diff.to_hash if diff
  end

  def diff
    @diff ||= Gitlab::Git::Diff.new(st_diff) if st_diff.respond_to?(:map)
  end

171
172
173
174
  def diff_for_line_code
    Note.where(noteable_id: noteable_id, noteable_type: noteable_type, line_code: line_code).last.try(:diff)
  end

175
176
177
178
179
180
181
  # Check if this note is part of an "active" discussion
  #
  # This will always return true for anything except MergeRequest noteables,
  # which have special logic.
  #
  # If the note's current diff cannot be matched in the MergeRequest's current
  # diff, it's considered inactive.
182
  def active?
183
    return true unless self.diff
184
    return false unless noteable
185
    return @active if defined?(@active)
186

187
    noteable_diff = find_noteable_diff
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
188

189
190
    if noteable_diff
      parsed_lines = Gitlab::Diff::Parser.new.parse(noteable_diff.diff.each_line)
191

192
193
194
195
      @active = parsed_lines.any? { |line_obj| line_obj.text == diff_line }
    else
      @active = false
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
196

197
    @active
198
199
  end

200
  def diff_file_index
201
    line_code.split('_')[0] if line_code
202
203
204
  end

  def diff_file_name
205
    diff.new_path if diff
206
207
  end

208
209
210
211
212
213
214
215
  def file_path
    if diff.new_path.present?
      diff.new_path
    elsif diff.old_path.present?
      diff.old_path
    end
  end

216
  def diff_old_line
217
    line_code.split('_')[1].to_i if line_code
218
219
220
  end

  def diff_new_line
221
    line_code.split('_')[2].to_i if line_code
222
223
  end

224
225
226
227
  def generate_line_code(line)
    Gitlab::Diff::LineCode.generate(file_path, line.new_pos, line.old_pos)
  end

228
  def diff_line
229
230
    return @diff_line if @diff_line

231
    if diff
232
      diff_lines.each do |line|
233
234
235
        if generate_line_code(line) == self.line_code
          @diff_line = line.text
        end
236
      end
237
    end
238
239

    @diff_line
240
241
  end

242
243
244
245
246
247
248
249
250
251
252
253
254
255
  def diff_line_type
    return @diff_line_type if @diff_line_type

    if diff
      diff_lines.each do |line|
        if generate_line_code(line) == self.line_code
          @diff_line_type = line.type
        end
      end
    end

    @diff_line_type
  end

256
257
258
259
260
  def truncated_diff_lines
    max_number_of_lines = 16
    prev_match_line = nil
    prev_lines = []

261
    highlighted_diff_lines.each do |line|
262
263
264
      if line.type == "match"
        prev_lines.clear
        prev_match_line = line
265
266
      else
        prev_lines << line
267

268
269
270
        break if generate_line_code(line) == self.line_code

        prev_lines.shift if prev_lines.length >= max_number_of_lines
271
272
      end
    end
273
274

    prev_lines
275
276
277
  end

  def diff_lines
278
    @diff_lines ||= Gitlab::Diff::Parser.new.parse(diff.diff.each_line)
279
280
281
282
  end

  def highlighted_diff_lines
    Gitlab::Diff::Highlight.new(diff_lines).highlight
283
284
  end

285
  def discussion_id
286
    @discussion_id ||= Note.build_discussion_id(noteable_type, noteable_id || commit_id, line_code)
287
288
289
290
291
292
293
294
295
296
297
298
299
300
  end

  def for_commit?
    noteable_type == "Commit"
  end

  def for_commit_diff_line?
    for_commit? && for_diff_line?
  end

  def for_diff_line?
    line_code.present?
  end

Riyad Preukschas's avatar
Riyad Preukschas committed
301
302
303
304
  def for_issue?
    noteable_type == "Issue"
  end

305
306
307
308
309
310
  def for_merge_request?
    noteable_type == "MergeRequest"
  end

  def for_merge_request_diff_line?
    for_merge_request? && for_diff_line?
Cedric Gatay's avatar
Cedric Gatay committed
311
  end
312

313
  def for_snippet?
314
315
316
    noteable_type == "Snippet"
  end

Riyad Preukschas's avatar
Riyad Preukschas committed
317
318
319
  # override to return commits, which are not active record
  def noteable
    if for_commit?
320
      project.commit(commit_id)
321
    else
Riyad Preukschas's avatar
Riyad Preukschas committed
322
      super
323
    end
324
325
  # Temp fix to prevent app crash
  # if note commit id doesn't exist
326
  rescue
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
327
    nil
328
  end
329

Andrew8xx8's avatar
Andrew8xx8 committed
330
  # FIXME: Hack for polymorphic associations with STI
Steven Burgart's avatar
Steven Burgart committed
331
  #        For more information visit http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations
332
333
  def noteable_type=(noteable_type)
    super(noteable_type.to_s.classify.constantize.base_class.to_s)
Andrew8xx8's avatar
Andrew8xx8 committed
334
  end
Drew Blessing's avatar
Drew Blessing committed
335
336
337
338
339
340
341
342
343
344
345

  # Reset notes events cache
  #
  # Since we do cache @event we need to reset cache in special cases:
  # * when a note is updated
  # * when a note is removed
  # Events cache stored like  events/23-20130109142513.
  # The cache key includes updated_at timestamp.
  # Thus it will automatically generate a new fragment
  # when the event is updated because the key changes.
  def reset_events_cache
346
    Event.reset_event_cache_for(self)
Drew Blessing's avatar
Drew Blessing committed
347
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
348

349
  def downvote?
350
    is_award && note == "thumbsdown"
351
352
353
  end

  def upvote?
354
    is_award && note == "thumbsup"
355
356
  end

357
  def editable?
358
    !system? && !is_award
359
  end
360

361
362
363
364
  def cross_reference_not_visible_for?(user)
    cross_reference? && referenced_mentionables(user).empty?
  end

365
  # Checks if note is an award added as a comment
366
  #
367
368
  # If note is an award, this method sets is_award to true
  #   and changes content of the note to award name.
369
370
371
372
  #
  # Method is executed as a before_validation callback.
  #
  def set_award!
373
    return unless awards_supported? && contains_emoji_only?
374

375
376
377
378
    self.is_award = true
    self.note = award_emoji_name
  end

379
380
  private

381
382
383
384
  def clear_blank_line_code!
    self.line_code = nil if self.line_code.blank?
  end

385
386
387
388
389
390
  # Find the diff on noteable that matches our own
  def find_noteable_diff
    diffs = noteable.diffs(Commit.max_diff_options)
    diffs.find { |d| d.new_path == self.diff.new_path }
  end

391
  def awards_supported?
392
    (for_issue? || for_merge_request?) && !for_diff_line?
393
394
  end

395
  def contains_emoji_only?
396
    note =~ /\A#{Banzai::Filter::EmojiFilter.emoji_pattern}\s?\Z/
397
398
399
  end

  def award_emoji_name
400
    original_name = note.match(Banzai::Filter::EmojiFilter.emoji_pattern)[1]
Valery Sizov's avatar
Valery Sizov committed
401
    AwardEmoji.normilize_emoji_name(original_name)
402
  end
gitlabhq's avatar
gitlabhq committed
403
end