A platform for community discussion. Free, open, simple.
FEATURE: Add background job and ability to delete posts from suspend user modal (#36813)
Bannon Tanner938bf7ac25d3
diff --git a/app/controllers/admin/email_templates_controller.rb b/app/controllers/admin/email_templates_controller.rbindex fac5c61a38e..b7e1a67979c 100644--- a/app/controllers/admin/email_templates_controller.rb+++ b/app/controllers/admin/email_templates_controller.rb@@ -79,6 +79,7 @@ class Admin::EmailTemplatesController < Admin::AdminControllersystem_messages.user_added_to_group_as_ownersystem_messages.user_automatically_silencedsystem_messages.user_automatically_silenced_with_reason+ system_messages.user_posts_deletedsystem_messages.welcome_invitesystem_messages.welcome_staffsystem_messages.welcome_tl1_userdiff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rbindex 0d75026b662..76469da941c 100644--- a/app/controllers/admin/users_controller.rb+++ b/app/controllers/admin/users_controller.rb@@ -79,6 +79,22 @@ class Admin::UsersController < Admin::StaffControllerrender json: { posts_deleted: deleted_posts.length }end+ def delete_posts_decider+ @user = User.find_by(id: params[:user_id])+ raise Discourse::NotFound if !@user+ raise Discourse::InvalidAccess unless guardian.can_delete_all_posts?(@user)++ post_count = @user.post_count+ threshold = SiteSetting.delete_all_posts_background_threshold.to_i++ if threshold > 0 && post_count > threshold+ Jobs.enqueue(:delete_user_posts, user_id: @user.id, acting_user_id: current_user.id)+ render json: { job_enqueued: true, post_count: post_count }+ else+ render json: { job_enqueued: false, post_count: post_count }+ end+ end+# DELETE action to delete penalty history for a userdef penalty_history# We don't delete any history, we merely remove the action typediff --git a/app/jobs/regular/delete_user_posts.rb b/app/jobs/regular/delete_user_posts.rbnew file mode 100644index 00000000000..7df7ad80c74--- /dev/null+++ b/app/jobs/regular/delete_user_posts.rb@@ -0,0 +1,37 @@+# frozen_string_literal: true++module Jobs+ class DeleteUserPosts < ::Jobs::Base+ sidekiq_options queue: "critical"++ def execute(args)+ user = User.find(args[:user_id])+ return if user.nil?++ acting_user = User.find(args[:acting_user_id]) if args[:acting_user_id]+ return if acting_user.nil?++ guardian = Guardian.new(acting_user)+ return unless guardian.can_delete_all_posts?(user)++ deleted_count = 0++ loop do+ delete = user.delete_posts_in_batches(guardian)+ break if delete.empty?+ deleted_count += delete.size+ end++ post =+ SystemMessage.create_from_system_user(+ acting_user,+ :user_posts_deleted,+ user: user.username,+ staff_user: acting_user.username,+ deleted_posts_count: deleted_count,+ )++ post&.topic&.invite_group(acting_user, Group[:admins])+ end+ end+enddiff --git a/app/services/user/suspend.rb b/app/services/user/suspend.rbindex 91eacad8919..bd7db6e31c1 100644--- a/app/services/user/suspend.rb+++ b/app/services/user/suspend.rb@@ -19,7 +19,7 @@ class User::Suspendvalidates :other_user_ids, length: { maximum: User::MAX_SIMILAR_USERS }validates :post_action,inclusion: {- in: %w[delete delete_replies edit none],+ in: %w[delete delete_replies delete_all edit none],},allow_blank: trueenddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 654b218c319..ba48850a43a 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -8081,6 +8081,17 @@ en:penalty_post_actions: "What would you like to do with the associated post?"penalty_post_delete: "Delete the post"penalty_post_delete_replies: "Delete the post + any replies"+ penalty_post_delete_all: "Delete all topics by user + any replies"+ penalty_post_delete_all_confirmation_MF: |+ <span>This will delete+ { TOPICS, plural,+ one {# topic}+ other {# topics}+ } and+ { REPLIES, plural,+ one {# reply}+ other {# replies}+ }. <b>This cannot be undone!</b> Are you sure you would like to do this?</span>penalty_post_edit: "Edit the post"penalty_post_none: "Do nothing"penalty_count: "Penalty Count"@@ -8187,7 +8198,9 @@ en:button: "Delete all posts"progress:title: "Progress of deleting posts"- description: "Deleting posts…"+ description:+ one: "Deleting %{count} post by @%{username}..."+ other: "Deleting %{count} posts by @%{username}..."confirmation:title: "Delete all posts by @%{username}"description: |@@ -8200,6 +8213,7 @@ en:text: "delete posts by @%{username}"delete: "Delete posts by @%{username}"cancel: "Cancel"+ all_enqueued: "All of @%{username}'s posts have been queued for deletion"merge:button: "Merge"prompt:diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 4a4c73ca39c..5d0b1c1d775 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -2399,6 +2399,7 @@ en:relative_date_duration: "Number of days after posting where post dates will be shown as relative (7d) instead of absolute (20 Feb)."delete_user_max_post_age: "Don't allow deleting users whose first post is older than (x) days."delete_all_posts_max: "The maximum number of posts that can be deleted at once with the Delete All Posts button. If a user has more than this many posts, the posts cannot all be deleted at once and the user can't be deleted."+ delete_all_posts_background_threshold: "The maximum number of posts that can be deleted at once with the Delete All Posts button before the deletion is processed in the background."delete_user_self_max_post_count: "The maximum number of posts a user can have while allowing self-service account deletion. Set to -1 to disable self-service account deletion."username_change_period: "The maximum number of days after registration that accounts can change their username (0 to disallow username change)."email_editable: "Allow users to change their e-mail address after registration."@@ -4106,6 +4107,12 @@ en:Posts from new users were held for moderation and are currently waiting to be reviewed. [Approve or reject them here](%{base_url}/review?type=ReviewableQueuedPost).+ user_posts_deleted:+ title: "User Posts Deleted"+ subject_template: "All of %{user}'s posts have been deleted"+ text_body_template: |+ %{deleted_posts_count} posts from @%{user} have been deleted by @%{staff_user}.+unsubscribe_link: |To unsubscribe from these emails, [click here](%{unsubscribe_url}).diff --git a/config/routes.rb b/config/routes.rbindex 364a0cda965..194ded7eed9 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -145,6 +145,7 @@ Discourse::Application.routes.draw dodelete "penalty_history", constraints: AdminConstraint.newput "suspend"put "delete_posts_batch"+ post "delete_posts_decider"put "unsuspend"put "revoke_admin", constraints: AdminConstraint.newput "grant_admin", constraints: AdminConstraint.newdiff --git a/config/site_settings.yml b/config/site_settings.ymlindex 8801086309a..91912fd3806 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -992,6 +992,11 @@ users:default: 15min: 1area: "users"+ delete_all_posts_background_threshold:+ client: true+ default: 200+ min: 1+ area: "users"delete_user_self_max_post_count:default: 1min: -1diff --git a/frontend/discourse/admin/components/admin-penalty-post-action.gjs b/frontend/discourse/admin/components/admin-penalty-post-action.gjsindex 01776bc6f42..29111eec036 100644--- a/frontend/discourse/admin/components/admin-penalty-post-action.gjs+++ b/frontend/discourse/admin/components/admin-penalty-post-action.gjs@@ -1,20 +1,25 @@/* eslint-disable ember/no-classic-components */-import Component, { Textarea } from "@ember/component";+import { tracked } from "@glimmer/tracking";+import Component, { Input, Textarea } from "@ember/component";+import { on } from "@ember/modifier";import { action } from "@ember/object";import { equal } from "@ember/object/computed";import { htmlSafe } from "@ember/template";import discourseComputed, { afterRender } from "discourse/lib/decorators";import ComboBox from "discourse/select-kit/components/combo-box";-import { i18n } from "discourse-i18n";+import I18n, { i18n } from "discourse-i18n";-const ACTIONS = ["delete", "delete_replies", "edit", "none"];+const ACTIONS = ["delete", "delete_all", "delete_replies", "edit", "none"];export default class AdminPenaltyPostAction extends Component {+ @tracked confirmDeleteAll = false;+postId = null;postAction = null;postEdit = null;@equal("postAction", "edit") editing;+ @equal("postAction", "delete_all") deletingAll;@discourseComputedpenaltyActions() {@@ -23,6 +28,32 @@ export default class AdminPenaltyPostAction extends Component {});}+ get topicsCount() {+ return this.user.topic_count;+ }++ get repliesCount() {+ return this.user.post_count - this.user.topic_count;+ }++ canSubmitDeleteAll() {+ return this.postAction === "delete_all" && this.confirmDeleteAll;+ }++ get readyToDeleteAll() {+ return this.canSubmitDeleteAll();+ }++ get postTotalMessage() {+ return I18n.messageFormat(+ "admin.user.penalty_post_delete_all_confirmation_MF",+ {+ TOPICS: this.topicsCount,+ REPLIES: this.repliesCount,+ }+ );+ }+@actionpenaltyChanged(postAction) {this.set("postAction", postAction);@@ -33,6 +64,13 @@ export default class AdminPenaltyPostAction extends Component {}}+ @action+ toggleConfirmDeleteAll(event) {+ this.set("confirmDeleteAll", event.target.checked);++ this.onDeleteAllPostsReady?.(this.readyToDeleteAll);+ }+@afterRender_focusEditTextarea() {const elem = this.element;@@ -60,5 +98,16 @@ export default class AdminPenaltyPostAction extends Component {<Textarea @value={{this.postEdit}} class="post-editor" /></div>{{/if}}++ {{#if this.deletingAll}}+ <label>+ <Input+ @type="checkbox"+ @checked={{this.confirmDeleteAll}}+ {{on "click" this.toggleConfirmDeleteAll}}+ />+ {{htmlSafe this.postTotalMessage}}+ </label>+ {{/if}}</template>}diff --git a/frontend/discourse/admin/components/modal/delete-user-posts-progress.gjs b/frontend/discourse/admin/components/modal/delete-user-posts-progress.gjsindex a7d61edc573..723e57ffa22 100644--- a/frontend/discourse/admin/components/modal/delete-user-posts-progress.gjs+++ b/frontend/discourse/admin/components/modal/delete-user-posts-progress.gjs@@ -10,10 +10,14 @@ import { i18n } from "discourse-i18n";export default class DeleteUserPostsProgress extends Component {@tracked deletedPosts = 0;+ @tracked totalDeletedPosts = 0;@tracked flash;+ originalPostCount = 0;+constructor() {super(...arguments);+ this.originalPostCount = this.userPostCount;this.deletePosts();}@@ -22,7 +26,14 @@ export default class DeleteUserPostsProgress extends Component {}get deletedPercentage() {- return Math.floor((this.deletedPosts * 100) / this.userPostCount);+ return Math.floor((this.totalDeletedPosts * 100) / this.originalPostCount);+ }++ get deletedDescription() {+ return i18n("admin.user.delete_posts.progress.description", {+ count: this.originalPostCount,+ username: this.args.model.user.username,+ });}@action@@ -30,6 +41,7 @@ export default class DeleteUserPostsProgress extends Component {try {const progress = await this.args.model.user.deleteAllPosts();this.deletedPosts = progress.posts_deleted;+ this.totalDeletedPosts += progress.posts_deleted;this.args.model.updateUserPostCount(this.userPostCount - this.deletedPosts);@@ -52,7 +64,7 @@ export default class DeleteUserPostsProgress extends Component {@dismissable={{false}}><:body>- <p>{{i18n "admin.user.delete_posts.progress.description"}}</p>+ <p>{{htmlSafe this.deletedDescription}}</p><div class="progress-bar"><spanstyle={{htmlSafe (concat "width: " this.deletedPercentage "%")}}diff --git a/frontend/discourse/admin/components/modal/penalize-user.gjs b/frontend/discourse/admin/components/modal/penalize-user.gjsindex 71940384bd3..7c72b78a534 100644--- a/frontend/discourse/admin/components/modal/penalize-user.gjs+++ b/frontend/discourse/admin/components/modal/penalize-user.gjs@@ -27,6 +27,7 @@ export default class PenalizeUser extends Component {@tracked flash;@tracked reason;@tracked message;+ @tracked readyToDeleteAll = false;constructor() {super(...arguments);@@ -72,7 +73,8 @@ export default class PenalizeUser extends Component {this.penalizing ||isEmpty(this.penalizeUntil) ||!this.reason ||- this.reason.length < 1+ this.reason.length < 1 ||+ (this.postAction === "delete_all" && !this.readyToDeleteAll));}@@ -110,8 +112,12 @@ export default class PenalizeUser extends Component {console.error("Unknown penalty type:", this.args.model.penaltyType);}this.args.closeModal({ success: true });- if (this.successCallback) {- await this.successCallback(result);+ if (this.args.model.successCallback) {+ await this.args.model.successCallback({+ ...result,+ shouldDeleteAllPosts:+ this.postAction === "delete_all" && this.readyToDeleteAll,+ });}} catch (error) {this.flash = result ? extractError(result) : extractError(error);@@ -138,6 +144,11 @@ export default class PenalizeUser extends Component {this.otherUserIds = userIds;}+ @action+ updateReadyToDeleteAll(flag) {+ this.readyToDeleteAll = flag;+ }+<template><DModalclass="{{@model.penaltyType}}-user-modal"@@ -185,6 +196,8 @@ export default class PenalizeUser extends Component {@postId={{@model.postId}}@postAction={{this.postAction}}@postEdit={{this.postEdit}}+ @user={{@model.user}}+ @onDeleteAllPostsReady={{this.updateReadyToDeleteAll}}/>{{/if}}{{#if @model.user.similar_users_count}}diff --git a/frontend/discourse/admin/controllers/admin-user/index.js b/frontend/discourse/admin/controllers/admin-user/index.jsindex 5727ca79924..505750458f0 100644--- a/frontend/discourse/admin/controllers/admin-user/index.js+++ b/frontend/discourse/admin/controllers/admin-user/index.js@@ -13,7 +13,6 @@ import getURL from "discourse/lib/get-url";import DiscourseURL, { userPath } from "discourse/lib/url";import { i18n } from "discourse-i18n";import DeletePostsConfirmationModal from "../../components/modal/delete-posts-confirmation";-import DeleteUserPostsProgressModal from "../../components/modal/delete-user-posts-progress";import MergeUsersConfirmationModal from "../../components/modal/merge-users-confirmation";import MergeUsersProgressModal from "../../components/modal/merge-users-progress";import MergeUsersPromptModal from "../../components/modal/merge-users-prompt";@@ -664,21 +663,9 @@ export default class AdminUserIndexController extends Controller {@actionshowDeletePostsConfirmation() {this.modal.show(DeletePostsConfirmationModal, {- model: { user: this.model, deleteAllPosts: this.deleteAllPosts },- });- }-- @action- updateUserPostCount(count) {- this.model.set("post_count", count);- }-- @action- deleteAllPosts() {- this.modal.show(DeleteUserPostsProgressModal, {model: {user: this.model,- updateUserPostCount: this.updateUserPostCount,+ deleteAllPosts: () => this.adminTools.deletePostsDecider(this.model),},});}diff --git a/frontend/discourse/admin/models/admin-user.js b/frontend/discourse/admin/models/admin-user.jsindex 3d08ef3e30a..c7754e46cd9 100644--- a/frontend/discourse/admin/models/admin-user.js+++ b/frontend/discourse/admin/models/admin-user.js@@ -108,6 +108,12 @@ export default class AdminUser extends User {});}+ deleteAllPostsDecider() {+ return ajax(`/admin/users/${this.get("id")}/delete_posts_decider`, {+ type: "POST",+ });+ }+revokeAdmin() {return ajax(`/admin/users/${this.id}/revoke_admin`, {type: "PUT",diff --git a/frontend/discourse/admin/services/admin-tools.js b/frontend/discourse/admin/services/admin-tools.jsindex a33ac1b3e17..179f2089a37 100644--- a/frontend/discourse/admin/services/admin-tools.js+++ b/frontend/discourse/admin/services/admin-tools.js@@ -2,6 +2,7 @@ import { action } from "@ember/object";import Service, { service } from "@ember/service";import { htmlSafe } from "@ember/template";import { Promise } from "rsvp";+import DeleteUserPostsProgressModal from "discourse/admin/components/modal/delete-user-posts-progress";import PenalizeUserModal from "discourse/admin/components/modal/penalize-user";import AdminUser from "discourse/admin/models/admin-user";import { ajax } from "discourse/lib/ajax";@@ -44,6 +45,7 @@ export default class AdminToolsService extends Service {const loadedUser = user.adminUserView? user: await AdminUser.find(user.get("id"));+ const originalSuccessCallback = opts.successCallback;return this.modal.show(PenalizeUserModal, {model: {penaltyType: type,@@ -51,7 +53,15 @@ export default class AdminToolsService extends Service {postEdit: opts.postEdit,user: loadedUser,before: opts.before,- successCallback: opts.successCallback,+ successCallback: async (result) => {+ if (originalSuccessCallback) {+ await originalSuccessCallback(result);+ }++ if (result?.shouldDeleteAllPosts) {+ return this.deletePostsDecider(loadedUser);+ }+ },},});}@@ -118,4 +128,32 @@ export default class AdminToolsService extends Service {});});}++ async deletePostsDecider(user) {+ const response = await ajax(+ `/admin/users/${user.id}/delete_posts_decider`,+ {+ type: "POST",+ }+ );++ if (response.job_enqueued) {+ this.dialog.alert(+ i18n("admin.user.delete_posts.all_enqueued", {+ username: user.username,+ })+ );+ this.modal.close();+ return;+ }++ this.modal.show(DeleteUserPostsProgressModal, {+ model: {+ user,+ updateUserPostCount(count) {+ user.set("post_count", count);+ },+ },+ });+ }}diff --git a/spec/jobs/delete_user_posts_spec.rb b/spec/jobs/delete_user_posts_spec.rbnew file mode 100644index 00000000000..36a6b867aea--- /dev/null+++ b/spec/jobs/delete_user_posts_spec.rb@@ -0,0 +1,51 @@+# frozen_string_literal: true++RSpec.describe Jobs::DeleteUserPosts do+ fab!(:admin)+ fab!(:user)+ fab!(:topic) { Fabricate(:topic, user: user) }+ fab!(:posts) { Fabricate.times(3, :post, user: user, topic: topic) }++ it "deletes all posts for the user in batches" do+ expect(user.posts.count).to eq(3)+ described_class.new.execute(user_id: user.id, acting_user_id: admin.id)+ user.reload+ expect(user.post_count).to eq(0)+ expect(topic.reload.posts.count).to eq(0)+ end++ it "sends a system message with deletion count and invites admins" do+ described_class.new.execute(user_id: user.id, acting_user_id: admin.id)+ system_message = Post.where(user: Discourse.system_user).last+ expect(system_message).to be_present+ expect(system_message.topic.allowed_groups).to include(Group[:admins])+ end++ it "does nothing if not authorized to delete posts" do+ non_admin = Fabricate(:user)+ expect {+ described_class.new.execute(user_id: user.id, acting_user_id: non_admin.id)+ }.not_to change { user.posts.count }++ allow_any_instance_of(Guardian).to receive(:can_delete_all_posts?).and_return(false)+ expect {+ described_class.new.execute(user_id: user.id, acting_user_id: admin.id)+ }.not_to change { user.posts.count }+ end++ it "does nothing if user has no posts" do+ user.posts.destroy_all+ user.reload+ expect {+ described_class.new.execute(user_id: user.id, acting_user_id: admin.id)+ }.not_to change { user.posts.count }+ end++ it "handles large post counts by batching" do+ Fabricate.times(7, :post, user: user, topic: topic)+ expect(user.posts.count).to eq(10)+ described_class.new.execute(user_id: user.id, acting_user_id: admin.id)+ user.reload+ expect(user.posts.count).to eq(0)+ end+enddiff --git a/spec/requests/admin/users_controller_spec.rb b/spec/requests/admin/users_controller_spec.rbindex 20257607c4c..901aecf064e 100644--- a/spec/requests/admin/users_controller_spec.rb+++ b/spec/requests/admin/users_controller_spec.rb@@ -2537,6 +2537,104 @@ RSpec.describe Admin::UsersController doendend+ describe "#delete_posts_decider" do+ shared_examples "delete_posts_decider accessible" do |acting_user_role|+ let(:acting_user) { send(acting_user_role) }+ context "when user exists" do+ fab!(:target_user, :user)++ context "when post count is below or equal to threshold" do+ before { SiteSetting.delete_all_posts_background_threshold = 10 }++ it "returns job_enqueued: false with correct post_count" do+ post "/admin/users/#{target_user.id}/delete_posts_decider.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body["job_enqueued"]).to eq(false)+ expect(response.parsed_body["post_count"]).to eq(0)+ end+ end++ context "when post count exceeds threshold" do+ before do+ SiteSetting.delete_all_posts_background_threshold = 1+ Fabricate.times(2, :post, user: target_user)+ target_user.reload+ target_user.user_stat.update!(post_count: 2)++ allow(Jobs).to receive(:enqueue)+ end++ it "enqueues the delete_user_posts job and returns job_enqueued: true with correct post_count" do+ post "/admin/users/#{target_user.id}/delete_posts_decider.json"++ expect(Jobs).to have_received(:enqueue).with(+ :delete_user_posts,+ include(user_id: target_user.id, acting_user_id: acting_user.id),+ )++ expect(response.status).to eq(200)+ expect(response.parsed_body["job_enqueued"]).to eq(true)+ expect(response.parsed_body["post_count"]).to eq(2)+ end+ end++ context "when threshold is 0" do+ it "does not allow threshold to be set to 0" do+ expect { SiteSetting.delete_all_posts_background_threshold = 0 }.to raise_error(+ Discourse::InvalidParameters,+ )+ end+ end+ end++ context "when user does not exist" do+ it "returns 404 not found" do+ post "/admin/users/999999/delete_posts_decider.json"++ expect(response.status).to eq(404)+ expect(response.parsed_body["errors"]).to include(I18n.t("not_found"))+ end+ end+ end++ context "when logged in as an admin" do+ before { sign_in(admin) }+ include_examples "delete_posts_decider accessible", :admin+ end++ context "when logged in as a moderator" do+ before { sign_in(moderator) }+ include_examples "delete_posts_decider accessible", :moderator++ context "when user has too many posts to delete" do+ fab!(:target_user) do+ user = Fabricate(:user)+ Fabricate.times(16, :post, user: user)+ user.reload+ user.user_stat.update!(post_count: 16)+ user+ end++ it "denies access with a 403 response due to insufficient permissions" do+ post "/admin/users/#{target_user.id}/delete_posts_decider.json"+ expect(response.status).to eq(403)+ expect(response.parsed_body["errors"]).to include(I18n.t("invalid_access"))+ end+ end+ end++ context "when logged in as a non-staff user" do+ before { sign_in(user) }++ it "denies access with a 404 response" do+ post "/admin/users/#{user.id}/delete_posts_decider.json"++ expect(response.status).to eq(404)+ expect(response.parsed_body["errors"]).to include(I18n.t("not_found"))+ end+ end+ end+describe "#merge" dofab!(:target_user, :user)fab!(:topic) { Fabricate(:topic, user: user) }diff --git a/spec/services/user/suspend_spec.rb b/spec/services/user/suspend_spec.rbindex 12af49b0464..4dde0c01e75 100644--- a/spec/services/user/suspend_spec.rb+++ b/spec/services/user/suspend_spec.rb@@ -13,7 +13,7 @@ RSpec.describe User::Suspend doendit dois_expected.to validate_inclusion_of(:post_action).in_array(- %w[delete delete_replies edit none],+ %w[delete delete_replies delete_all edit none],).allow_blankendend