Class: ReviewablesController

Inherits:
ApplicationController show all
Defined in:
app/controllers/reviewables_controller.rb

Constant Summary collapse

PER_PAGE =
10

Constants inherited from ApplicationController

ApplicationController::LEGACY_NO_THEMES, ApplicationController::LEGACY_NO_UNOFFICIAL_PLUGINS, ApplicationController::NO_PLUGINS, ApplicationController::NO_THEMES, ApplicationController::NO_UNOFFICIAL_PLUGINS, ApplicationController::SAFE_MODE

Constants included from CanonicalURL::ControllerExtensions

CanonicalURL::ControllerExtensions::ALLOWED_CANONICAL_PARAMS

Instance Attribute Summary

Attributes inherited from ApplicationController

#theme_id

Instance Method Summary collapse

Methods inherited from ApplicationController

#application_layout, #can_cache_content?, #clear_notifications, #conditionally_allow_site_embedding, #current_homepage, #discourse_expires_in, #dont_cache_page, #ember_cli_required?, #fetch_user_from_params, #guardian, #handle_permalink, #handle_theme, #handle_unverified_request, #has_escaped_fragment?, #immutable_for, #no_cookies, #perform_refresh_session, #post_ids_including_replies, #preload_json, #rate_limit_second_factor!, #redirect_with_client_support, #render_json_dump, #render_serialized, requires_plugin, #rescue_discourse_actions, #resolve_safe_mode, #secure_session, #serialize_data, #set_current_user_for_logs, #set_layout, #set_mobile_view, #set_mp_snapshot_fields, #show_browser_update?, #store_preloaded, #use_crawler_layout?, #with_resolved_locale

Methods included from VaryHeader

#ensure_vary_header

Methods included from ReadOnlyMixin

#add_readonly_header, #allowed_in_staff_writes_only_mode?, #block_if_readonly_mode, #check_readonly_mode, included, #staff_writes_only_mode?

Methods included from Hijack

#hijack

Methods included from GlobalPath

#cdn_path, #cdn_relative_path, #full_cdn_url, #path, #upload_cdn_path

Methods included from JsonError

#create_errors_json

Methods included from CanonicalURL::ControllerExtensions

#canonical_url, #default_canonical, included

Methods included from CurrentUser

#clear_current_user, #current_user, has_auth_cookie?, #is_api?, #is_user_api?, #log_off_user, #log_on_user, lookup_from_env, #refresh_session

Instance Method Details

#countObject



89
90
91
# File 'app/controllers/reviewables_controller.rb', line 89

def count
  render_json_dump(count: Reviewable.pending_count(current_user))
end

#destroyObject



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'app/controllers/reviewables_controller.rb', line 157

def destroy
  user =
    if is_api?
      if @guardian.is_admin?
        fetch_user_from_params
      else
        raise Discourse::InvalidAccess
      end
    else
      current_user
    end

  reviewable =
    Reviewable.find_by_flagger_or_queued_post_creator(
      id: params[:reviewable_id],
      user_id: user.id,
    )
  raise Discourse::NotFound.new if reviewable.blank?

  reviewable.perform(current_user, :delete, { guardian: @guardian })

  render json: success_json
end

#explainObject



131
132
133
134
135
136
137
138
139
140
# File 'app/controllers/reviewables_controller.rb', line 131

def explain
  reviewable = find_reviewable

  render_serialized(
    { reviewable: reviewable, scores: reviewable.explain_score },
    ReviewableExplanationSerializer,
    rest_serializer: true,
    root: "reviewable_explanation",
  )
end

#indexObject



11
12
13
14
15
16
17
18
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
# File 'app/controllers/reviewables_controller.rb', line 11

def index
  offset = params[:offset].to_i

  if params[:type].present?
    raise Discourse::InvalidParameters.new(:type) unless Reviewable.valid_type?(params[:type])
  end

  status = (params[:status] || "pending").to_sym
  raise Discourse::InvalidParameters.new(:status) unless allowed_statuses.include?(status)

  topic_id = params[:topic_id] ? params[:topic_id].to_i : nil
  category_id = params[:category_id] ? params[:category_id].to_i : nil

  custom_keys = Reviewable.custom_filters.map(&:first)
  additional_filters =
    JSON.parse(params.fetch(:additional_filters, {}), symbolize_names: true).slice(*custom_keys)
  filters = {
    ids: params[:ids],
    status: status,
    category_id: category_id,
    topic_id: topic_id,
    additional_filters: additional_filters.reject { |_, v| v.blank? },
  }

  %i[priority username reviewed_by from_date to_date type sort_order].each do |filter_key|
    filters[filter_key] = params[filter_key]
  end

  total_rows = Reviewable.list_for(current_user, **filters).count
  reviewables =
    Reviewable.list_for(current_user, **filters.merge(limit: PER_PAGE, offset: offset)).to_a

  claimed_topics = ReviewableClaimedTopic.claimed_hash(reviewables.map { |r| r.topic_id }.uniq)

  # This is a bit awkward, but ActiveModel serializers doesn't seem to serialize STI. Note `hash`
  # is mutated by the serializer and contains the side loaded records which must be merged in the end.
  hash = {}
  json = {
    reviewables:
      reviewables.map! do |r|
        result =
          r
            .serializer
            .new(r, root: nil, hash: hash, scope: guardian, claimed_topics: claimed_topics)
            .as_json
        hash[:bundled_actions].uniq!
        (hash["actions"] || []).uniq!
        result
      end,
    meta:
      filters.merge(
        total_rows_reviewables: total_rows,
        types: meta_types,
        reviewable_types: Reviewable.types,
        reviewable_count: current_user.reviewable_count,
        unseen_reviewable_count: Reviewable.unseen_reviewable_count(current_user),
      ),
  }
  if (offset + PER_PAGE) < total_rows
    json[:meta][:load_more_reviewables] = review_path(filters.merge(offset: offset + PER_PAGE))
  end
  json.merge!(hash)

  render_json_dump(json, rest_serializer: true)
end

#performObject



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'app/controllers/reviewables_controller.rb', line 214

def perform
  args = { version: params[:version].to_i }

  result = nil
  begin
    reviewable = find_reviewable

    if error = claim_error?(reviewable)
      return render_json_error(error)
    end

    if reviewable.type == "ReviewableUser"
      args.merge!(
        reject_reason: params[:reject_reason],
        send_email: params[:send_email] != "false",
      )
    end

    plugin_params =
      DiscoursePluginRegistry.reviewable_params.select do |reviewable_param|
        reviewable.type == reviewable_param[:type].to_s.classify
      end
    args.merge!(params.slice(*plugin_params.map { |pp| pp[:param] }).permit!)

    result = reviewable.perform(current_user, params[:action_id].to_sym, args)
  rescue Reviewable::InvalidAction => e
    if reviewable.type == "ReviewableUser" && !reviewable.pending? && reviewable.target.blank?
      raise Discourse::NotFound.new(
              e.message,
              custom_message: "reviewables.already_handled_and_user_not_exist",
            )
    else
      # Consider InvalidAction an InvalidAccess
      raise Discourse::InvalidAccess.new(e.message)
    end
  rescue Reviewable::UpdateConflict
    return render_json_error(I18n.t("reviewables.conflict"), status: 409)
  end

  if result.success?
    render_serialized(result, ReviewablePerformResultSerializer)
  else
    render_json_error(result)
  end
end

#settingsObject



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'app/controllers/reviewables_controller.rb', line 260

def settings
  raise Discourse::InvalidAccess.new unless current_user.admin?

  post_action_types = PostActionType.where(id: PostActionType.flag_types.values).order("id")

  if request.put?
    params[:reviewable_priorities].each do |id, priority|
      if !priority.nil? && Reviewable.priorities.has_value?(priority.to_i)
        # For now, the score bonus is equal to the priority. In the future we might want
        # to calculate it a different way.
        PostActionType.where(id: id).update_all(
          reviewable_priority: priority.to_i,
          score_bonus: priority.to_f,
        )
      end
    end
  end

  data = { reviewable_score_types: post_action_types }
  render_serialized(data, ReviewableSettingsSerializer, rest_serializer: true)
end

#showObject



142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'app/controllers/reviewables_controller.rb', line 142

def show
  reviewable = find_reviewable

  render_serialized(
    reviewable,
    reviewable.serializer,
    rest_serializer: true,
    claimed_topics: ReviewableClaimedTopic.claimed_hash([reviewable.topic_id]),
    root: "reviewable",
    meta: {
      types: meta_types,
    },
  )
end

#topicsObject



93
94
95
96
97
98
99
100
101
102
103
104
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
# File 'app/controllers/reviewables_controller.rb', line 93

def topics
  topic_ids = Set.new

  stats = {}
  unique_users = {}

  # topics isn't indexed on `reviewable_score` and doesn't know what the current user can see,
  # so let's query from the inside out.
  pending = Reviewable.viewable_by(current_user).pending
  pending = pending.where("score >= ?", Reviewable.min_score_for_priority)

  pending.each do |r|
    topic_ids << r.topic_id

    meta = stats[r.topic_id] ||= { count: 0, unique_users: 0 }
    users = unique_users[r.topic_id] ||= Set.new

    r.reviewable_scores.each do |rs|
      users << rs.user_id
      meta[:count] += 1
    end
    meta[:unique_users] = users.size
  end

  topics = Topic.where(id: topic_ids).order("reviewable_score DESC")
  render_serialized(
    topics,
    ReviewableTopicSerializer,
    root: "reviewable_topics",
    stats: stats,
    claimed_topics: ReviewableClaimedTopic.claimed_hash(topic_ids),
    rest_serializer: true,
    meta: {
      types: meta_types,
    },
  )
end

#updateObject



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'app/controllers/reviewables_controller.rb', line 181

def update
  reviewable = find_reviewable
  if error = claim_error?(reviewable)
    return render_json_error(error)
  end

  editable = reviewable.editable_for(guardian)
  raise Discourse::InvalidAccess.new unless editable.present?

  # Validate parameters are all editable
  edit_params = params[:reviewable] || {}
  edit_params.each do |name, value|
    if value.is_a?(ActionController::Parameters)
      value.each do |pay_name, pay_value|
        raise Discourse::InvalidAccess.new unless editable.has?("#{name}.#{pay_name}")
      end
    else
      raise Discourse::InvalidAccess.new unless editable.has?(name)
    end
  end

  begin
    if reviewable.update_fields(edit_params, current_user, version: params[:version].to_i)
      result = edit_params.merge(version: reviewable.version)
      render json: result
    else
      render_json_error(reviewable.errors)
    end
  rescue Reviewable::UpdateConflict
    render_json_error(I18n.t("reviewables.conflict"), status: 409)
  end
end

#user_menu_listObject



77
78
79
80
81
82
83
84
85
86
87
# File 'app/controllers/reviewables_controller.rb', line 77

def user_menu_list
  json = {
    reviewables:
      Reviewable.basic_serializers_for_list(
        Reviewable.user_menu_list_for(current_user),
        current_user,
      ).as_json,
    reviewable_count: current_user.reviewable_count,
  }
  render_json_dump(json, rest_serializer: true)
end