# frozen_string_literal: true module Jobs class UpdateUsername < ::Jobs::Base sidekiq_options queue: "low" def execute(args) @user_id = args[:user_id] user = User.find_by(id: @user_id) return unless user @old_username = args[:old_username].unicode_normalize @new_username = args[:new_username].unicode_normalize avatar_img = PrettyText.avatar_img(args[:avatar_template], "tiny") @quote_rewriter = QuoteRewriter.new(@user_id, @old_username, @new_username, avatar_img) @raw_mention_regex = / (?: (?> 'original_username' WHEN :old_username THEN :new_username ELSE NULL END, 'display_username', CASE data :: JSONB ->> 'display_username' WHEN :old_username THEN :new_username ELSE NULL END, 'username', CASE data :: JSONB ->> 'username' WHEN :old_username THEN :new_username ELSE NULL END, 'username2', CASE data :: JSONB ->> 'username2' WHEN :old_username THEN :new_username ELSE NULL END ) )) :: JSON WHERE data ILIKE '%' || :old_username || '%' SQL end def update_post_custom_fields DB.exec(<<~SQL, old_username: @old_username, new_username: @new_username) UPDATE post_custom_fields SET value = :new_username WHERE name = 'action_code_who' AND value = :old_username SQL end protected def update_post(post) post.raw = update_raw(post.raw) post.cooked = update_cooked(post.cooked) post.update_columns(raw: post.raw, cooked: post.cooked) SearchIndexer.index(post, force: true) if post.topic rescue => e Discourse.warn_exception(e, message: "Failed to update post with id #{post.id}") end def update_revision(revision) if revision.modifications.key?("raw") || revision.modifications.key?("cooked") revision.modifications["raw"]&.map! { |raw| update_raw(raw) } revision.modifications["cooked"]&.map! { |cooked| update_cooked(cooked) } revision.save! end rescue => e Discourse.warn_exception(e, message: "Failed to update post revision with id #{revision.id}") end def mentioned(post_id_column) <<~SQL JOIN user_actions AS a ON (a.target_post_id = #{post_id_column} AND a.action_type = #{UserAction::MENTION}) SQL end def quoted(post_id_column) <<~SQL JOIN quoted_posts AS q ON (q.post_id = #{post_id_column}) JOIN posts AS p ON (q.quoted_post_id = p.id) SQL end def update_raw(raw) @quote_rewriter.rewrite_raw(raw.gsub(@raw_mention_regex, "@#{@new_username}")) end # Uses Nokogiri instead of rebake, because it works for posts and revisions # and there is no reason to invalidate oneboxes, run the post analyzer etc. # when only the username changes. def update_cooked(cooked) doc = Nokogiri::HTML5.fragment(cooked) doc .css("a.mention") .each do |a| a.content = a.content.gsub(@cooked_mention_username_regex, "@#{@new_username}") a["href"] = a["href"].gsub( @cooked_mention_user_path_regex, "/u/#{UrlHelper.encode_component(@new_username)}", ) if a["href"] end @quote_rewriter.rewrite_cooked(doc) doc.to_html end def quotes_correct_user?(aside) Post.exists?( topic_id: aside["data-topic"], post_number: aside["data-post"], user_id: @user_id, ) end end end