Class: Draft

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/draft.rb

Defined Under Namespace

Classes: OutOfSequence

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.allowed_draft_posts_for_user(user) ⇒ Object



219
220
221
222
# File 'app/models/draft.rb', line 219

def self.allowed_draft_posts_for_user(user)
  # .secured handles whispers, merge handles topic/pm visibility
  Post.secured(Guardian.new(user)).joins(:topic).merge(self.allowed_draft_topics_for_user(user))
end

.allowed_draft_topics_for_user(user) ⇒ Object



213
214
215
216
217
# File 'app/models/draft.rb', line 213

def self.allowed_draft_topics_for_user(user)
  topics = Topic.listable_topics.secured(Guardian.new(user))
  pms = Topic.private_messages_for_user(user)
  topics.or(pms)
end

.backup_draft(user, key, sequence, data) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'app/models/draft.rb', line 257

def self.backup_draft(user, key, sequence, data)
  reply = JSON.parse(data)["reply"] || ""
  return if reply.length < SiteSetting.backup_drafts_to_pm_length

  post_id = BackupDraftPost.where(user_id: user.id, key: key).pick(:post_id)
  post = Post.where(id: post_id).first if post_id

  BackupDraftPost.where(user_id: user.id, key: key).delete_all if post_id && !post

  indented_reply = reply.split("\n").map! { |l| "    #{l}" }
  draft_body = <<~MD
    #{indented_reply.join("\n")}

    ```text
    seq: #{sequence}
    key: #{key}
    ```
  MD

  return if post && post.raw == draft_body

  if !post
    topic = ensure_draft_topic!(user)
    Post.transaction do
      post =
        PostCreator.new(
          user,
          raw: draft_body,
          skip_jobs: true,
          skip_validations: true,
          topic_id: topic.id,
        ).create
      BackupDraftPost.create!(user_id: user.id, key: key, post_id: post.id)
    end
  elsif post.last_version_at > 5.minutes.ago
    # bypass all validations here to maximize speed
    post.update_columns(
      raw: draft_body,
      cooked: PrettyText.cook(draft_body),
      updated_at: Time.zone.now,
    )
  else
    revisor = PostRevisor.new(post, post.topic)
    revisor.revise!(
      user,
      { raw: draft_body },
      bypass_bump: true,
      skip_validations: true,
      skip_staff_log: true,
      bypass_rate_limiter: true,
    )
  end
rescue => e
  Discourse.warn_exception(e, message: "Failed to backup draft")
end

.cleanup!Object



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'app/models/draft.rb', line 239

def self.cleanup!
  DB.exec(<<~SQL)
    DELETE FROM drafts
     WHERE sequence < (
      SELECT MAX(s.sequence)
        FROM draft_sequences s
       WHERE s.draft_key = drafts.draft_key
         AND s.user_id = drafts.user_id
    )
  SQL

  # remove old drafts
  delete_drafts_older_than_n_days = SiteSetting.delete_drafts_older_than_n_days.days.ago
  Draft.where("updated_at < ?", delete_drafts_older_than_n_days).destroy_all

  UserStat.update_draft_count
end

.clear(user, key, sequence) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'app/models/draft.rb', line 140

def self.clear(user, key, sequence)
  if !user || !user.id || !User.human_user_id?(user.id)
    raise StandardError.new("user not present")
  end

  current_sequence = DraftSequence.current(user, key)

  # bad caller is a reason to complain
  raise Draft::OutOfSequence.new("bad draft sequence") if sequence != current_sequence

  # corrupt data is not a reason not to leave data
  Draft.where(user_id: user.id, draft_key: key).destroy_all
end

.ensure_draft_topic!(user) ⇒ Object



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'app/models/draft.rb', line 313

def self.ensure_draft_topic!(user)
  topic_id = BackupDraftTopic.where(user_id: user.id).pick(:topic_id)
  topic = Topic.find_by(id: topic_id) if topic_id

  BackupDraftTopic.where(user_id: user.id).delete_all if topic_id && !topic

  if !topic
    Topic.transaction do
      creator =
        PostCreator.new(
          user,
          title: I18n.t("draft_backup.pm_title"),
          archetype: Archetype.private_message,
          raw: I18n.t("draft_backup.pm_body"),
          skip_jobs: true,
          skip_validations: true,
          target_usernames: user.username,
        )
      topic = creator.create.topic
      BackupDraftTopic.create!(topic_id: topic.id, user_id: user.id)
    end
  end

  topic
end

.get(user, key, sequence) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'app/models/draft.rb', line 105

def self.get(user, key, sequence)
  return if !user || !user.id || !User.human_user_id?(user.id)

  opts = { user_id: user.id, draft_key: key, sequence: sequence }

  current_sequence, data, draft_sequence = DB.query_single(<<~SQL, opts)
    WITH draft AS (
      SELECT data, sequence
      FROM drafts
      WHERE draft_key = :draft_key AND user_id = :user_id
    ),
    draft_sequence AS (
      SELECT sequence
      FROM draft_sequences
      WHERE draft_key = :draft_key AND user_id = :user_id
    )
    SELECT
      ( SELECT sequence FROM draft_sequence) ,
      ( SELECT data FROM draft ),
      ( SELECT sequence FROM draft )
  SQL

  current_sequence ||= 0

  raise Draft::OutOfSequence if sequence != current_sequence

  data if current_sequence == draft_sequence
end

.has_topic_draft(user) ⇒ Object



134
135
136
137
138
# File 'app/models/draft.rb', line 134

def self.has_topic_draft(user)
  return if !user || !user.id || !User.human_user_id?(user.id)

  Draft.where(user_id: user.id, draft_key: NEW_TOPIC).present?
end

.preload_data(drafts, user) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
# File 'app/models/draft.rb', line 200

def self.preload_data(drafts, user)
  topic_ids = drafts.map(&:topic_id)
  post_ids = drafts.map(&:post_id)

  topics = self.allowed_draft_topics_for_user(user).where(id: topic_ids)
  posts = self.allowed_draft_posts_for_user(user).where(id: post_ids)

  drafts.each do |draft|
    draft.preload_topic(topics.detect { |t| t.id == draft.topic_id })
    draft.preload_post(posts.detect { |p| p.id == draft.post_id })
  end
end

.set(user, key, sequence, data, owner = nil, force_save: false) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'app/models/draft.rb', line 19

def self.set(user, key, sequence, data, owner = nil, force_save: false)
  return 0 if !User.human_user_id?(user.id)
  force_save = force_save.to_s == "true"

  if SiteSetting.backup_drafts_to_pm_length > 0 &&
       SiteSetting.backup_drafts_to_pm_length < data.length
    backup_draft(user, key, sequence, data)
  end

  # this is called a lot so we should micro optimize here
  draft_id, current_owner, current_sequence = DB.query_single(<<~SQL, user_id: user.id, key: key)
    WITH draft AS (
      SELECT id, owner FROM drafts
      WHERE
        user_id = :user_id AND
        draft_key = :key
    ),
    draft_sequence AS (
      SELECT sequence
      FROM draft_sequences
      WHERE
        user_id = :user_id AND
        draft_key = :key
    )

    SELECT
      (SELECT id FROM draft),
      (SELECT owner FROM draft),
      (SELECT sequence FROM draft_sequence)
  SQL

  current_sequence ||= 0

  if draft_id
    raise Draft::OutOfSequence if !force_save && (current_sequence != sequence)

    sequence = current_sequence if force_save
    sequence += 1

    # we need to keep upping our sequence on every save
    # if we do not do that there are bad race conditions
    DraftSequence.upsert(
      { sequence: sequence, draft_key: key, user_id: user.id },
      unique_by: %i[user_id draft_key],
    )

    DB.exec(<<~SQL, id: draft_id, sequence: sequence, data: data, owner: owner || current_owner)
      UPDATE drafts
         SET sequence = :sequence
           , data = :data
           , revisions = revisions + 1
           , owner = :owner
           , updated_at = CURRENT_TIMESTAMP
       WHERE id = :id
    SQL
  elsif sequence != current_sequence
    raise Draft::OutOfSequence
  else
    opts = { user_id: user.id, draft_key: key, data: data, sequence: sequence, owner: owner }

    draft_id = DB.query_single(<<~SQL, opts).first
      INSERT INTO drafts (user_id, draft_key, data, sequence, owner, created_at, updated_at)
      VALUES (:user_id, :draft_key, :data, :sequence, :owner, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
      ON CONFLICT (user_id, draft_key) DO
      UPDATE
      SET
        sequence = :sequence,
        data = :data,
        revisions = drafts.revisions + 1,
        owner = :owner,
        updated_at = CURRENT_TIMESTAMP
      RETURNING id
    SQL

    UserStat.update_draft_count(user.id)
  end

  UploadReference.ensure_exist!(
    upload_ids: Upload.extract_upload_ids(data),
    target_type: "Draft",
    target_id: draft_id,
  )

  sequence
end

.stream(opts = nil) ⇒ Object



224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'app/models/draft.rb', line 224

def self.stream(opts = nil)
  opts ||= {}

  user_id = opts[:user].id
  offset = (opts[:offset] || 0).to_i
  limit = (opts[:limit] || 30).to_i

  stream = Draft.where(user_id: user_id).order(updated_at: :desc).offset(offset).limit(limit)

  # Preload posts and topics to avoid N+1 queries
  Draft.preload_data(stream, opts[:user])

  stream
end

Instance Method Details

#display_userObject



154
155
156
# File 'app/models/draft.rb', line 154

def display_user
  post&.user || topic&.user || user
end

#parsed_dataObject



158
159
160
161
162
163
164
# File 'app/models/draft.rb', line 158

def parsed_data
  begin
    JSON.parse(data)
  rescue JSON::ParserError
    {}
  end
end

#postObject



192
193
194
# File 'app/models/draft.rb', line 192

def post
  post_preloaded? ? @post : @post = Draft.allowed_draft_posts_for_user(user).find_by(id: post_id)
end

#post_idObject



184
185
186
# File 'app/models/draft.rb', line 184

def post_id
  parsed_data["postId"]
end

#post_preloaded?Boolean

Returns:

  • (Boolean)


188
189
190
# File 'app/models/draft.rb', line 188

def post_preloaded?
  !!defined?(@post)
end

#preload_post(post) ⇒ Object



196
197
198
# File 'app/models/draft.rb', line 196

def preload_post(post)
  @post = post
end

#preload_topic(topic) ⇒ Object



180
181
182
# File 'app/models/draft.rb', line 180

def preload_topic(topic)
  @topic = topic
end

#topicObject



174
175
176
177
178
# File 'app/models/draft.rb', line 174

def topic
  topic_preloaded? ?
    @topic :
    @topic = Draft.allowed_draft_topics_for_user(user).find_by(id: topic_id)
end

#topic_idObject



166
167
168
# File 'app/models/draft.rb', line 166

def topic_id
  draft_key.gsub(EXISTING_TOPIC, "").to_i if draft_key.starts_with?(EXISTING_TOPIC)
end

#topic_preloaded?Boolean

Returns:

  • (Boolean)


170
171
172
# File 'app/models/draft.rb', line 170

def topic_preloaded?
  !!defined?(@topic)
end

#update_draft_countObject



339
340
341
# File 'app/models/draft.rb', line 339

def update_draft_count
  UserStat.update_draft_count(self.user_id)
end