A platform for community discussion. Free, open, simple.
DEV: Enable Style/RedundantBegin rubocop rule (#40096)
Jarek Radoszfbb3bf3fe858
diff --git a/.rubocop.yml b/.rubocop.ymlindex a02a3da8b1b..435e774ff1e 100644--- a/.rubocop.yml+++ b/.rubocop.yml@@ -65,3 +65,6 @@ Lint/SymbolConversion:Style/RedundantParentheses:Enabled: true++Style/RedundantBegin:+ Enabled: truediff --git a/app/controllers/admin/backups_controller.rb b/app/controllers/admin/backups_controller.rbindex bb6c5904994..d665d4570ec 100644--- a/app/controllers/admin/backups_controller.rb+++ b/app/controllers/admin/backups_controller.rb@@ -299,17 +299,15 @@ class Admin::BackupsController < Admin::AdminControllerenddef create_direct_multipart_upload- begin- yield- rescue BackupRestore::BackupStore::StorageError => err- message =- debug_upload_error(- err,- I18n.t("upload.create_multipart_failure", additional_detail: err.message),- )- raise ExternalUploadHelpers::ExternalUploadValidationError.new(message)- rescue BackupRestore::BackupStore::BackupFileExists- raise ExternalUploadHelpers::ExternalUploadValidationError.new(I18n.t("backup.file_exists"))- end+ yield+ rescue BackupRestore::BackupStore::StorageError => err+ message =+ debug_upload_error(+ err,+ I18n.t("upload.create_multipart_failure", additional_detail: err.message),+ )+ raise ExternalUploadHelpers::ExternalUploadValidationError.new(message)+ rescue BackupRestore::BackupStore::BackupFileExists+ raise ExternalUploadHelpers::ExternalUploadValidationError.new(I18n.t("backup.file_exists"))endenddiff --git a/app/controllers/admin/themes_controller.rb b/app/controllers/admin/themes_controller.rbindex 256e65dee34..b8aae90450d 100644--- a/app/controllers/admin/themes_controller.rb+++ b/app/controllers/admin/themes_controller.rb@@ -66,35 +66,33 @@ class Admin::ThemesController < Admin::AdminControllerendhijack do- begin- branch = params[:branch] ? params[:branch] : nil- private_key =- params[:public_key] ? Discourse.redis.get("ssh_key_#{params[:public_key]}") : nil- if params[:public_key].present? && private_key.blank?- return render_json_error I18n.t("themes.import_error.ssh_key_gone")- end-- @theme =- RemoteTheme.import_theme(remote, theme_user, private_key: private_key, branch: branch)+ branch = params[:branch] ? params[:branch] : nil+ private_key =+ params[:public_key] ? Discourse.redis.get("ssh_key_#{params[:public_key]}") : nil+ if params[:public_key].present? && private_key.blank?+ return render_json_error I18n.t("themes.import_error.ssh_key_gone")+ end++ @theme =+ RemoteTheme.import_theme(remote, theme_user, private_key: private_key, branch: branch)+ render json: serialize_data(@theme, ThemeSerializer), status: :created+ rescue RemoteTheme::ImportError => e+ if params[:force]+ theme_name = params[:remote].gsub(/.git\z/, "").split("/").last++ remote_theme = RemoteTheme.new+ remote_theme.private_key = private_key+ remote_theme.branch = params[:branch] ? params[:branch] : nil+ remote_theme.remote_url = params[:remote]+ remote_theme.save!++ @theme = Theme.new(user_id: theme_user&.id || -1, name: theme_name)+ @theme.remote_theme = remote_theme+ @theme.save!+render json: serialize_data(@theme, ThemeSerializer), status: :created- rescue RemoteTheme::ImportError => e- if params[:force]- theme_name = params[:remote].gsub(/.git\z/, "").split("/").last-- remote_theme = RemoteTheme.new- remote_theme.private_key = private_key- remote_theme.branch = params[:branch] ? params[:branch] : nil- remote_theme.remote_url = params[:remote]- remote_theme.save!-- @theme = Theme.new(user_id: theme_user&.id || -1, name: theme_name)- @theme.remote_theme = remote_theme- @theme.save!-- render json: serialize_data(@theme, ThemeSerializer), status: :created- else- render_json_error e.message- end+ else+ render_json_error e.messageendendelsif params[:bundle] ||@@ -388,39 +386,35 @@ class Admin::ThemesController < Admin::AdminControllertheme_id = @theme.idhijack do- begin- private_key = nil- if params[:public_key].present?- private_key = Discourse.redis.get("ssh_key_#{params[:public_key]}")- return render_json_error I18n.t("themes.import_error.ssh_key_gone") if private_key.blank?- end+ private_key = nil+ if params[:public_key].present?+ private_key = Discourse.redis.get("ssh_key_#{params[:public_key]}")+ return render_json_error I18n.t("themes.import_error.ssh_key_gone") if private_key.blank?+ end- theme = Theme.include_relations.find(theme_id)- remote_theme = theme.remote_theme+ theme = Theme.include_relations.find(theme_id)+ remote_theme = theme.remote_theme- remote_theme.transaction do- remote_theme.remote_url = remote_url- remote_theme.branch = params[:branch].presence- remote_theme.private_key = private_key if private_key.present?- remote_theme.local_version = nil- remote_theme.remote_version = nil- remote_theme.commits_behind = nil+ remote_theme.transaction do+ remote_theme.remote_url = remote_url+ remote_theme.branch = params[:branch].presence+ remote_theme.private_key = private_key if private_key.present?+ remote_theme.local_version = nil+ remote_theme.remote_version = nil+ remote_theme.commits_behind = nil- remote_theme.update_from_remote(already_in_transaction: true)+ remote_theme.update_from_remote(already_in_transaction: true)- if remote_theme.last_error_text.present?- raise RemoteTheme::ImportError.new(remote_theme.last_error_text)- end+ if remote_theme.last_error_text.present?+ raise RemoteTheme::ImportError.new(remote_theme.last_error_text)end-- log_theme_change(nil, theme.reload)- render json: serialize_data(theme, ThemeSerializer), status: :ok- rescue RemoteTheme::ImportError,- ActiveRecord::RecordInvalid,- Theme::SettingsMigrationError => e- remote_theme.reload- render_json_error e.messageend++ log_theme_change(nil, theme.reload)+ render json: serialize_data(theme, ThemeSerializer), status: :ok+ rescue RemoteTheme::ImportError, ActiveRecord::RecordInvalid, Theme::SettingsMigrationError => e+ remote_theme.reload+ render_json_error e.messageendenddiff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rbindex e115436b807..c20d4d6597b 100644--- a/app/controllers/admin/users_controller.rb+++ b/app/controllers/admin/users_controller.rb@@ -406,27 +406,25 @@ class Admin::UsersController < Admin::StaffControlleroptions[:prepare_for_destroy] = truehijack do- begin- if UserDestroyer.new(current_user).destroy(user, options)- render json: { deleted: true }- else- render json: {- deleted: false,- user: AdminDetailedUserSerializer.new(user, root: false).as_json,- }- end- rescue UserDestroyer::PostsExistError+ if UserDestroyer.new(current_user).destroy(user, options)+ render json: { deleted: true }+ elserender json: {deleted: false,- message:- I18n.t(- "user.cannot_delete_has_posts",- username: user.username,- count: user.posts.joins(:topic).count,- ),- },- status: :forbidden+ user: AdminDetailedUserSerializer.new(user, root: false).as_json,+ }end+ rescue UserDestroyer::PostsExistError+ render json: {+ deleted: false,+ message:+ I18n.t(+ "user.cannot_delete_has_posts",+ username: user.username,+ count: user.posts.joins(:topic).count,+ ),+ },+ status: :forbiddenendenddiff --git a/app/controllers/drafts_controller.rb b/app/controllers/drafts_controller.rbindex 1c920807f07..3177144ac3f 100644--- a/app/controllers/drafts_controller.rb+++ b/app/controllers/drafts_controller.rb@@ -190,14 +190,12 @@ class DraftsController < ApplicationController# Validate all sequences first (fail fast)sequence_errors = []draft_keys.each do |draft_key|- begin- current_sequence = DraftSequence.current(user, draft_key)- provided_sequence = sequences[draft_key].to_i- sequence_errors << draft_key if provided_sequence != current_sequence- rescue StandardError- # If we can't get sequence for some reason, skip validation for this draft- # This maintains the same lenient behavior as the single delete- end+ current_sequence = DraftSequence.current(user, draft_key)+ provided_sequence = sequences[draft_key].to_i+ sequence_errors << draft_key if provided_sequence != current_sequence+ rescue StandardError+ # If we can't get sequence for some reason, skip validation for this draft+ # This maintains the same lenient behavior as the single deleteendif sequence_errors.any?diff --git a/app/controllers/finish_installation_controller.rb b/app/controllers/finish_installation_controller.rbindex 6f4dd95e064..f6d81afe07f 100644--- a/app/controllers/finish_installation_controller.rb+++ b/app/controllers/finish_installation_controller.rb@@ -84,21 +84,19 @@ class FinishInstallationController < ApplicationControllerenddef setup_discourse_id- begin- if find_allowed_emails.empty?- raise StandardError.new(I18n.t("finish_installation.discourse_id.no_allowed_emails"))- end- SiteSetting.enable_discourse_id = true- # Since we're setting up Discourse ID, disable local logins- SiteSetting.enable_local_logins = false- # Let ID set people's usernames- SiteSetting.auth_overrides_username = true- @discourse_id_enabled = true- @discourse_id_error = nil- rescue StandardError => e- @discourse_id_enabled = false- @discourse_id_error = e.message+ if find_allowed_emails.empty?+ raise StandardError.new(I18n.t("finish_installation.discourse_id.no_allowed_emails"))end+ SiteSetting.enable_discourse_id = true+ # Since we're setting up Discourse ID, disable local logins+ SiteSetting.enable_local_logins = false+ # Let ID set people's usernames+ SiteSetting.auth_overrides_username = true+ @discourse_id_enabled = true+ @discourse_id_error = nil+ rescue StandardError => e+ @discourse_id_enabled = false+ @discourse_id_error = e.messageenddef seed_admin_usersdiff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rbindex 8d7ac528dd9..18075bb6e8b 100644--- a/app/controllers/groups_controller.rb+++ b/app/controllers/groups_controller.rb@@ -423,19 +423,17 @@ class GroupsController < ApplicationControllerskip_email ||= params.key?(:notify_users) && !notifyemails.each do |email|- begin- Invite.generate(current_user, email:, group_ids:, skip_email:)- rescue RateLimiter::LimitExceeded => e- return(- render_json_error(- I18n.t(- "invite.rate_limit",- count: SiteSetting.max_invites_per_day,- time_left: e.time_left,- ),- )+ Invite.generate(current_user, email:, group_ids:, skip_email:)+ rescue RateLimiter::LimitExceeded => e+ return(+ render_json_error(+ I18n.t(+ "invite.rate_limit",+ count: SiteSetting.max_invites_per_day,+ time_left: e.time_left,+ ),)- end+ )endrender json: success_json.merge!(usernames: uniq_users.map(&:username), emails: emails)@@ -757,30 +755,28 @@ class GroupsController < ApplicationControllerendhijack do- begin- raise Discourse::InvalidParameters if params[:ssl_mode].blank?+ raise Discourse::InvalidParameters if params[:ssl_mode].blank?- settings.delete(:ssl_mode)+ settings.delete(:ssl_mode)- if Group.smtp_ssl_modes.values.exclude?(params[:ssl_mode].to_i)- raise Discourse::InvalidParameters.new("SSL mode must be valid")- end+ if Group.smtp_ssl_modes.values.exclude?(params[:ssl_mode].to_i)+ raise Discourse::InvalidParameters.new("SSL mode must be valid")+ end- final_settings =- settings.merge(- enable_tls: params[:ssl_mode].to_i == Group.smtp_ssl_modes[:ssl_tls],- enable_starttls_auto: params[:ssl_mode].to_i == Group.smtp_ssl_modes[:starttls],- ).permit(:host, :port, :username, :password, :enable_tls, :enable_starttls_auto, :debug)- EmailSettingsValidator.validate_as_user(- current_user,- "smtp",- **final_settings.to_h.symbolize_keys,- )+ final_settings =+ settings.merge(+ enable_tls: params[:ssl_mode].to_i == Group.smtp_ssl_modes[:ssl_tls],+ enable_starttls_auto: params[:ssl_mode].to_i == Group.smtp_ssl_modes[:starttls],+ ).permit(:host, :port, :username, :password, :enable_tls, :enable_starttls_auto, :debug)+ EmailSettingsValidator.validate_as_user(+ current_user,+ "smtp",+ **final_settings.to_h.symbolize_keys,+ )- render json: success_json- rescue *EmailSettingsExceptionHandler::EXPECTED_EXCEPTIONS, StandardError => err- render_json_error(EmailSettingsExceptionHandler.friendly_exception_message(err, email_host))- end+ render json: success_json+ rescue *EmailSettingsExceptionHandler::EXPECTED_EXCEPTIONS, StandardError => err+ render_json_error(EmailSettingsExceptionHandler.friendly_exception_message(err, email_host))endenddiff --git a/app/controllers/invites_controller.rb b/app/controllers/invites_controller.rbindex 5df6cf2ff79..fa55cef53da 100644--- a/app/controllers/invites_controller.rb+++ b/app/controllers/invites_controller.rb@@ -90,28 +90,26 @@ class InvitesController < ApplicationControllerfail = []emails.map do |email|- begin- invite =- Invite.generate(- current_user,- email: email,- description: params[:description],- domain: params[:domain],- skip_email: skip_email_param,- invited_by: current_user,- custom_message: params["custom_message"],- max_redemptions_allowed: params[:max_redemptions_allowed],- topic_id: topic&.id,- group_ids: groups&.map(&:id),- expires_at: params[:expires_at],- invite_to_topic: params[:invite_to_topic],- )- success.push({ email: email, invite: invite }) if invite- rescue Invite::UserExists => e- fail.push({ email: email, error: e.message })- rescue ActiveRecord::RecordInvalid => e- fail.push({ email: email, error: e.record.errors.full_messages.first })- end+ invite =+ Invite.generate(+ current_user,+ email: email,+ description: params[:description],+ domain: params[:domain],+ skip_email: skip_email_param,+ invited_by: current_user,+ custom_message: params["custom_message"],+ max_redemptions_allowed: params[:max_redemptions_allowed],+ topic_id: topic&.id,+ group_ids: groups&.map(&:id),+ expires_at: params[:expires_at],+ invite_to_topic: params[:invite_to_topic],+ )+ success.push({ email: email, invite: invite }) if invite+ rescue Invite::UserExists => e+ fail.push({ email: email, error: e.message })+ rescue ActiveRecord::RecordInvalid => e+ fail.push({ email: email, error: e.record.errors.full_messages.first })endrender json: {@@ -124,62 +122,59 @@ class InvitesController < ApplicationControllerenddef create- begin- if params[:topic_id].present?- topic = Topic.find_by(id: params[:topic_id])- raise Discourse::InvalidParameters.new(:topic_id) if topic.blank?- guardian.ensure_can_invite_to!(topic)- end+ if params[:topic_id].present?+ topic = Topic.find_by(id: params[:topic_id])+ raise Discourse::InvalidParameters.new(:topic_id) if topic.blank?+ guardian.ensure_can_invite_to!(topic)+ end- if params[:group_ids].present? || params[:group_names].present?- groups =- Group.lookup_groups(group_ids: params[:group_ids], group_names: params[:group_names])- end+ if params[:group_ids].present? || params[:group_names].present?+ groups = Group.lookup_groups(group_ids: params[:group_ids], group_names: params[:group_names])+ end- guardian.ensure_can_invite_to_forum!(groups)+ guardian.ensure_can_invite_to_forum!(groups)- if !groups_can_see_topic?(groups, topic)- editable_topic_groups = topic.category.groups.filter { |g| guardian.can_edit_group?(g) }- return(- render_json_error(- I18n.t("invite.requires_groups", groups: editable_topic_groups.pluck(:name).join(", ")),- )+ if !groups_can_see_topic?(groups, topic)+ editable_topic_groups = topic.category.groups.filter { |g| guardian.can_edit_group?(g) }+ return(+ render_json_error(+ I18n.t("invite.requires_groups", groups: editable_topic_groups.pluck(:name).join(", ")),)- end+ )+ end- invite =- Invite.generate(- current_user,- email: params[:email],- description: params[:description],- domain: params[:domain],- skip_email: skip_email_param,- invited_by: current_user,- custom_message: params[:custom_message],- max_redemptions_allowed: params[:max_redemptions_allowed],- topic_id: topic&.id,- group_ids: groups&.map(&:id),- expires_at: params[:expires_at],- invite_to_topic: params[:invite_to_topic],- )+ invite =+ Invite.generate(+ current_user,+ email: params[:email],+ description: params[:description],+ domain: params[:domain],+ skip_email: skip_email_param,+ invited_by: current_user,+ custom_message: params[:custom_message],+ max_redemptions_allowed: params[:max_redemptions_allowed],+ topic_id: topic&.id,+ group_ids: groups&.map(&:id),+ expires_at: params[:expires_at],+ invite_to_topic: params[:invite_to_topic],+ )- if invite.present?- render_serialized(- invite,- InviteSerializer,- scope: guardian,- root: nil,- show_emails: params.has_key?(:email),- show_warnings: true,- )- else- render json: failed_json, status: :unprocessable_entity- end- rescue Invite::UserExists => e- render_json_error(e.message)- rescue ActiveRecord::RecordInvalid => e- render_json_error(e.record.errors.full_messages.first)+ if invite.present?+ render_serialized(+ invite,+ InviteSerializer,+ scope: guardian,+ root: nil,+ show_emails: params.has_key?(:email),+ show_warnings: true,+ )+ else+ render json: failed_json, status: :unprocessable_entityend+ rescue Invite::UserExists => e+ render_json_error(e.message)+ rescue ActiveRecord::RecordInvalid => e+ render_json_error(e.record.errors.full_messages.first)enddef retrieve@@ -489,68 +484,66 @@ class InvitesController < ApplicationControllerguardian.ensure_can_bulk_invite_to_forum!hijack do- begin- file = params[:file] || params[:files].first-- csv_header = nil- invites = []- valid_columns = nil-- CSV.foreach(file.tempfile, encoding: "bom|utf-8") do |row|- # Try to extract a CSV header, if it exists- if csv_header.nil?- if row[0] == "email"- csv_header = row- valid_columns = Set.new(ALLOWED_BULK_INVITE_COLUMNS + UserField.pluck(:name))- next- else- csv_header = %w[email groups topic_id]- end- end-- if row[0].present?- invite =- csv_header- .zip(row)- .map- .to_h- .filter { |k, v| v.present? && (!valid_columns || valid_columns.include?(k)) }- invites.push(invite)+ file = params[:file] || params[:files].first++ csv_header = nil+ invites = []+ valid_columns = nil++ CSV.foreach(file.tempfile, encoding: "bom|utf-8") do |row|+ # Try to extract a CSV header, if it exists+ if csv_header.nil?+ if row[0] == "email"+ csv_header = row+ valid_columns = Set.new(ALLOWED_BULK_INVITE_COLUMNS + UserField.pluck(:name))+ next+ else+ csv_header = %w[email groups topic_id]end+ end- break if invites.count >= SiteSetting.max_bulk_invites+ if row[0].present?+ invite =+ csv_header+ .zip(row)+ .map+ .to_h+ .filter { |k, v| v.present? && (!valid_columns || valid_columns.include?(k)) }+ invites.push(invite)end- if invites.present?- custom_error =- DiscoursePluginRegistry.apply_modifier(:invite_bulk_csv_custom_error, nil, invites)+ break if invites.count >= SiteSetting.max_bulk_invites+ end- if custom_error.present?- return(- render json: failed_json.merge(errors: [custom_error]), status: :unprocessable_entity- )- end+ if invites.present?+ custom_error =+ DiscoursePluginRegistry.apply_modifier(:invite_bulk_csv_custom_error, nil, invites)- Jobs.enqueue(:bulk_invite, invites: invites, current_user_id: current_user.id)-- if invites.count >= SiteSetting.max_bulk_invites- render json:- failed_json.merge(- errors: [- I18n.t(- "bulk_invite.max_rows",- max_bulk_invites: SiteSetting.max_bulk_invites,- ),- ],- ),- status: :unprocessable_entity- else- render json: success_json- end- else- render json: failed_json.merge(errors: [I18n.t("bulk_invite.error")]),+ if custom_error.present?+ return(+ render json: failed_json.merge(errors: [custom_error]), status: :unprocessable_entity+ )+ end++ Jobs.enqueue(:bulk_invite, invites: invites, current_user_id: current_user.id)++ if invites.count >= SiteSetting.max_bulk_invites+ render json:+ failed_json.merge(+ errors: [+ I18n.t(+ "bulk_invite.max_rows",+ max_bulk_invites: SiteSetting.max_bulk_invites,+ ),+ ],+ ),status: :unprocessable_entity+ else+ render json: success_jsonend+ else+ render json: failed_json.merge(errors: [I18n.t("bulk_invite.error")]),+ status: :unprocessable_entityendendenddiff --git a/app/controllers/stylesheets_controller.rb b/app/controllers/stylesheets_controller.rbindex a5f9740613c..0f808f1bfcc 100644--- a/app/controllers/stylesheets_controller.rb+++ b/app/controllers/stylesheets_controller.rb@@ -105,9 +105,7 @@ class StylesheetsController < ApplicationControllerprivatedef read_file(location)- begin- File.read(location)- rescue Errno::ENOENT- end+ File.read(location)+ rescue Errno::ENOENTendenddiff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rbindex 748e1dc9736..cd680bfe619 100644--- a/app/controllers/tags_controller.rb+++ b/app/controllers/tags_controller.rb@@ -320,30 +320,28 @@ class TagsController < ::ApplicationControllerfile = params[:file] || params[:files].firsthijack do- begin- Tag.transaction do- CSV.foreach(file.tempfile) do |row|- if row.length > 2- raise Discourse::InvalidParameters.new(I18n.t("tags.upload_row_too_long"))- end-- tag_name = DiscourseTagging.clean_tag(row[0])- tag_group_name = row[1] || nil-- tag = Tag.find_by_name(tag_name) || Tag.create!(name: tag_name)-- if tag_group_name- tag_group =- TagGroup.find_by_name_insensitive(tag_group_name) ||- TagGroup.create!(name: tag_group_name)- tag.tag_groups << tag_group if tag.tag_groups.exclude?(tag_group)- end+ Tag.transaction do+ CSV.foreach(file.tempfile) do |row|+ if row.length > 2+ raise Discourse::InvalidParameters.new(I18n.t("tags.upload_row_too_long"))+ end++ tag_name = DiscourseTagging.clean_tag(row[0])+ tag_group_name = row[1] || nil++ tag = Tag.find_by_name(tag_name) || Tag.create!(name: tag_name)++ if tag_group_name+ tag_group =+ TagGroup.find_by_name_insensitive(tag_group_name) ||+ TagGroup.create!(name: tag_group_name)+ tag.tag_groups << tag_group if tag.tag_groups.exclude?(tag_group)endend- render json: success_json- rescue Discourse::InvalidParameters => e- render json: failed_json.merge(errors: [e.message]), status: :unprocessable_entityend+ render json: success_json+ rescue Discourse::InvalidParameters => e+ render json: failed_json.merge(errors: [e.message]), status: :unprocessable_entityendenddiff --git a/app/controllers/theme_javascripts_controller.rb b/app/controllers/theme_javascripts_controller.rbindex 3fa589d55ac..5434bd06167 100644--- a/app/controllers/theme_javascripts_controller.rb+++ b/app/controllers/theme_javascripts_controller.rb@@ -72,12 +72,10 @@ class ThemeJavascriptsController < ApplicationControllerdef last_modified@last_modified ||=- begin- if params[:action].to_s == "show_tests"- File.exist?(@cache_file) ? File.ctime(@cache_file) : nil- else- query.pick(:updated_at)- end+ if params[:action].to_s == "show_tests"+ File.exist?(@cache_file) ? File.ctime(@cache_file) : nil+ else+ query.pick(:updated_at)endenddiff --git a/app/controllers/uploads_controller.rb b/app/controllers/uploads_controller.rbindex 1759fa71d95..d0d4e3930bb 100644--- a/app/controllers/uploads_controller.rb+++ b/app/controllers/uploads_controller.rb@@ -68,26 +68,24 @@ class UploadsController < ApplicationController# note, atm hijack is processed in its own context and has not access to controller# longer term we may change thishijack do- begin- info =- UploadsController.create_upload(- current_user: me,- file:,- url:,- type:,- for_private_message:,- for_site_setting:,- site_setting_name:,- pasted:,- is_api:,- retain_hours:,- )- rescue => e- render json: failed_json.merge(message: e.message&.split("\n")&.first),- status: :unprocessable_entity- else- render json: UploadsController.serialize_upload(info), status: Upload === info ? 200 : 422- end+ info =+ UploadsController.create_upload(+ current_user: me,+ file:,+ url:,+ type:,+ for_private_message:,+ for_site_setting:,+ site_setting_name:,+ pasted:,+ is_api:,+ retain_hours:,+ )+ rescue => e+ render json: failed_json.merge(message: e.message&.split("\n")&.first),+ status: :unprocessable_entity+ else+ render json: UploadsController.serialize_upload(info), status: Upload === info ? 200 : 422endend@@ -117,26 +115,24 @@ class UploadsController < ApplicationControllerrequest.env.delete(Auth::DefaultCurrentUserProvider::CURRENT_USER_KEY)RailsMultisite::ConnectionManagement.with_connection(params[:site]) do |db|- begin- # current_user here refers to the user for the site that we are operating on- # using with_connection. If DB for the target site matches the current site- # for the request, then current_user will be the same as the request_site_current_user- return render_404 if SiteSetting.prevent_anons_from_downloading_files && current_user.nil?-- upload =- Upload.find_by(sha1: params[:sha]) ||- Upload.find_by(id: params[:id], url: request.env["PATH_INFO"])-- if upload.present?- if !Discourse.store.internal?- local_store = FileStore::LocalStore.new- return render_404 unless local_store.has_been_uploaded?(upload.url)- end-- send_file_local_upload(upload)- else- render_404+ # current_user here refers to the user for the site that we are operating on+ # using with_connection. If DB for the target site matches the current site+ # for the request, then current_user will be the same as the request_site_current_user+ return render_404 if SiteSetting.prevent_anons_from_downloading_files && current_user.nil?++ upload =+ Upload.find_by(sha1: params[:sha]) ||+ Upload.find_by(id: params[:id], url: request.env["PATH_INFO"])++ if upload.present?+ if !Discourse.store.internal?+ local_store = FileStore::LocalStore.new+ return render_404 unless local_store.has_been_uploaded?(upload.url)end++ send_file_local_upload(upload)+ else+ render_404endendensure@@ -392,15 +388,13 @@ class UploadsController < ApplicationControllerenddef create_direct_multipart_upload- begin- yield- rescue Aws::S3::Errors::ServiceError => err- message =- debug_upload_error(- err,- I18n.t("upload.create_multipart_failure", additional_detail: err.message),- )- raise ExternalUploadHelpers::ExternalUploadValidationError.new(message)- end+ yield+ rescue Aws::S3::Errors::ServiceError => err+ message =+ debug_upload_error(+ err,+ I18n.t("upload.create_multipart_failure", additional_detail: err.message),+ )+ raise ExternalUploadHelpers::ExternalUploadValidationError.new(message)endenddiff --git a/app/controllers/user_avatars_controller.rb b/app/controllers/user_avatars_controller.rbindex c0c4966b4a1..d0dc32c054d 100644--- a/app/controllers/user_avatars_controller.rb+++ b/app/controllers/user_avatars_controller.rb@@ -53,14 +53,12 @@ class UserAvatarsController < ApplicationControllerreturn render_blank if disable_proxy?hijack do- begin- proxy_avatar(- "https://avatars.discourse-cdn.com/#{params[:version]}/letter/#{params[:letter]}/#{params[:color]}/#{params[:size]}.png",- Time.new(1990, 01, 01),- )- rescue OpenURI::HTTPError- render_blank- end+ proxy_avatar(+ "https://avatars.discourse-cdn.com/#{params[:version]}/letter/#{params[:letter]}/#{params[:color]}/#{params[:size]}.png",+ Time.new(1990, 01, 01),+ )+ rescue OpenURI::HTTPError+ render_blankendenddiff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rbindex 338a3f643d0..589abc40af9 100644--- a/app/controllers/users_controller.rb+++ b/app/controllers/users_controller.rb@@ -2248,12 +2248,10 @@ class UsersController < ApplicationControllerallowed_actions = %w[show update destroy]http_verbs.any? do |verb|- begin- path = Rails.application.routes.recognize_path("/u/#{normalized_username}", method: verb)- allowed_actions.exclude?(path[:action])- rescue ActionController::RoutingError- false- end+ path = Rails.application.routes.recognize_path("/u/#{normalized_username}", method: verb)+ allowed_actions.exclude?(path[:action])+ rescue ActionController::RoutingError+ falseendenddiff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rbindex c49e29925b0..95c67502878 100644--- a/app/helpers/application_helper.rb+++ b/app/helpers/application_helper.rb@@ -457,32 +457,28 @@ module ApplicationHelperdef application_logo_url@application_logo_url ||=- begin- if mobile_view?- if dark_color_scheme? && SiteSetting.site_mobile_logo_dark_url.present?- SiteSetting.site_mobile_logo_dark_url- elsif SiteSetting.site_mobile_logo_url.present?- SiteSetting.site_mobile_logo_url- end+ if mobile_view?+ if dark_color_scheme? && SiteSetting.site_mobile_logo_dark_url.present?+ SiteSetting.site_mobile_logo_dark_url+ elsif SiteSetting.site_mobile_logo_url.present?+ SiteSetting.site_mobile_logo_url+ end+ else+ if dark_color_scheme? && SiteSetting.site_logo_dark_url.present?+ SiteSetting.site_logo_dark_urlelse- if dark_color_scheme? && SiteSetting.site_logo_dark_url.present?- SiteSetting.site_logo_dark_url- else- SiteSetting.site_logo_url- end+ SiteSetting.site_logo_urlendendenddef application_logo_dark_url@application_logo_dark_url ||=- begin- if dark_scheme_id != -1- if mobile_view? && SiteSetting.site_mobile_logo_dark_url != application_logo_url- SiteSetting.site_mobile_logo_dark_url- elsif !mobile_view? && SiteSetting.site_logo_dark_url != application_logo_url- SiteSetting.site_logo_dark_url- end+ if dark_scheme_id != -1+ if mobile_view? && SiteSetting.site_mobile_logo_dark_url != application_logo_url+ SiteSetting.site_mobile_logo_dark_url+ elsif !mobile_view? && SiteSetting.site_logo_dark_url != application_logo_url+ SiteSetting.site_logo_dark_urlendendend@@ -584,12 +580,10 @@ module ApplicationHelperDiscourse.cache.fetch("splash_screen_svg_#{upload.id}_#{upload.sha1}", expires_in: 1.day) do- begin- upload.content.presence- rescue StandardError => e- Discourse.warn_exception(e, message: "Failed to fetch splash screen logo SVG")- nil- end+ upload.content.presence+ rescue StandardError => e+ Discourse.warn_exception(e, message: "Failed to fetch splash screen logo SVG")+ nilendend@@ -665,14 +659,12 @@ module ApplicationHelperenddef topic_featured_link_domain(link)- begin- uri = UrlHelper.encode_and_parse(link)- uri = URI.parse("http://#{uri}") if uri.scheme.nil?- host = uri.host.downcase- host.start_with?("www.") ? host[4..-1] : host- rescue StandardError- ""- end+ uri = UrlHelper.encode_and_parse(link)+ uri = URI.parse("http://#{uri}") if uri.scheme.nil?+ host = uri.host.downcase+ host.start_with?("www.") ? host[4..-1] : host+ rescue StandardError+ ""enddef theme_iddiff --git a/app/jobs/base.rb b/app/jobs/base.rbindex 16fa6f1ccfc..abe32acac5c 100644--- a/app/jobs/base.rb+++ b/app/jobs/base.rb@@ -106,11 +106,9 @@ module Jobsenddef self.raw_log(message)- begin- logger << message- rescue => e- Discourse.warn_exception(e, message: "Exception encountered while logging Sidekiq job")- end+ logger << message+ rescue => e+ Discourse.warn_exception(e, message: "Exception encountered while logging Sidekiq job")end# For test environment only@@ -162,19 +160,17 @@ module Jobsinterval = interval.to_i@@interval_thread ||=Thread.new do- begin- loop do- sleep interval- mutex.synchronize do- @@active_jobs.each { |j| j.write_to_log if j.current_duration > interval }- end+ loop do+ sleep interval+ mutex.synchronize do+ @@active_jobs.each { |j| j.write_to_log if j.current_duration > interval }end- rescue Exception => e- Discourse.warn_exception(- e,- message: "Sidekiq interval logging thread terminated unexpectedly",- )end+ rescue Exception => e+ Discourse.warn_exception(+ e,+ message: "Sidekiq interval logging thread terminated unexpectedly",+ )endendend@@ -299,38 +295,36 @@ module Jobsexceptions = []dbs.each do |db|- begin- exception = {}+ exception = {}- RailsMultisite::ConnectionManagement.with_connection(db) do- job_instrumenter =- JobInstrumenter.new(job_class: self.class, opts: opts, db: db, jid: jid)+ RailsMultisite::ConnectionManagement.with_connection(db) do+ job_instrumenter =+ JobInstrumenter.new(job_class: self.class, opts: opts, db: db, jid: jid)+ begin+ I18n.locale =+ SiteSetting.default_locale || SiteSettings::DefaultsProvider::DEFAULT_LOCALE+ I18n.ensure_all_loaded!begin- I18n.locale =- SiteSetting.default_locale || SiteSettings::DefaultsProvider::DEFAULT_LOCALE- I18n.ensure_all_loaded!- begin- logster_env = {}- Logster.add_to_env(logster_env, :job, self.class.to_s)- Logster.add_to_env(logster_env, :db, db)- Thread.current[Logster::Logger::LOGSTER_ENV] = logster_env-- execute(opts)- rescue => e- exception[:ex] = e- exception[:other] = { problem_db: db }- end+ logster_env = {}+ Logster.add_to_env(logster_env, :job, self.class.to_s)+ Logster.add_to_env(logster_env, :db, db)+ Thread.current[Logster::Logger::LOGSTER_ENV] = logster_env++ execute(opts)rescue => eexception[:ex] = e- exception[:message] = "While establishing database connection to #{db}"exception[:other] = { problem_db: db }- ensure- job_instrumenter.stop(exception: exception)end+ rescue => e+ exception[:ex] = e+ exception[:message] = "While establishing database connection to #{db}"+ exception[:other] = { problem_db: db }+ ensure+ job_instrumenter.stop(exception: exception)end-- exceptions << exception unless exception.empty?end++ exceptions << exception unless exception.empty?endThread.current[Logster::Logger::LOGSTER_ENV] = nildiff --git a/app/jobs/onceoff/grant_onebox.rb b/app/jobs/onceoff/grant_onebox.rbindex 5eb6ec0538f..c74942e0590 100644--- a/app/jobs/onceoff/grant_onebox.rb+++ b/app/jobs/onceoff/grant_onebox.rb@@ -16,16 +16,14 @@ module Jobs.where("raw LIKE '%http%'").find_in_batches do |group|group.each do |p|- begin- # Note we can't use `p.cooked` here because oneboxes have been cooked out- cooked = PrettyText.cook(p.raw)- doc = Nokogiri::HTML5.fragment(cooked)- if doc.search("a.onebox").size > 0- to_award[p.user_id] ||= { post_id: p.id, created_at: p.created_at }- end- rescue StandardError- nil # if there is a problem cooking we don't care+ # Note we can't use `p.cooked` here because oneboxes have been cooked out+ cooked = PrettyText.cook(p.raw)+ doc = Nokogiri::HTML5.fragment(cooked)+ if doc.search("a.onebox").size > 0+ to_award[p.user_id] ||= { post_id: p.id, created_at: p.created_at }end+ rescue StandardError+ nil # if there is a problem cooking we don't careendenddiff --git a/app/jobs/regular/export_user_archive.rb b/app/jobs/regular/export_user_archive.rbindex a5035f0e4b7..ab7f96f7686 100644--- a/app/jobs/regular/export_user_archive.rb+++ b/app/jobs/regular/export_user_archive.rb@@ -187,16 +187,14 @@ module Jobsenddef provide_results(user_export, zip_filename, export_title, args)- begin- create_upload_for_user(user_export, zip_filename)- ensure- post = notify_user(user_export, export_title)-- if user_export.present? && post.present?- topic = post.topic- user_export.update_columns(topic_id: topic.id)- topic.update_status("closed", true, Discourse.system_user)- end+ create_upload_for_user(user_export, zip_filename)+ ensure+ post = notify_user(user_export, export_title)++ if user_export.present? && post.present?+ topic = post.topic+ user_export.update_columns(topic_id: topic.id)+ topic.update_status("closed", true, Discourse.system_user)endenddiff --git a/app/jobs/regular/sync_access_control_for_uploads.rb b/app/jobs/regular/sync_access_control_for_uploads.rbindex 696a2e45417..e31bca69e00 100644--- a/app/jobs/regular/sync_access_control_for_uploads.rb+++ b/app/jobs/regular/sync_access_control_for_uploads.rb@@ -15,18 +15,16 @@ module Jobs.where(id: args[:upload_ids]).find_in_batches do |uploads|uploads.each do |upload|- begin- Discourse.store.update_upload_access_control(upload, remove_existing_acl: true)- rescue => err- Discourse.warn_exception(- err,- message: "Failed to update upload access control",- env: {- upload_id: upload.id,- filename: upload.original_filename,- },- )- end+ Discourse.store.update_upload_access_control(upload, remove_existing_acl: true)+ rescue => err+ Discourse.warn_exception(+ err,+ message: "Failed to update upload access control",+ env: {+ upload_id: upload.id,+ filename: upload.original_filename,+ },+ )endendenddiff --git a/app/jobs/scheduled/clean_up_inactive_users.rb b/app/jobs/scheduled/clean_up_inactive_users.rbindex 183a5f44600..6f70048194f 100644--- a/app/jobs/scheduled/clean_up_inactive_users.rb+++ b/app/jobs/scheduled/clean_up_inactive_users.rb@@ -33,24 +33,22 @@ module JobsUser.transaction doids.each do |id|- begin- user = User.find_by(id: id)- next unless user- destroyer.destroy(- user,- transaction: false,- context: I18n.t("user.destroy_reasons.inactive_user"),- )- rescue => e- Discourse.handle_job_exception(- e,- message: "Cleaning up inactive users",- extra: {- user_id: id,- },- )- raise e- end+ user = User.find_by(id: id)+ next unless user+ destroyer.destroy(+ user,+ transaction: false,+ context: I18n.t("user.destroy_reasons.inactive_user"),+ )+ rescue => e+ Discourse.handle_job_exception(+ e,+ message: "Cleaning up inactive users",+ extra: {+ user_id: id,+ },+ )+ raise eendendenddiff --git a/app/jobs/scheduled/clean_up_unused_staged_users.rb b/app/jobs/scheduled/clean_up_unused_staged_users.rbindex 301de4efeaf..20bafeac391 100644--- a/app/jobs/scheduled/clean_up_unused_staged_users.rb+++ b/app/jobs/scheduled/clean_up_unused_staged_users.rb@@ -16,17 +16,15 @@ module Jobs.where(staged: true, admin: false, moderator: false).where("users.created_at < ?", clean_up_after_days.days.ago).find_each do |user|- begin- destroyer.destroy(user, context: I18n.t("user.destroy_reasons.unused_staged_user"))- rescue => e- Discourse.handle_job_exception(- e,- message: "Cleaning up unused staged user",- extra: {- user_id: user.id,- },- )- end+ destroyer.destroy(user, context: I18n.t("user.destroy_reasons.unused_staged_user"))+ rescue => e+ Discourse.handle_job_exception(+ e,+ message: "Cleaning up unused staged user",+ extra: {+ user_id: user.id,+ },+ )endendenddiff --git a/app/jobs/scheduled/process_user_notification_schedules.rb b/app/jobs/scheduled/process_user_notification_schedules.rbindex 1f8bbe4f839..06267e5fb51 100644--- a/app/jobs/scheduled/process_user_notification_schedules.rb+++ b/app/jobs/scheduled/process_user_notification_schedules.rb@@ -9,14 +9,12 @@ module Jobs.enabled.includes(:user).each do |schedule|- begin- schedule.create_do_not_disturb_timings- rescue => e- Discourse.warn_exception(- e,- message: "Failed to process user_notification_schedule with ID #{schedule.id}",- )- end+ schedule.create_do_not_disturb_timings+ rescue => e+ Discourse.warn_exception(+ e,+ message: "Failed to process user_notification_schedule with ID #{schedule.id}",+ )endendenddiff --git a/app/jobs/scheduled/topic_timer_enqueuer.rb b/app/jobs/scheduled/topic_timer_enqueuer.rbindex 13322184e66..ca4d8180def 100644--- a/app/jobs/scheduled/topic_timer_enqueuer.rb+++ b/app/jobs/scheduled/topic_timer_enqueuer.rb@@ -14,14 +14,13 @@ module JobsTopicTimer.pending_timers.find_each do |timer|# the typed job may not enqueue if it has already# been scheduled with enqueue_at- begin- timer.enqueue_typed_job- rescue => err- Discourse.warn_exception(- err,- message: "Error when attempting to enqueue topic timer job for timer #{timer.id}",- )- end++ timer.enqueue_typed_job+ rescue => err+ Discourse.warn_exception(+ err,+ message: "Error when attempting to enqueue topic timer job for timer #{timer.id}",+ )endendenddiff --git a/app/models/bookmark.rb b/app/models/bookmark.rbindex dbee454ebd4..f7efb6a7293 100644--- a/app/models/bookmark.rb+++ b/app/models/bookmark.rb@@ -11,14 +11,12 @@ class Bookmark < ActiveRecord::Baseenddef self.registered_bookmarkable_from_type(type)- begin- resolved_type = Bookmark.polymorphic_class_for(type).name- Bookmark.registered_bookmarkables.find { |bm| bm.model.name == resolved_type }+ resolved_type = Bookmark.polymorphic_class_for(type).name+ Bookmark.registered_bookmarkables.find { |bm| bm.model.name == resolved_type }- # If the class cannot be found from the provided type using polymorphic_class_for,- # then the type is not valid and thus there will not be any registered bookmarkable.- rescue NameError- end+ # If the class cannot be found from the provided type using polymorphic_class_for,+ # then the type is not valid and thus there will not be any registered bookmarkable.+ rescue NameErrorenddef self.valid_bookmarkable_typesdiff --git a/app/models/draft.rb b/app/models/draft.rbindex d3705221bbe..87e604462cd 100644--- a/app/models/draft.rb+++ b/app/models/draft.rb@@ -150,11 +150,9 @@ class Draft < ActiveRecord::Baseenddef parsed_data- begin- JSON.parse(data)- rescue JSON::ParserError- {}- end+ JSON.parse(data)+ rescue JSON::ParserError+ {}enddef topic_iddiff --git a/app/models/global_setting.rb b/app/models/global_setting.rbindex fce1c211714..1d7cb57c04d 100644--- a/app/models/global_setting.rb+++ b/app/models/global_setting.rb@@ -98,13 +98,11 @@ class GlobalSettingdef self.use_s3?(@use_s3 ||=- begin- if s3_bucket && s3_region &&- (s3_use_iam_profile || (s3_access_key_id && s3_secret_access_key))- :true- else- :false- end+ if s3_bucket && s3_region &&+ (s3_use_iam_profile || (s3_access_key_id && s3_secret_access_key))+ :true+ else+ :falseend) == :trueenddiff --git a/app/models/post.rb b/app/models/post.rbindex 22cf285253d..1162e38a187 100644--- a/app/models/post.rb+++ b/app/models/post.rb@@ -828,32 +828,30 @@ class Post < ActiveRecord::Base.limit(limit).pluck(:id).each do |id|- begin- break if !limiter.can_perform?+ break if !limiter.can_perform?- post = Post.find(id)- post.rebake!(priority: priority)+ post = Post.find(id)+ post.rebake!(priority: priority)- begin- limiter.performed! if rate_limiter- rescue RateLimiter::LimitExceeded- break- end- rescue => e- problems << { post: post, ex: e }+ begin+ limiter.performed! if rate_limiter+ rescue RateLimiter::LimitExceeded+ break+ end+ rescue => e+ problems << { post: post, ex: e }- attempts = post.custom_fields["rebake_attempts"].to_i+ attempts = post.custom_fields["rebake_attempts"].to_i- if attempts > 3- post.update_columns(baked_version: BAKED_VERSION)- Discourse.warn_exception(- e,- message: "Can not rebake post# #{post.id} after 3 attempts, giving up",- )- else- post.custom_fields["rebake_attempts"] = attempts + 1- post.save_custom_fields- end+ if attempts > 3+ post.update_columns(baked_version: BAKED_VERSION)+ Discourse.warn_exception(+ e,+ message: "Can not rebake post# #{post.id} after 3 attempts, giving up",+ )+ else+ post.custom_fields["rebake_attempts"] = attempts + 1+ post.save_custom_fieldsendendproblemsdiff --git a/app/models/post_analyzer.rb b/app/models/post_analyzer.rbindex a3a8d2e7e59..a072c8c61d9 100644--- a/app/models/post_analyzer.rb+++ b/app/models/post_analyzer.rb@@ -104,14 +104,12 @@ class PostAnalyzer@linked_hosts = {}all_links.each do |u|- begin- uri = self.class.parse_uri_rfc2396(u)- host = uri.host- @linked_hosts[host] ||= 1 unless host.nil?- rescue URI::Error- # An invalid URI does not count as a host- next- end+ uri = self.class.parse_uri_rfc2396(u)+ host = uri.host+ @linked_hosts[host] ||= 1 unless host.nil?+ rescue URI::Error+ # An invalid URI does not count as a host+ nextend@linked_hostsdiff --git a/app/models/post_mover.rb b/app/models/post_mover.rbindex 161738a3c29..12de911cd16 100644--- a/app/models/post_mover.rb+++ b/app/models/post_mover.rb@@ -722,14 +722,12 @@ class PostMoverdef posts@posts ||=- begin- Post- .where(topic: @original_topic, id: post_ids)- .where.not(post_type: Post.types[:small_action])- .where.not(raw: "")- .order(:created_at)- .tap { |posts| raise Discourse::InvalidParameters.new(:post_ids) if posts.empty? }- end+ Post+ .where(topic: @original_topic, id: post_ids)+ .where.not(post_type: Post.types[:small_action])+ .where.not(raw: "")+ .order(:created_at)+ .tap { |posts| raise Discourse::InvalidParameters.new(:post_ids) if posts.empty? }enddef update_last_post_statsdiff --git a/app/models/site_setting.rb b/app/models/site_setting.rbindex 62763180c34..29634a0c044 100644--- a/app/models/site_setting.rb+++ b/app/models/site_setting.rb@@ -241,28 +241,28 @@ class SiteSetting < ActiveRecord::Basecurrent_db = RailsMultisite::ConnectionManagement.current_db@blocked_attachment_content_types_regex ||= {}- @blocked_attachment_content_types_regex[current_db] ||= begin- Regexp.union(SiteSetting.blocked_attachment_content_types.split("|"))- end+ @blocked_attachment_content_types_regex[current_db] ||= Regexp.union(+ SiteSetting.blocked_attachment_content_types.split("|"),+ )enddef self.blocked_attachment_filenames_regexcurrent_db = RailsMultisite::ConnectionManagement.current_db@blocked_attachment_filenames_regex ||= {}- @blocked_attachment_filenames_regex[current_db] ||= begin- Regexp.union(SiteSetting.blocked_attachment_filenames.split("|"))- end+ @blocked_attachment_filenames_regex[current_db] ||= Regexp.union(+ SiteSetting.blocked_attachment_filenames.split("|"),+ )enddef self.allowed_unicode_username_characters_regexcurrent_db = RailsMultisite::ConnectionManagement.current_db@allowed_unicode_username_regex ||= {}- @allowed_unicode_username_regex[current_db] ||= begin- if SiteSetting.allowed_unicode_username_characters.present?- Regexp.new(SiteSetting.allowed_unicode_username_characters)- end+ @allowed_unicode_username_regex[+ current_db+ ] ||= if SiteSetting.allowed_unicode_username_characters.present?+ Regexp.new(SiteSetting.allowed_unicode_username_characters)endenddiff --git a/app/models/theme_field.rb b/app/models/theme_field.rbindex da08fe71957..bb686aa7e4b 100644--- a/app/models/theme_field.rb+++ b/app/models/theme_field.rb@@ -208,14 +208,12 @@ class ThemeField < ActiveRecord::Basefallback_data =fallback_fields.each_with_index.map do |field, index|- begin- field.raw_translation_data(internal: internal)- rescue ThemeTranslationParser::InvalidYaml- # If this is the locale with the error, raise it.- # If not, let the other theme_field raise the error when it processes itself- raise if field.id == id- {}- end+ field.raw_translation_data(internal: internal)+ rescue ThemeTranslationParser::InvalidYaml+ # If this is the locale with the error, raise it.+ # If not, let the other theme_field raise the error when it processes itself+ raise if field.id == id+ {}end# TODO: Deduplicate the fallback data in the same way as JSLocaleHelper#load_translations_merged@@ -678,21 +676,19 @@ class ThemeField < ActiveRecord::Baseenddef upsert_svg_sprite!- begin- content = upload.content- rescue => e- Discourse.warn_exception(e, message: "Failed to fetch svg sprite for theme field #{id}")+ content = upload.content+ rescue => e+ Discourse.warn_exception(e, message: "Failed to fetch svg sprite for theme field #{id}")+ else+ if content.length > SvgSprite::MAX_THEME_SPRITE_SIZE+ Rails.logger.warn(+ "can't store theme svg sprite for theme #{theme_id} and upload #{upload_id}, sprite too big",+ )else- if content.length > SvgSprite::MAX_THEME_SPRITE_SIZE- Rails.logger.warn(- "can't store theme svg sprite for theme #{theme_id} and upload #{upload_id}, sprite too big",- )- else- ThemeSvgSprite.upsert(- { theme_id: theme_id, upload_id: upload_id, sprite: content },- unique_by: :theme_id,- )- end+ ThemeSvgSprite.upsert(+ { theme_id: theme_id, upload_id: upload_id, sprite: content },+ unique_by: :theme_id,+ )endenddiff --git a/app/models/topic_link.rb b/app/models/topic_link.rbindex b84a19dac01..83086cfb883 100644--- a/app/models/topic_link.rb+++ b/app/models/topic_link.rb@@ -155,15 +155,13 @@ class TopicLink < ActiveRecord::Base.uniq { |_, p| p }.each do |link, parsed|TopicLink.transaction do- begin- url, reflected_id = self.ensure_entry_for(post, link, parsed)- current_urls << url unless url.nil?- reflected_ids << reflected_id unless reflected_id.nil?- rescue URI::Error- # if the URI is invalid, don't store it.- rescue ActionController::RoutingError- # If we can't find the route, no big deal- end+ url, reflected_id = self.ensure_entry_for(post, link, parsed)+ current_urls << url unless url.nil?+ reflected_ids << reflected_id unless reflected_id.nil?+ rescue URI::Error+ # if the URI is invalid, don't store it.+ rescue ActionController::RoutingError+ # If we can't find the route, no big dealendenddiff --git a/app/models/topic_list.rb b/app/models/topic_list.rbindex cc810d51b85..f6222be384d 100644--- a/app/models/topic_list.rb+++ b/app/models/topic_list.rb@@ -179,12 +179,10 @@ class TopicListdef category_user_lookup@category_user_lookup ||=- begin- if @current_user- CategoryUser.lookup_for(@current_user, @topics.map(&:category_id).uniq)- else- []- end+ if @current_user+ CategoryUser.lookup_for(@current_user, @topics.map(&:category_id).uniq)+ else+ []endendenddiff --git a/app/models/upload.rb b/app/models/upload.rbindex 60c5c2ebd44..83446d5fb6c 100644--- a/app/models/upload.rb+++ b/app/models/upload.rb@@ -559,93 +559,87 @@ class Upload < ActiveRecord::Baseremap_scope = nilscope.each do |upload|- begin- # keep track of the url- previous_url = upload.url.dup- # where is the file currently stored?- external = previous_url =~ %r{\A//}- # download if external- if external- url = SiteSetting.scheme + ":" + previous_url-- begin- retries ||= 0-- file =- FileHelper.download(- url,- max_file_size: max_file_size_kb,- tmp_file_name: "discourse",- follow_redirect: true,- )- rescue OpenURI::HTTPError- retry if (retries += 1) < 1- next- end-- path = file.path- else- path = local_store.path_for(upload)- end- # compute SHA if missing- upload.sha1 = Upload.generate_digest(path) if upload.sha1.blank?-- # store to new location & update the filesize- File.open(path) do |f|- upload.url = Discourse.store.store_upload(f, upload)- upload.filesize = f.size- upload.save!(validate: false)+ # keep track of the url+ previous_url = upload.url.dup+ # where is the file currently stored?+ external = previous_url =~ %r{\A//}+ # download if external+ if external+ url = SiteSetting.scheme + ":" + previous_url++ begin+ retries ||= 0++ file =+ FileHelper.download(+ url,+ max_file_size: max_file_size_kb,+ tmp_file_name: "discourse",+ follow_redirect: true,+ )+ rescue OpenURI::HTTPError+ retry if (retries += 1) < 1+ nextend- # remap the URLs- DbHelper.remap(UrlHelper.absolute(previous_url), upload.url) unless external-- DbHelper.remap(- previous_url,- upload.url,- excluded_tables: %w[- posts- post_search_data- incoming_emails- notifications- single_sign_on_records- stylesheet_cache- topic_search_data- users- user_emails- draft_sequences- optimized_images- ],- )- remap_scope ||=- begin- Post- .with_deleted- .where(- "raw ~ '/uploads/#{db}/\\d+/' OR raw ~ '/uploads/#{db}/original/(\\d|[a-z])/'",- )- .select(:id, :raw, :cooked)- .all- end-- remap_scope.each do |post|- post.raw.gsub!(previous_url, upload.url)- post.cooked.gsub!(previous_url, upload.url)- if post.changed?- Post.with_deleted.where(id: post.id).update_all(raw: post.raw, cooked: post.cooked)- end- end+ path = file.path+ else+ path = local_store.path_for(upload)+ end+ # compute SHA if missing+ upload.sha1 = Upload.generate_digest(path) if upload.sha1.blank?++ # store to new location & update the filesize+ File.open(path) do |f|+ upload.url = Discourse.store.store_upload(f, upload)+ upload.filesize = f.size+ upload.save!(validate: false)+ end+ # remap the URLs+ DbHelper.remap(UrlHelper.absolute(previous_url), upload.url) unless external++ DbHelper.remap(+ previous_url,+ upload.url,+ excluded_tables: %w[+ posts+ post_search_data+ incoming_emails+ notifications+ single_sign_on_records+ stylesheet_cache+ topic_search_data+ users+ user_emails+ draft_sequences+ optimized_images+ ],+ )- upload.optimized_images.find_each(&:destroy!)- upload.rebake_posts_on_old_scheme- # remove the old file (when local)- FileUtils.rm(path, force: true) unless external- rescue => e- problems << { upload: upload, ex: e }- ensure- file&.unlink- file&.close+ remap_scope ||=+ Post+ .with_deleted+ .where("raw ~ '/uploads/#{db}/\\d+/' OR raw ~ '/uploads/#{db}/original/(\\d|[a-z])/'")+ .select(:id, :raw, :cooked)+ .all++ remap_scope.each do |post|+ post.raw.gsub!(previous_url, upload.url)+ post.cooked.gsub!(previous_url, upload.url)+ if post.changed?+ Post.with_deleted.where(id: post.id).update_all(raw: post.raw, cooked: post.cooked)+ endend++ upload.optimized_images.find_each(&:destroy!)+ upload.rebake_posts_on_old_scheme+ # remove the old file (when local)+ FileUtils.rm(path, force: true) unless external+ rescue => e+ problems << { upload: upload, ex: e }+ ensure+ file&.unlink+ file&.closeendendenddiff --git a/app/models/user.rb b/app/models/user.rbindex c2e75a5a9f6..7b2daf1f646 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -2206,11 +2206,9 @@ class User < ActiveRecord::Base.where("user_histories.id IS NULL").limit(200).find_each do |user|- begin- destroyer.destroy(user, context: I18n.t(:purge_reason))- rescue Discourse::InvalidAccess- # keep going- end+ destroyer.destroy(user, context: I18n.t(:purge_reason))+ rescue Discourse::InvalidAccess+ # keep goingendenddiff --git a/app/models/user_action.rb b/app/models/user_action.rbindex 793cc8fc54c..90714e8ce0d 100644--- a/app/models/user_action.rb+++ b/app/models/user_action.rb@@ -274,45 +274,43 @@ class UserAction < ActiveRecord::Baserequire_parameters(hash, *required_parameters)transaction(requires_new: true) do- begin- # TODO there are conditions when this is called and user_id was already rolled back and is invalid.+ # TODO there are conditions when this is called and user_id was already rolled back and is invalid.- # protect against dupes, for some reason this is failing in some cases- action = self.find_by(hash.select { |k, _| required_parameters.include?(k) })- return action if action+ # protect against dupes, for some reason this is failing in some cases+ action = self.find_by(hash.select { |k, _| required_parameters.include?(k) })+ return action if action- action = self.new(hash)+ action = self.new(hash)- action.created_at = hash[:created_at] if hash[:created_at]- action.save!+ action.created_at = hash[:created_at] if hash[:created_at]+ action.save!- user_id = hash[:user_id]+ user_id = hash[:user_id]- topic = Topic.includes(:category).find_by(id: hash[:target_topic_id])+ topic = Topic.includes(:category).find_by(id: hash[:target_topic_id])- update_like_count(user_id, hash[:action_type], 1) if topic && !topic.private_message?+ update_like_count(user_id, hash[:action_type], 1) if topic && !topic.private_message?- user_ids = user_id != action.acting_user_id ? [user_id] : nil+ user_ids = user_id != action.acting_user_id ? [user_id] : nil- group_ids = nil- if topic&.category&.read_restricted- group_ids = [Group::AUTO_GROUPS[:admins]] | topic.category.groups.pluck("groups.id")- end-- if action.user && (user_ids.present? || group_ids.present?)- MessageBus.publish(- "/u/#{action.user.username_lower}",- action.id,- user_ids: user_ids,- group_ids: group_ids,- )- end+ group_ids = nil+ if topic&.category&.read_restricted+ group_ids = [Group::AUTO_GROUPS[:admins]] | topic.category.groups.pluck("groups.id")+ end- action- rescue ActiveRecord::RecordNotUnique- # can happen, don't care already logged- raise ActiveRecord::Rollback+ if action.user && (user_ids.present? || group_ids.present?)+ MessageBus.publish(+ "/u/#{action.user.username_lower}",+ action.id,+ user_ids: user_ids,+ group_ids: group_ids,+ )end++ action+ rescue ActiveRecord::RecordNotUnique+ # can happen, don't care already logged+ raise ActiveRecord::Rollbackendenddiff --git a/app/models/user_avatar.rb b/app/models/user_avatar.rbindex 9f81c4c97a9..2b40ef99272 100644--- a/app/models/user_avatar.rb+++ b/app/models/user_avatar.rb@@ -27,61 +27,59 @@ class UserAvatar < ActiveRecord::Basedef update_gravatar!DistributedMutex.synchronize("update_gravatar_#{user_id}") do- begin- self.update!(last_gravatar_download_attempt: Time.zone.now)+ self.update!(last_gravatar_download_attempt: Time.zone.now)- max = Discourse.avatar_sizes.max+ max = Discourse.avatar_sizes.max- # The user could be deleted before this executes- return if user.blank? || user.primary_email.blank?+ # The user could be deleted before this executes+ return if user.blank? || user.primary_email.blank?- email_hash = @@custom_user_gravatar_email_hash[user_id] || user.email_hash- gravatar_url =- "https://#{SiteSetting.gravatar_base_url}/avatar/#{email_hash}.png?s=#{max}&d=404&reset_cache=#{SecureRandom.urlsafe_base64(5)}"+ email_hash = @@custom_user_gravatar_email_hash[user_id] || user.email_hash+ gravatar_url =+ "https://#{SiteSetting.gravatar_base_url}/avatar/#{email_hash}.png?s=#{max}&d=404&reset_cache=#{SecureRandom.urlsafe_base64(5)}"- if SiteSetting.verbose_upload_logging- Rails.logger.warn("Verbose Upload Logging: Downloading gravatar from #{gravatar_url}")- end+ if SiteSetting.verbose_upload_logging+ Rails.logger.warn("Verbose Upload Logging: Downloading gravatar from #{gravatar_url}")+ end- # follow redirects in case gravatar change rules on us- tempfile =- FileHelper.download(- gravatar_url,- max_file_size: SiteSetting.max_image_size_kb.kilobytes,- tmp_file_name: "gravatar",- skip_rate_limit: true,- verbose: false,- follow_redirect: true,- )-- if tempfile- ext = File.extname(tempfile)- ext = ".png" if ext.blank?-- upload =- UploadCreator.new(- tempfile,- "gravatar#{ext}",- origin: gravatar_url,- type: "avatar",- for_gravatar: true,- ).create_for(user_id)-- if gravatar_upload_id != upload.id- User.transaction do- if gravatar_upload_id && user.uploaded_avatar_id == gravatar_upload_id- user.update!(uploaded_avatar_id: upload.id)- end-- self.update!(gravatar_upload: upload)+ # follow redirects in case gravatar change rules on us+ tempfile =+ FileHelper.download(+ gravatar_url,+ max_file_size: SiteSetting.max_image_size_kb.kilobytes,+ tmp_file_name: "gravatar",+ skip_rate_limit: true,+ verbose: false,+ follow_redirect: true,+ )++ if tempfile+ ext = File.extname(tempfile)+ ext = ".png" if ext.blank?++ upload =+ UploadCreator.new(+ tempfile,+ "gravatar#{ext}",+ origin: gravatar_url,+ type: "avatar",+ for_gravatar: true,+ ).create_for(user_id)++ if gravatar_upload_id != upload.id+ User.transaction do+ if gravatar_upload_id && user.uploaded_avatar_id == gravatar_upload_id+ user.update!(uploaded_avatar_id: upload.id)end++ self.update!(gravatar_upload: upload)endend- rescue OpenURI::HTTPError => e- raise e if e.io&.status&.[](0).to_i != 404- ensure- tempfile&.close!end+ rescue OpenURI::HTTPError => e+ raise e if e.io&.status&.[](0).to_i != 404+ ensure+ tempfile&.close!endend@@ -199,14 +197,12 @@ class UserAvatar < ActiveRecord::Basewarnings_reported = 0ids.each do |id|- begin- OptimizedImage.find(id).destroy!- rescue ActiveRecord::RecordNotFound- rescue => e- if warnings_reported < 10- Discourse.warn_exception(e, message: "Failed to remove optimized image")- warnings_reported += 1- end+ OptimizedImage.find(id).destroy!+ rescue ActiveRecord::RecordNotFound+ rescue => e+ if warnings_reported < 10+ Discourse.warn_exception(e, message: "Failed to remove optimized image")+ warnings_reported += 1endendenddiff --git a/app/models/user_export.rb b/app/models/user_export.rbindex 00917b9e70f..57b91258c2f 100644--- a/app/models/user_export.rb+++ b/app/models/user_export.rb@@ -20,14 +20,12 @@ class UserExport < ActiveRecord::Base.where("created_at < ?", DESTROY_CREATED_BEFORE.ago).find_each do |user_export|UserExport.transaction do- begin- Post.where(topic_id: user_export.topic_id).find_each { |p| p.destroy! }- user_export.destroy!- rescue => e- Rails.logger.warn(- "Failed to remove user_export record with id #{user_export.id}: #{e.message}\n#{e.backtrace.join("\n")}",- )- end+ Post.where(topic_id: user_export.topic_id).find_each { |p| p.destroy! }+ user_export.destroy!+ rescue => e+ Rails.logger.warn(+ "Failed to remove user_export record with id #{user_export.id}: #{e.message}\n#{e.backtrace.join("\n")}",+ )endendenddiff --git a/app/models/user_profile.rb b/app/models/user_profile.rbindex 69081db6fde..fffd274d881 100644--- a/app/models/user_profile.rb+++ b/app/models/user_profile.rb@@ -88,11 +88,9 @@ class UserProfile < ActiveRecord::Base.where("bio_cooked_version IS NULL OR bio_cooked_version < ?", BAKED_VERSION).limit(limit).each do |p|- begin- p.rebake!- rescue => e- problems << { profile: p, ex: e }- end+ p.rebake!+ rescue => e+ problems << { profile: p, ex: e }endproblemsenddiff --git a/app/serializers/post_serializer.rb b/app/serializers/post_serializer.rbindex 011f54523ea..76b4d731e3b 100644--- a/app/serializers/post_serializer.rb+++ b/app/serializers/post_serializer.rb@@ -177,12 +177,10 @@ class PostSerializer < BasicPostSerializerdef include_group_moderator?@group_moderator ||=- begin- if @topic_view- @topic_view.category_group_moderator_user_ids.include?(object.user_id)- else- object&.user&.guardian&.is_category_group_moderator?(object&.topic&.category)- end+ if @topic_view+ @topic_view.category_group_moderator_user_ids.include?(object.user_id)+ else+ object&.user&.guardian&.is_category_group_moderator?(object&.topic&.category)endenddiff --git a/app/serializers/post_stream_serializer_mixin.rb b/app/serializers/post_stream_serializer_mixin.rbindex f6ef79a25c0..e3f84a6de19 100644--- a/app/serializers/post_stream_serializer_mixin.rb+++ b/app/serializers/post_stream_serializer_mixin.rb@@ -56,18 +56,16 @@ module PostStreamSerializerMixindef posts@posts ||=- begin- (object.posts || []).map do |post|- post.topic = object.topic+ (object.posts || []).map do |post|+ post.topic = object.topic- serializer = PostSerializer.new(post, scope: scope, root: false)- serializer.add_raw = true if @options[:include_raw]- serializer.topic_view = object+ serializer = PostSerializer.new(post, scope: scope, root: false)+ serializer.add_raw = true if @options[:include_raw]+ serializer.topic_view = object- serializer.notice_created_by_users = post_notice_created_by_users if scope.is_staff?+ serializer.notice_created_by_users = post_notice_created_by_users if scope.is_staff?- serializer.as_json- end+ serializer.as_jsonendenddiff --git a/app/services/destroy_task.rb b/app/services/destroy_task.rbindex f6038c0ccf2..1aae65a34b1 100644--- a/app/services/destroy_task.rb+++ b/app/services/destroy_task.rb@@ -138,25 +138,23 @@ class DestroyTask.human_users.where(admin: false).find_each do |user|- begin- if UserDestroyer.new(Discourse.system_user).destroy(- user,- delete_posts: true,- context: "destroy task",- )- @io.puts "#{user.username} deleted"- else- @io.puts "#{user.username} not deleted"- end- rescue UserDestroyer::PostsExistError- raise Discourse::InvalidAccess.new(- "User #{user.username} has #{user.post_count} posts, so can't be deleted.",- )- rescue NoMethodError- @io.puts "#{user.username} could not be deleted"- rescue Discourse::InvalidAccess => e- @io.puts "#{user.username} #{e.message}"+ if UserDestroyer.new(Discourse.system_user).destroy(+ user,+ delete_posts: true,+ context: "destroy task",+ )+ @io.puts "#{user.username} deleted"+ else+ @io.puts "#{user.username} not deleted"end+ rescue UserDestroyer::PostsExistError+ raise Discourse::InvalidAccess.new(+ "User #{user.username} has #{user.post_count} posts, so can't be deleted.",+ )+ rescue NoMethodError+ @io.puts "#{user.username} could not be deleted"+ rescue Discourse::InvalidAccess => e+ @io.puts "#{user.username} #{e.message}"endenddiff --git a/app/services/email_settings_validator.rb b/app/services/email_settings_validator.rbindex 451adf0e92c..92df9e37b30 100644--- a/app/services/email_settings_validator.rb+++ b/app/services/email_settings_validator.rb@@ -25,25 +25,23 @@ class EmailSettingsValidatoropenssl_verify: SiteSetting.pop3_polling_openssl_verify,debug: Rails.env.development?)- begin- pop3 = Net::POP3.new(host, port)+ pop3 = Net::POP3.new(host, port)- # Note that we do not allow which verification mode to be specified- # like we do for SMTP, we just pick TLS1_2 if the SSL and openSSL verify- # options have been enabled.- if ssl- if openssl_verify- pop3.enable_ssl(max_version: OpenSSL::SSL::TLS1_2_VERSION)- else- pop3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)- end+ # Note that we do not allow which verification mode to be specified+ # like we do for SMTP, we just pick TLS1_2 if the SSL and openSSL verify+ # options have been enabled.+ if ssl+ if openssl_verify+ pop3.enable_ssl(max_version: OpenSSL::SSL::TLS1_2_VERSION)+ else+ pop3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)end-- # This disconnects itself, unlike SMTP.- pop3.auth_only(username, password)- rescue => err- log_and_raise(err, debug)end++ # This disconnects itself, unlike SMTP.+ pop3.auth_only(username, password)+ rescue => err+ log_and_raise(err, debug)end##@@ -67,63 +65,61 @@ class EmailSettingsValidatoropenssl_verify_mode: GlobalSetting.smtp_openssl_verify_mode,debug: Rails.env.development?)- begin- if username || password- authentication = SmtpProviderOverrides.authentication_override(host) if authentication.nil?- authentication = authentication.to_sym- if !%i[plain login cram_md5].include?(authentication)- raise ArgumentError, "Invalid authentication method. Must be plain, login, or cram_md5."- end- else- authentication = nil+ if username || password+ authentication = SmtpProviderOverrides.authentication_override(host) if authentication.nil?+ authentication = authentication.to_sym+ if !%i[plain login cram_md5].include?(authentication)+ raise ArgumentError, "Invalid authentication method. Must be plain, login, or cram_md5."end+ else+ authentication = nil+ end- if domain.blank?- if Rails.env.development?- domain = "localhost"- else- # Because we are using the SMTP settings here to send emails,- # the domain should just be the TLD of the host.- domain = MiniSuffix.domain(host)- end+ if domain.blank?+ if Rails.env.development?+ domain = "localhost"+ else+ # Because we are using the SMTP settings here to send emails,+ # the domain should just be the TLD of the host.+ domain = MiniSuffix.domain(host)end+ end- smtp = Net::SMTP.new(host, port)+ smtp = Net::SMTP.new(host, port)- # These SSL options are cribbed from the Mail gem, which is used internally- # by ActionMailer. Unfortunately the mail gem hides this setup in private- # methods, e.g. https://github.com/mikel/mail/blob/master/lib/mail/network/delivery_methods/smtp.rb#L112-L147- #- # Relying on the GlobalSetting options is a good idea here.- #- # For specific use cases, options should be passed in from higher up. For example- # Gmail needs either port 465 and tls enabled, or port 587 and starttls_auto.- if openssl_verify_mode.kind_of?(String)- openssl_verify_mode = OpenSSL::SSL.const_get("VERIFY_#{openssl_verify_mode.upcase}")- end- ssl_context = Net::SMTP.default_ssl_context- ssl_context.verify_mode = openssl_verify_mode if openssl_verify_mode+ # These SSL options are cribbed from the Mail gem, which is used internally+ # by ActionMailer. Unfortunately the mail gem hides this setup in private+ # methods, e.g. https://github.com/mikel/mail/blob/master/lib/mail/network/delivery_methods/smtp.rb#L112-L147+ #+ # Relying on the GlobalSetting options is a good idea here.+ #+ # For specific use cases, options should be passed in from higher up. For example+ # Gmail needs either port 465 and tls enabled, or port 587 and starttls_auto.+ if openssl_verify_mode.kind_of?(String)+ openssl_verify_mode = OpenSSL::SSL.const_get("VERIFY_#{openssl_verify_mode.upcase}")+ end+ ssl_context = Net::SMTP.default_ssl_context+ ssl_context.verify_mode = openssl_verify_mode if openssl_verify_mode- if enable_starttls_auto- # starttls is automatic, but we might need to change the context- smtp.enable_starttls_auto(ssl_context)- else- smtp.disable_starttls- end- smtp.enable_tls(ssl_context) if enable_tls+ if enable_starttls_auto+ # starttls is automatic, but we might need to change the context+ smtp.enable_starttls_auto(ssl_context)+ else+ smtp.disable_starttls+ end+ smtp.enable_tls(ssl_context) if enable_tls- smtp.open_timeout = 5+ smtp.open_timeout = 5- # Some SMTP servers have a higher delay to respond with errors- # as a tarpit measure that slows down clients who are sending "bad" commands.- # 10s is the minimum, we might need to increase this in the future.- smtp.read_timeout = 10+ # Some SMTP servers have a higher delay to respond with errors+ # as a tarpit measure that slows down clients who are sending "bad" commands.+ # 10s is the minimum, we might need to increase this in the future.+ smtp.read_timeout = 10- smtp.start(domain, username, password, authentication)- smtp.finish- rescue => err- log_and_raise(err, debug)- end+ smtp.start(domain, username, password, authentication)+ smtp.finish+ rescue => err+ log_and_raise(err, debug)enddef self.log_and_raise(err, debug)diff --git a/app/services/problem_check/group_email_credentials.rb b/app/services/problem_check/group_email_credentials.rbindex cb794e0ac3d..6d552859dc0 100644--- a/app/services/problem_check/group_email_credentials.rb+++ b/app/services/problem_check/group_email_credentials.rb@@ -37,21 +37,18 @@ class ProblemCheck::GroupEmailCredentials < ProblemCheckenddef try_validate(group, &blk)- begin- blk.call- no_problem- rescue *EmailSettingsExceptionHandler::EXPECTED_EXCEPTIONS => err- error_message =- EmailSettingsExceptionHandler.friendly_exception_message(err, group.smtp_server)-- problem(group, override_data: { error: error_message })- rescue => err- Discourse.warn_exception(- err,- message:- "Unexpected error when checking SMTP credentials for group #{group.id} (#{group.name}).",- )- no_problem- end+ blk.call+ no_problem+ rescue *EmailSettingsExceptionHandler::EXPECTED_EXCEPTIONS => err+ error_message = EmailSettingsExceptionHandler.friendly_exception_message(err, group.smtp_server)++ problem(group, override_data: { error: error_message })+ rescue => err+ Discourse.warn_exception(+ err,+ message:+ "Unexpected error when checking SMTP credentials for group #{group.id} (#{group.name}).",+ )+ no_problemendenddiff --git a/app/services/search_indexer.rb b/app/services/search_indexer.rbindex 2e2c70582be..09ec2c2e967 100644--- a/app/services/search_indexer.rb+++ b/app/services/search_indexer.rb@@ -357,15 +357,13 @@ class SearchIndexerraw_data.scan(Discourse::Utils::URI_REGEXP) { urls << $& }urls.each do |url|- begin- case File.extname(URI(url).path || "")- when Oneboxer::VIDEO_REGEX- raw_data.gsub!(url, I18n.t("search.video"))- when Oneboxer::AUDIO_REGEX- raw_data.gsub!(url, I18n.t("search.audio"))- end- rescue URI::InvalidURIError+ case File.extname(URI(url).path || "")+ when Oneboxer::VIDEO_REGEX+ raw_data.gsub!(url, I18n.t("search.video"))+ when Oneboxer::AUDIO_REGEX+ raw_data.gsub!(url, I18n.t("search.audio"))end+ rescue URI::InvalidURIErrorendraw_datadiff --git a/app/services/video_conversion/aws_media_convert_adapter.rb b/app/services/video_conversion/aws_media_convert_adapter.rbindex c08eac211a7..41b679e34f4 100644--- a/app/services/video_conversion/aws_media_convert_adapter.rb+++ b/app/services/video_conversion/aws_media_convert_adapter.rb@@ -232,39 +232,37 @@ module VideoConversionenddef update_file_acl(s3_store, destination_path)- begin- s3_store.update_file_access_control(destination_path, @upload.secure?)- rescue Aws::S3::Errors::NotFound => e- Rails.logger.error(- "MediaConvert file not found when updating access control at #{destination_path} for upload #{@upload.id}: #{e.message}",- )- raise- rescue Aws::S3::Errors::AccessDenied, Aws::S3::Errors::Forbidden => e- # ACL update failed due to permissions - this is critical as it will cause 403s- Discourse.warn_exception(- e,- message: "MediaConvert ACL update failed due to permissions - file may be inaccessible",- env: {- upload_id: @upload.id,- destination_path: destination_path,- secure: @upload.secure?,- },- )- raise- rescue Aws::S3::Errors::ServiceError => e- # Catch other AWS S3 errors that might prevent ACL from being set- Discourse.warn_exception(- e,- message: "MediaConvert ACL update failed with AWS error",- env: {- upload_id: @upload.id,- destination_path: destination_path,- secure: @upload.secure?,- error_code: e.code,- },- )- raise- end+ s3_store.update_file_access_control(destination_path, @upload.secure?)+ rescue Aws::S3::Errors::NotFound => e+ Rails.logger.error(+ "MediaConvert file not found when updating access control at #{destination_path} for upload #{@upload.id}: #{e.message}",+ )+ raise+ rescue Aws::S3::Errors::AccessDenied, Aws::S3::Errors::Forbidden => e+ # ACL update failed due to permissions - this is critical as it will cause 403s+ Discourse.warn_exception(+ e,+ message: "MediaConvert ACL update failed due to permissions - file may be inaccessible",+ env: {+ upload_id: @upload.id,+ destination_path: destination_path,+ secure: @upload.secure?,+ },+ )+ raise+ rescue Aws::S3::Errors::ServiceError => e+ # Catch other AWS S3 errors that might prevent ACL from being set+ Discourse.warn_exception(+ e,+ message: "MediaConvert ACL update failed with AWS error",+ env: {+ upload_id: @upload.id,+ destination_path: destination_path,+ secure: @upload.secure?,+ error_code: e.code,+ },+ )+ raiseenddef remove_temp_file(s3_store, temp_path)diff --git a/config/initializers/005-site_settings.rb b/config/initializers/005-site_settings.rbindex 7527f49a449..b23ee0cf39f 100644--- a/config/initializers/005-site_settings.rb+++ b/config/initializers/005-site_settings.rb@@ -16,13 +16,11 @@ endRails.application.config.to_prepare doRailsMultisite::ConnectionManagement.safe_each_connection do- begin- SiteSetting.refresh!+ SiteSetting.refresh!- # Check for circular dependencies in site settings.- SiteSetting.type_supervisor.dependencies.order- rescue ActiveRecord::StatementInvalid- # This will happen when migrating a new database- end+ # Check for circular dependencies in site settings.+ SiteSetting.type_supervisor.dependencies.order+ rescue ActiveRecord::StatementInvalid+ # This will happen when migrating a new databaseendenddiff --git a/config/initializers/014-track-setting-changes.rb b/config/initializers/014-track-setting-changes.rbindex af34fa4fdcd..77ed9952257 100644--- a/config/initializers/014-track-setting-changes.rb+++ b/config/initializers/014-track-setting-changes.rb@@ -102,13 +102,11 @@ DiscourseEvent.on(:site_setting_changed) do |name, old_value, new_value|if SiteSetting.discourse_id_client_id.present? && SiteSetting.discourse_id_client_secret.present?if %i[title logo logo_small site_description].include?(name)Scheduler::Defer.later("Update Discourse ID metadata") do- begin- DiscourseId::Register.call(update: true)- rescue StandardError => e- Rails.logger.error(- "Failed to update Discourse ID metadata after #{name} change: #{e.message}",- )- end+ DiscourseId::Register.call(update: true)+ rescue StandardError => e+ Rails.logger.error(+ "Failed to update Discourse ID metadata after #{name} change: #{e.message}",+ )endendenddiff --git a/config/initializers/101-lograge.rb b/config/initializers/101-lograge.rbindex 542e744455e..c0276eb96d7 100644--- a/config/initializers/101-lograge.rb+++ b/config/initializers/101-lograge.rb@@ -66,92 +66,88 @@ if DiscourseLograge.enabled?)config.lograge.custom_payload do |controller|- begin- username =- begin- controller.current_user&.username if controller.respond_to?(:current_user)- rescue Discourse::InvalidAccess, Discourse::ReadOnly, ActiveRecord::ReadOnlyError- nil- end+ username =+ begin+ controller.current_user&.username if controller.respond_to?(:current_user)+ rescue Discourse::InvalidAccess, Discourse::ReadOnly, ActiveRecord::ReadOnlyError+ nil+ end- ip =- begin- controller.request.remote_ip- rescue ActionDispatch::RemoteIp::IpSpoofAttackError- nil- end+ ip =+ begin+ controller.request.remote_ip+ rescue ActionDispatch::RemoteIp::IpSpoofAttackError+ nil+ end- DiscourseLograge.custom_payload(ip: ip, username: username)- rescue => e- Rails.logger.warn(- "Failed to append custom payload: #{e.message}\n#{e.backtrace.join("\n")}",- )- {}- end+ DiscourseLograge.custom_payload(ip: ip, username: username)+ rescue => e+ Rails.logger.warn(+ "Failed to append custom payload: #{e.message}\n#{e.backtrace.join("\n")}",+ )+ {}endconfig.lograge.custom_options =lambda do |event|- begin- exceptions = %w[controller action format id]+ exceptions = %w[controller action format id]- params = event.payload[:params].except(*exceptions)+ params = event.payload[:params].except(*exceptions)- if (file = params[:file]) && file.respond_to?(:headers)- params[:file] = file.headers- end-- if (files = params[:files]) && files.respond_to?(:map)- params[:files] = files.map { |f| f.respond_to?(:headers) ? f.headers : f }- end+ if (file = params[:file]) && file.respond_to?(:headers)+ params[:file] = file.headers+ end- output = {- params: params.to_query,- database: RailsMultisite::ConnectionManagement.current_db,- }-- if ENV["LOGRAGE_INCLUDE_HTTP_ACCEPT_LANGUAGE_HEADER"] == "1" &&- (- http_accept_language_request_header =- event.payload[:headers]["HTTP_ACCEPT_LANGUAGE"]- ).present?- output["request.headers.http_accept_language"] = http_accept_language_request_header- end+ if (files = params[:files]) && files.respond_to?(:map)+ params[:files] = files.map { |f| f.respond_to?(:headers) ? f.headers : f }+ end- if data = Thread.current[:_method_profiler] || event.payload[:timings]- if sql = data[:sql]- output[:db] = sql[:duration] * 1000- output[:db_calls] = sql[:calls]- end+ output = {+ params: params.to_query,+ database: RailsMultisite::ConnectionManagement.current_db,+ }++ if ENV["LOGRAGE_INCLUDE_HTTP_ACCEPT_LANGUAGE_HEADER"] == "1" &&+ (+ http_accept_language_request_header =+ event.payload[:headers]["HTTP_ACCEPT_LANGUAGE"]+ ).present?+ output["request.headers.http_accept_language"] = http_accept_language_request_header+ end- if redis = data[:redis]- output[:redis] = redis[:duration] * 1000- output[:redis_calls] = redis[:calls]- end+ if data = Thread.current[:_method_profiler] || event.payload[:timings]+ if sql = data[:sql]+ output[:db] = sql[:duration] * 1000+ output[:db_calls] = sql[:calls]+ end- if net = data[:net]- output[:net] = net[:duration] * 1000- output[:net_calls] = net[:calls]- end+ if redis = data[:redis]+ output[:redis] = redis[:duration] * 1000+ output[:redis_calls] = redis[:calls]+ end- # MethodProfiler.stop is called after this lambda, so the delta- # must be computed here.- if data[:__start_gc_heap_live_slots]- output[:heap_live_slots] = GC.stat[:heap_live_slots] -- data[:__start_gc_heap_live_slots]- end+ if net = data[:net]+ output[:net] = net[:duration] * 1000+ output[:net_calls] = net[:calls]end- output- rescue RateLimiter::LimitExceeded- # no idea who this is, but they are limited- {}- rescue => e- Rails.logger.warn(- "Failed to append custom options: #{e.message}\n#{e.backtrace.join("\n")}",- )- {}+ # MethodProfiler.stop is called after this lambda, so the delta+ # must be computed here.+ if data[:__start_gc_heap_live_slots]+ output[:heap_live_slots] = GC.stat[:heap_live_slots] -+ data[:__start_gc_heap_live_slots]+ endend++ output+ rescue RateLimiter::LimitExceeded+ # no idea who this is, but they are limited+ {}+ rescue => e+ Rails.logger.warn(+ "Failed to append custom options: #{e.message}\n#{e.backtrace.join("\n")}",+ )+ {}endconfig.lograge.formatter = Lograge::Formatters::Logstash.newdiff --git a/db/fixtures/001_refresh.rb b/db/fixtures/001_refresh.rbindex b7e737c632f..b522445edaa 100644--- a/db/fixtures/001_refresh.rb+++ b/db/fixtures/001_refresh.rb@@ -12,11 +12,9 @@ class SeedData::Refresher# Not that reset_column_information is not thread safe so we have to be careful# not to run it concurrently within the same process.ActiveRecord::Base.connection.tables.each do |table|- begin- table.classify.constantize.reset_column_information- rescue StandardError- nil- end+ table.classify.constantize.reset_column_information+ rescue StandardError+ nilend@refreshed = truediff --git a/db/migrate/20121204183855_fix_link_post_id.rb b/db/migrate/20121204183855_fix_link_post_id.rbindex 5c4423405c6..baa66f70870 100644--- a/db/migrate/20121204183855_fix_link_post_id.rb+++ b/db/migrate/20121204183855_fix_link_post_id.rb@@ -7,16 +7,14 @@ class FixLinkPostId < ActiveRecord::Migration[4.2]TopicLink.where("internal = TRUE AND link_post_id IS NULL").each do |tl|- begin- parsed = URI.parse(tl.url)- route = Rails.application.routes.recognize_path(parsed.path)- if route[:topic_id].present?- post = Post.find_by(topic_id: route[:topic_id], post_number: route[:post_number] || 1)- tl.update_column(:link_post_id, post.id) if post.present?- end- rescue ActionController::RoutingError- to_remove << tl.id+ parsed = URI.parse(tl.url)+ route = Rails.application.routes.recognize_path(parsed.path)+ if route[:topic_id].present?+ post = Post.find_by(topic_id: route[:topic_id], post_number: route[:post_number] || 1)+ tl.update_column(:link_post_id, post.id) if post.present?end+ rescue ActionController::RoutingError+ to_remove << tl.idendTopicLink.where("id in (?)", to_remove).delete_alldiff --git a/db/migrate/20131210181901_migrate_word_counts.rb b/db/migrate/20131210181901_migrate_word_counts.rbindex 7f20c255b06..ee3cbe00dba 100644--- a/db/migrate/20131210181901_migrate_word_counts.rb+++ b/db/migrate/20131210181901_migrate_word_counts.rb@@ -8,12 +8,10 @@ class MigrateWordCounts < ActiveRecord::Migration[4.2]execute("SELECT id FROM posts WHERE word_count IS NULL LIMIT 500").map { |r| r["id"].to_i }while post_ids.length > 03.times do- begin- execute "UPDATE posts SET word_count = COALESCE(array_length(regexp_split_to_array(raw, ' '),1), 0) WHERE id IN (#{post_ids.join(",")})"- break- rescue PG::Error- # Deadlock. Try again, up to 3 times.- end+ execute "UPDATE posts SET word_count = COALESCE(array_length(regexp_split_to_array(raw, ' '),1), 0) WHERE id IN (#{post_ids.join(",")})"+ break+ rescue PG::Error+ # Deadlock. Try again, up to 3 times.endpost_ids =execute("SELECT id FROM posts WHERE word_count IS NULL LIMIT 500").map { |r| r["id"].to_i }@@ -23,12 +21,10 @@ class MigrateWordCounts < ActiveRecord::Migration[4.2]execute("SELECT id FROM topics WHERE word_count IS NULL LIMIT 500").map { |r| r["id"].to_i }while topic_ids.length > 03.times do- begin- execute "UPDATE topics SET word_count = COALESCE((SELECT SUM(COALESCE(posts.word_count, 0)) FROM posts WHERE posts.topic_id = topics.id), 0) WHERE topics.id IN (#{topic_ids.join(",")})"- break- rescue PG::Error- # Deadlock. Try again, up to 3 times.- end+ execute "UPDATE topics SET word_count = COALESCE((SELECT SUM(COALESCE(posts.word_count, 0)) FROM posts WHERE posts.topic_id = topics.id), 0) WHERE topics.id IN (#{topic_ids.join(",")})"+ break+ rescue PG::Error+ # Deadlock. Try again, up to 3 times.endtopic_ids =execute("SELECT id FROM topics WHERE word_count IS NULL LIMIT 500").map { |r| r["id"].to_i }diff --git a/db/migrate/20180521184439_allow_null_ip_search_log.rb b/db/migrate/20180521184439_allow_null_ip_search_log.rbindex 0bfa3db7cd7..965b86b8274 100644--- a/db/migrate/20180521184439_allow_null_ip_search_log.rb+++ b/db/migrate/20180521184439_allow_null_ip_search_log.rb@@ -2,12 +2,10 @@class AllowNullIpSearchLog < ActiveRecord::Migration[5.1]def up- begin- Migration::SafeMigrate.disable!- change_column :search_logs, :ip_address, :inet, null: true- ensure- Migration::SafeMigrate.enable!- end+ Migration::SafeMigrate.disable!+ change_column :search_logs, :ip_address, :inet, null: true+ ensure+ Migration::SafeMigrate.enable!enddef downdiff --git a/db/migrate/20180521190040_allow_null_ip_topic_link_click.rb b/db/migrate/20180521190040_allow_null_ip_topic_link_click.rbindex 584c5c5fe7c..e6ed3ed18b2 100644--- a/db/migrate/20180521190040_allow_null_ip_topic_link_click.rb+++ b/db/migrate/20180521190040_allow_null_ip_topic_link_click.rb@@ -2,12 +2,10 @@class AllowNullIpTopicLinkClick < ActiveRecord::Migration[5.1]def up- begin- Migration::SafeMigrate.disable!- change_column :topic_link_clicks, :ip_address, :inet, null: true- ensure- Migration::SafeMigrate.enable!- end+ Migration::SafeMigrate.disable!+ change_column :topic_link_clicks, :ip_address, :inet, null: true+ ensure+ Migration::SafeMigrate.enable!enddef downdiff --git a/db/migrate/20180717025038_drop_not_null_ip_address_on_topic_views.rb b/db/migrate/20180717025038_drop_not_null_ip_address_on_topic_views.rbindex 7d5e98c4a88..b5bb02e9c9a 100644--- a/db/migrate/20180717025038_drop_not_null_ip_address_on_topic_views.rb+++ b/db/migrate/20180717025038_drop_not_null_ip_address_on_topic_views.rb@@ -2,11 +2,9 @@class DropNotNullIpAddressOnTopicViews < ActiveRecord::Migration[5.2]def change- begin- Migration::SafeMigrate.disable!- change_column_null :topic_views, :ip_address, true- ensure- Migration::SafeMigrate.enable!- end+ Migration::SafeMigrate.disable!+ change_column_null :topic_views, :ip_address, true+ ensure+ Migration::SafeMigrate.enable!endenddiff --git a/db/migrate/20181210122522_remove_not_null_user_associated_account_user.rb b/db/migrate/20181210122522_remove_not_null_user_associated_account_user.rbindex aae98f99b67..b2a5c223b2d 100644--- a/db/migrate/20181210122522_remove_not_null_user_associated_account_user.rb+++ b/db/migrate/20181210122522_remove_not_null_user_associated_account_user.rb@@ -2,11 +2,9 @@class RemoveNotNullUserAssociatedAccountUser < ActiveRecord::Migration[5.2]def change- begin- Migration::SafeMigrate.disable!- change_column_null :user_associated_accounts, :user_id, true- ensure- Migration::SafeMigrate.enable!- end+ Migration::SafeMigrate.disable!+ change_column_null :user_associated_accounts, :user_id, true+ ensure+ Migration::SafeMigrate.enable!endenddiff --git a/db/migrate/20210617202227_change_automatic_on_directory_columns_to_bool.rb b/db/migrate/20210617202227_change_automatic_on_directory_columns_to_bool.rbindex 534d2217b3c..e75a5369718 100644--- a/db/migrate/20210617202227_change_automatic_on_directory_columns_to_bool.rb+++ b/db/migrate/20210617202227_change_automatic_on_directory_columns_to_bool.rb@@ -2,21 +2,19 @@class ChangeAutomaticOnDirectoryColumnsToBool < ActiveRecord::Migration[6.1]def up- begin- Migration::SafeMigrate.disable!+ Migration::SafeMigrate.disable!- # Because of a weird state we are in where some sites have a boolean type column for `automatic` and some- # have an `integer`type, we remove the column. Then we re-create it and using `user_field_id` to determine- # if the value should be true or false.- remove_column :directory_columns, :automatic- add_column :directory_columns, :automatic, :boolean, default: true, null: false+ # Because of a weird state we are in where some sites have a boolean type column for `automatic` and some+ # have an `integer`type, we remove the column. Then we re-create it and using `user_field_id` to determine+ # if the value should be true or false.+ remove_column :directory_columns, :automatic+ add_column :directory_columns, :automatic, :boolean, default: true, null: false- execute <<~SQL+ execute <<~SQLUPDATE directory_columns SET automatic = (user_field_id IS NULL);SQL- ensure- Migration::SafeMigrate.enable!- end+ ensure+ Migration::SafeMigrate.enable!enddef downdiff --git a/db/migrate/20211213060445_email_tokens_token_to_nullable.rb b/db/migrate/20211213060445_email_tokens_token_to_nullable.rbindex 16f542f01ca..1616fb830d4 100644--- a/db/migrate/20211213060445_email_tokens_token_to_nullable.rb+++ b/db/migrate/20211213060445_email_tokens_token_to_nullable.rb@@ -7,9 +7,9 @@ class EmailTokensTokenToNullable < ActiveRecord::Migration[6.1]## using this somewhat verbose pattern to avoid impacting people who# drifted on main- begin- Migration::SafeMigrate.disable!- execute <<~SQL if DB.query_single(<<~SQL).length > 0++ Migration::SafeMigrate.disable!+ execute <<~SQL if DB.query_single(<<~SQL).length > 0ALTER TABLE email_tokens ALTER COLUMN token DROP NOT NULLSQLSELECT 1 FROM INFORMATION_SCHEMA.COLUMNS@@ -17,9 +17,8 @@ class EmailTokensTokenToNullable < ActiveRecord::Migration[6.1]AND table_name = 'email_tokens'AND column_name = 'token'SQL- ensure- Migration::SafeMigrate.enable!- end+ ensure+ Migration::SafeMigrate.enable!enddef downdiff --git a/lib/auth/default_current_user_provider.rb b/lib/auth/default_current_user_provider.rbindex acfc07c0c01..085573e8ce4 100644--- a/lib/auth/default_current_user_provider.rb+++ b/lib/auth/default_current_user_provider.rb@@ -485,12 +485,10 @@ class Auth::DefaultCurrentUserProviderreturn @auth_token if defined?(@auth_token)@auth_token =- begin- if v0 = self.class.find_v0_auth_cookie(@request)- v0- elsif v1 = self.class.find_v1_auth_cookie(@env)- v1[:token] if v1[:issued_at] >= SiteSetting.maximum_session_age.hours.ago.to_i- end+ if v0 = self.class.find_v0_auth_cookie(@request)+ v0+ elsif v1 = self.class.find_v1_auth_cookie(@env)+ v1[:token] if v1[:issued_at] >= SiteSetting.maximum_session_age.hours.ago.to_iendendenddiff --git a/lib/autospec/manager.rb b/lib/autospec/manager.rbindex adfb85c2830..5ee9f97f422 100644--- a/lib/autospec/manager.rb+++ b/lib/autospec/manager.rb@@ -230,23 +230,21 @@ class Autospec::Manager%w[spec lib app config test vendor plugins].each do |watch|puts "@@@@@@@@@ Listen to #{path}/#{watch} #{options}" if @debugThread.new do- begin- listener =- Listen.to("#{path}/#{watch}", options) do |modified, added, _|- paths = [modified, added].flatten- paths.compact!- paths.map! do |long|- long = reverse_symlink(long)- long[(path.length + 1)..-1]- end- process_change(paths)+ listener =+ Listen.to("#{path}/#{watch}", options) do |modified, added, _|+ paths = [modified, added].flatten+ paths.compact!+ paths.map! do |long|+ long = reverse_symlink(long)+ long[(path.length + 1)..-1]end- listener.start- sleep- rescue => e- puts "FAILED to listen on changes to #{path}/#{watch}"- puts e- end+ process_change(paths)+ end+ listener.start+ sleep+ rescue => e+ puts "FAILED to listen on changes to #{path}/#{watch}"+ puts eendendenddiff --git a/lib/backup_restore/creator.rb b/lib/backup_restore/creator.rbindex ff3fcba943a..0691233d043 100644--- a/lib/backup_restore/creator.rb+++ b/lib/backup_restore/creator.rb@@ -158,16 +158,14 @@ module BackupRestoreendIO.popen("#{pg_dump_command} 2>&1") do |pipe|- begin- while line = pipe.readline- logs << line- end- rescue EOFError- # finished reading...- ensure- pg_dump_running = false- logs << ""+ while line = pipe.readline+ logs << lineend+ rescue EOFError+ # finished reading...+ ensure+ pg_dump_running = false+ logs << ""endraise "pg_dump failed" unless $?.success?diff --git a/lib/backup_restore/database_restorer.rb b/lib/backup_restore/database_restorer.rbindex b076f1ac0b2..92cc38773ab 100644--- a/lib/backup_restore/database_restorer.rb+++ b/lib/backup_restore/database_restorer.rb@@ -76,16 +76,14 @@ module BackupRestoreendIO.popen(restore_dump_command) do |pipe|- begin- while line = pipe.readline- logs << line- last_line = line- end- rescue EOFError- # finished reading...- ensure- psql_running = false+ while line = pipe.readline+ logs << line+ last_line = lineend+ rescue EOFError+ # finished reading...+ ensure+ psql_running = falseendlogs << ""diff --git a/lib/demon/base.rb b/lib/demon/base.rbindex f61d9e7477f..e22275a987d 100644--- a/lib/demon/base.rb+++ b/lib/demon/base.rb@@ -264,12 +264,10 @@ class Demon::BaseDiscourse.after_fork if defined?(Discourse)Signal.trap("HUP") do- begin- delete_pid_file- ensure- # TERM is way cleaner than exit- Process.kill("TERM", Process.pid)- end+ delete_pid_file+ ensure+ # TERM is way cleaner than exit+ Process.kill("TERM", Process.pid)end# keep stuff simple for nowdiff --git a/lib/discourse.rb b/lib/discourse.rbindex e5c35535256..681aa204f74 100644--- a/lib/discourse.rb+++ b/lib/discourse.rb@@ -589,12 +589,10 @@ module Discoursedef self.cache@cache ||=- begin- if GlobalSetting.skip_redis?- ActiveSupport::Cache::MemoryStore.new- else- Cache.new- end+ if GlobalSetting.skip_redis?+ ActiveSupport::Cache::MemoryStore.new+ else+ Cache.newendend@@ -1193,11 +1191,9 @@ module Discoursedef self.reset_active_record_cacheActiveRecord::Base.connection.query_cache.clear(ActiveRecord::Base.connection.tables - %w[schema_migrations versions]).each do |table|- begin- table.classify.constantize.reset_column_information- rescue StandardError- nil- end+ table.classify.constantize.reset_column_information+ rescue StandardError+ nilendnilend@@ -1221,11 +1217,9 @@ module Discourse# load up all models and schema(ActiveRecord::Base.connection.tables - %w[schema_migrations versions]).each do |table|- begin- table.classify.constantize.first- rescue StandardError- nil- end+ table.classify.constantize.first+ rescue StandardError+ nilend# ensure we have a full schema cache in case we missed something above@@ -1257,11 +1251,10 @@ module Discourse[Thread.new do# router warm up- begin- Rails.application.routes.recognize_path("abc")- rescue StandardError- nil- end++ Rails.application.routes.recognize_path("abc")+ rescue StandardError+ nilend,Thread.new do# preload discourse versiondiff --git a/lib/discourse_dev/post.rb b/lib/discourse_dev/post.rbindex 350696a7d8d..1d965183ff9 100644--- a/lib/discourse_dev/post.rb+++ b/lib/discourse_dev/post.rb@@ -94,20 +94,18 @@ module DiscourseDevputs "Creating #{count} replies in '#{topic.title}'"count.times do |i|- begin- user = User.random- reply =- Faker::DiscourseMarkdown.with_user(user.id) do- {- topic_id: topic.id,- raw: Faker::DiscourseMarkdown.sandwich(sentences: 5),- skip_validations: true,- }- end- PostCreator.new(user, reply).create!- rescue ActiveRecord::RecordNotSaved => e- puts e- end+ user = User.random+ reply =+ Faker::DiscourseMarkdown.with_user(user.id) do+ {+ topic_id: topic.id,+ raw: Faker::DiscourseMarkdown.sandwich(sentences: 5),+ skip_validations: true,+ }+ end+ PostCreator.new(user, reply).create!+ rescue ActiveRecord::RecordNotSaved => e+ puts eendputs "Done!"diff --git a/lib/discourse_ip_info.rb b/lib/discourse_ip_info.rbindex ab697db919b..0ccbdc5d7bb 100644--- a/lib/discourse_ip_info.rb+++ b/lib/discourse_ip_info.rb@@ -82,15 +82,13 @@ class DiscourseIpInfoenddef mmdb_load(filepath)- begin- MaxMindDB.new(filepath, MaxMindDB::LOW_MEMORY_FILE_READER)- rescue Errno::ENOENT => e- Rails.logger.warn("MaxMindDB (#{filepath}) could not be found: #{e}")- nil- rescue => e- Discourse.warn_exception(e, message: "MaxMindDB (#{filepath}) could not be loaded.")- nil- end+ MaxMindDB.new(filepath, MaxMindDB::LOW_MEMORY_FILE_READER)+ rescue Errno::ENOENT => e+ Rails.logger.warn("MaxMindDB (#{filepath}) could not be found: #{e}")+ nil+ rescue => e+ Discourse.warn_exception(e, message: "MaxMindDB (#{filepath}) could not be loaded.")+ nilenddef lookup(ip, locale: :en, resolve_hostname: false)diff --git a/lib/discourse_updates.rb b/lib/discourse_updates.rbindex 438e8cdfa2d..90c0517e2bd 100644--- a/lib/discourse_updates.rb+++ b/lib/discourse_updates.rb@@ -143,19 +143,17 @@ module DiscourseUpdatesreturn [] if entries.blank?entries.select! do |item|- begin- valid_version =- item["discourse_version"].nil? ||- Discourse.has_needed_version?(current_version, item["discourse_version"]) ||- GitUtils.has_commit?(item["discourse_version"])+ valid_version =+ item["discourse_version"].nil? ||+ Discourse.has_needed_version?(current_version, item["discourse_version"]) ||+ GitUtils.has_commit?(item["discourse_version"])- valid_plugin_name =- item["plugin_name"].blank? || Discourse.plugins_by_name[item["plugin_name"]].present?+ valid_plugin_name =+ item["plugin_name"].blank? || Discourse.plugins_by_name[item["plugin_name"]].present?- valid_version && valid_plugin_name- rescue StandardError- false- end+ valid_version && valid_plugin_name+ rescue StandardError+ falseendentries.sort_by { |item| Time.zone.parse(item["created_at"]).to_i }.reversediff --git a/lib/email/processor.rb b/lib/email/processor.rbindex 30c50c2baef..e47ff2565cd 100644--- a/lib/email/processor.rb+++ b/lib/email/processor.rb@@ -14,24 +14,22 @@ module Emailenddef process!- begin- @receiver = Email::Receiver.new(@mail, @opts)- @receiver.process!- rescue RateLimiter::LimitExceeded- if @opts[:retry_on_rate_limit]- Jobs.enqueue(:process_email, mail: @mail, source: @opts[:source])- else- raise- end- rescue => e- return handle_bounce(e) if @receiver&.is_bounce?-- log_email_process_failure(@mail, e)- incoming_email = @receiver.try(:incoming_email)- rejection_message = handle_failure(@mail, e)- if rejection_message.present?- set_incoming_email_rejection_message(incoming_email, rejection_message.body.to_s)- end+ @receiver = Email::Receiver.new(@mail, @opts)+ @receiver.process!+ rescue RateLimiter::LimitExceeded+ if @opts[:retry_on_rate_limit]+ Jobs.enqueue(:process_email, mail: @mail, source: @opts[:source])+ else+ raise+ end+ rescue => e+ return handle_bounce(e) if @receiver&.is_bounce?++ log_email_process_failure(@mail, e)+ incoming_email = @receiver.try(:incoming_email)+ rejection_message = handle_failure(@mail, e)+ if rejection_message.present?+ set_incoming_email_rejection_message(incoming_email, rejection_message.body.to_s)endenddiff --git a/lib/email/receiver.rb b/lib/email/receiver.rbindex 6dc9c004e1b..9b1aa1cbc7a 100644--- a/lib/email/receiver.rb+++ b/lib/email/receiver.rb@@ -124,27 +124,25 @@ module Emailid_hash = Digest::SHA1.hexdigest(@message_id)DistributedMutex.synchronize("process_email_#{id_hash}") do- begin- # If we find an existing incoming email record with the exact same `message_id`- # do not create a new `IncomingEmail` record to avoid double ups.- return if @incoming_email = IncomingEmail.find_by(message_id: @message_id)+ # If we find an existing incoming email record with the exact same `message_id`+ # do not create a new `IncomingEmail` record to avoid double ups.+ return if @incoming_email = IncomingEmail.find_by(message_id: @message_id)- Email::Validator.ensure_valid!(@mail)+ Email::Validator.ensure_valid!(@mail)- @from_email, @from_display_name = parse_from_field(@mail)- @from_user = User.find_by_email(@from_email)- @incoming_email = create_incoming_email+ @from_email, @from_display_name = parse_from_field(@mail)+ @from_user = User.find_by_email(@from_email)+ @incoming_email = create_incoming_email- post = process_internal+ post = process_internal- raise BouncedEmailError if is_bounce?+ raise BouncedEmailError if is_bounce?- post- rescue Exception => e- @incoming_email.update_columns(error: e.class.name) if @incoming_email- delete_created_staged_users- raise- end+ post+ rescue Exception => e+ @incoming_email.update_columns(error: e.class.name) if @incoming_email+ delete_created_staged_users+ raiseendend@@ -249,11 +247,9 @@ module Emailfirst_exception = nildestinations.each do |destination|- begin- return process_destination(destination, user, body, elided)- rescue => e- first_exception ||= e- end+ return process_destination(destination, user, body, elided)+ rescue => e+ first_exception ||= eendraise first_exception if first_exception@@ -292,10 +288,8 @@ module Emailnext if mail[field].blank?mail[field].each do |address_field|- begin- address_field.decoded- recipients << address_field.address.downcase- end+ address_field.decoded+ recipients << address_field.address.downcaseendend@@ -763,28 +757,26 @@ module Emailenddef self.extract_email_address_and_name(value)- begin- # ensure the email header value is a string- value = value.to_s- # in embedded emails, converts [mailto:[email protected]] to <[email protected]>- value = value.gsub(/\[mailto:([^\[\]]+?)\]/, "<\\1>")- # 'mailto:' suffix isn't supported by Mail::Address parsing- value = value.gsub("mailto:", "")- # parse the email header value- parsed = Mail::Address.new(value)- # extract the email address and name- mail = parsed.address.to_s.downcase.strip- name = parsed.name.to_s.strip- # ensure the email address is "valid"- if mail.include?("@")- # remove surrounding quotes from the name- name = name[1...-1] if name.size > 2 && name[/\A(['"]).+(\1)\z/]- # return the email address and name- [mail, name]- end- rescue Mail::Field::ParseError, Mail::Field::IncompleteParseError- # something went wrong parsing the email header value, return nil+ # ensure the email header value is a string+ value = value.to_s+ # in embedded emails, converts [mailto:[email protected]] to <[email protected]>+ value = value.gsub(/\[mailto:([^\[\]]+?)\]/, "<\\1>")+ # 'mailto:' suffix isn't supported by Mail::Address parsing+ value = value.gsub("mailto:", "")+ # parse the email header value+ parsed = Mail::Address.new(value)+ # extract the email address and name+ mail = parsed.address.to_s.downcase.strip+ name = parsed.name.to_s.strip+ # ensure the email address is "valid"+ if mail.include?("@")+ # remove surrounding quotes from the name+ name = name[1...-1] if name.size > 2 && name[/\A(['"]).+(\1)\z/]+ # return the email address and name+ [mail, name]end+ rescue Mail::Field::ParseError, Mail::Field::IncompleteParseError+ # something went wrong parsing the email header value, return nilenddef subject@@ -1587,46 +1579,44 @@ module Emailnext if mail_object[d].blank?mail_object[d].each do |address_field|- begin- address_field.decoded- email = address_field.address.downcase- display_name = address_field.display_name.try(:to_s)- next if !email.include?("@")-- if should_invite?(email)- user = User.find_by_email(email)-- # cap number of staged users created per email- if (!user || user.staged) &&- @staged_users.count >= SiteSetting.maximum_staged_users_per_email- max_staged_users_post ||=- post.topic.add_moderator_post(- sender,- I18n.t("emails.incoming.maximum_staged_user_per_email_reached"),- import_mode: @opts[:import_mode],- )- next- end-- user = find_or_create_user(email, display_name, user: user)- if user && can_invite?(post.topic, user)- post.topic.topic_allowed_users.create!(user_id: user.id)- TopicUser.auto_notification_for_staging(- user.id,- post.topic_id,- TopicUser.notification_reasons[:auto_watch],- )- post.topic.add_small_action(+ address_field.decoded+ email = address_field.address.downcase+ display_name = address_field.display_name.try(:to_s)+ next if !email.include?("@")++ if should_invite?(email)+ user = User.find_by_email(email)++ # cap number of staged users created per email+ if (!user || user.staged) &&+ @staged_users.count >= SiteSetting.maximum_staged_users_per_email+ max_staged_users_post ||=+ post.topic.add_moderator_post(sender,- "invited_user",- user.username,+ I18n.t("emails.incoming.maximum_staged_user_per_email_reached"),import_mode: @opts[:import_mode],)- end+ next+ end++ user = find_or_create_user(email, display_name, user: user)+ if user && can_invite?(post.topic, user)+ post.topic.topic_allowed_users.create!(user_id: user.id)+ TopicUser.auto_notification_for_staging(+ user.id,+ post.topic_id,+ TopicUser.notification_reasons[:auto_watch],+ )+ post.topic.add_small_action(+ sender,+ "invited_user",+ user.username,+ import_mode: @opts[:import_mode],+ )end- rescue ActiveRecord::RecordInvalid, EmailNotAllowed- # don't care if user already allowed or the user's email address is not allowedend+ rescue ActiveRecord::RecordInvalid, EmailNotAllowed+ # don't care if user already allowed or the user's email address is not allowedendendenddiff --git a/lib/email/sender.rb b/lib/email/sender.rbindex 5592212a44d..e3ffc872e23 100644--- a/lib/email/sender.rb+++ b/lib/email/sender.rb@@ -330,17 +330,11 @@ module Emailenddef cc_addresses- @cc_addresses ||=- begin- @message.try(:cc) || []- end+ @cc_addresses ||= @message.try(:cc) || []enddef bcc_addresses- @bcc_addresses ||=- begin- @message.try(:bcc) || []- end+ @bcc_addresses ||= @message.try(:bcc) || []enddef self.host_for(base_url)diff --git a/lib/email/styles.rb b/lib/email/styles.rbindex b8dab999fb9..9dc14a94e2c 100644--- a/lib/email/styles.rb+++ b/lib/email/styles.rb@@ -226,27 +226,24 @@ module Email@fragment.css("iframe").each do |i|- begin- # sometimes, iframes are blocklisted...- if i["src"].blank?- i.remove- next- end-- src_uri =- i["data-original-href"].present? ? URI(i["data-original-href"]) : URI(i["src"])- # If an iframe is protocol relative, use SSL when displaying it- display_src =- "#{src_uri.scheme || "https"}://#{src_uri.host}#{src_uri.path}#{src_uri.query.nil? ? "" : "?" + src_uri.query}#{src_uri.fragment.nil? ? "" : "#" + src_uri.fragment}"- i.replace(- Nokogiri::HTML5.fragment(- "<p><a href='#{src_uri}'>#{CGI.escapeHTML(display_src)}</a><p>",- ),- )- rescue URI::Error- # If the URL is weird, remove the iframe+ # sometimes, iframes are blocklisted...+ if i["src"].blank?i.remove+ nextend++ src_uri = i["data-original-href"].present? ? URI(i["data-original-href"]) : URI(i["src"])+ # If an iframe is protocol relative, use SSL when displaying it+ display_src =+ "#{src_uri.scheme || "https"}://#{src_uri.host}#{src_uri.path}#{src_uri.query.nil? ? "" : "?" + src_uri.query}#{src_uri.fragment.nil? ? "" : "#" + src_uri.fragment}"+ i.replace(+ Nokogiri::HTML5.fragment(+ "<p><a href='#{src_uri}'>#{CGI.escapeHTML(display_src)}</a><p>",+ ),+ )+ rescue URI::Error+ # If the URL is weird, remove the iframe+ i.removeendend@@ -486,11 +483,9 @@ module Email@fragment.css("a").each do |link|- begin- link["href"] = "#{site_uri}#{link["href"]}" if URI(link["href"].to_s).host.blank?- rescue URI::Error- # leave it- end+ link["href"] = "#{site_uri}#{link["href"]}" if URI(link["href"].to_s).host.blank?+ rescue URI::Error+ # leave itendenddiff --git a/lib/external_upload_helpers.rb b/lib/external_upload_helpers.rbindex f4d90f4c699..d65286f17cf 100644--- a/lib/external_upload_helpers.rb+++ b/lib/external_upload_helpers.rb@@ -291,55 +291,50 @@ module ExternalUploadHelpersexternal_upload_manager = ExternalUploadManager.new(external_upload_stub, opts)hijack do- begin- upload = external_upload_manager.transform!-- if upload.errors.empty?- response_serialized = self.class.serialize_upload(upload)- external_upload_stub.destroy!- render json: response_serialized, status: :ok- else- render_json_error(upload.errors.to_hash.values.flatten, status: 422)- end- rescue ExternalUploadManager::SizeMismatchError => err- render_json_error(- debug_upload_error(- err,- I18n.t("upload.size_mismatch_failure", additional_detail: err.message),- ),- status: 422,- )- rescue ExternalUploadManager::ChecksumMismatchError => err- render_json_error(- debug_upload_error(- err,- I18n.t("upload.checksum_mismatch_failure", additional_detail: err.message),- ),- status: 422,- )- rescue ExternalUploadManager::CannotPromoteError => err- render_json_error(- debug_upload_error(- err,- I18n.t("upload.cannot_promote_failure", additional_detail: err.message),- ),- status: 422,- )- rescue ExternalUploadManager::DownloadFailedError, Aws::S3::Errors::NotFound => err- render_json_error(- debug_upload_error(- err,- I18n.t("upload.download_failure", additional_detail: err.message),- ),- status: 422,- )- rescue => err- Rails.logger.error(- "Complete external upload failed unexpectedly for user #{current_user.id}: #{err.class} #{err.message}\n#{err.backtrace.join("\n")}",- )-- render_json_error(I18n.t("upload.failed"), status: 422)+ upload = external_upload_manager.transform!++ if upload.errors.empty?+ response_serialized = self.class.serialize_upload(upload)+ external_upload_stub.destroy!+ render json: response_serialized, status: :ok+ else+ render_json_error(upload.errors.to_hash.values.flatten, status: 422)end+ rescue ExternalUploadManager::SizeMismatchError => err+ render_json_error(+ debug_upload_error(+ err,+ I18n.t("upload.size_mismatch_failure", additional_detail: err.message),+ ),+ status: 422,+ )+ rescue ExternalUploadManager::ChecksumMismatchError => err+ render_json_error(+ debug_upload_error(+ err,+ I18n.t("upload.checksum_mismatch_failure", additional_detail: err.message),+ ),+ status: 422,+ )+ rescue ExternalUploadManager::CannotPromoteError => err+ render_json_error(+ debug_upload_error(+ err,+ I18n.t("upload.cannot_promote_failure", additional_detail: err.message),+ ),+ status: 422,+ )+ rescue ExternalUploadManager::DownloadFailedError, Aws::S3::Errors::NotFound => err+ render_json_error(+ debug_upload_error(err, I18n.t("upload.download_failure", additional_detail: err.message)),+ status: 422,+ )+ rescue => err+ Rails.logger.error(+ "Complete external upload failed unexpectedly for user #{current_user.id}: #{err.class} #{err.message}\n#{err.backtrace.join("\n")}",+ )++ render_json_error(I18n.t("upload.failed"), status: 422)endenddiff --git a/lib/final_destination.rb b/lib/final_destination.rbindex 924b7ae5b34..b7f76b1bdc1 100644--- a/lib/final_destination.rb+++ b/lib/final_destination.rb@@ -562,10 +562,8 @@ class FinalDestinationprivatedef uri(location)- begin- URI.parse(location)- rescue URI::Error- end+ URI.parse(location)+ rescue URI::Errorenddef fetch_canonical_url(body)diff --git a/lib/freedom_patches/rails_multisite.rb b/lib/freedom_patches/rails_multisite.rbindex a4ae7899997..63886a919fc 100644--- a/lib/freedom_patches/rails_multisite.rb+++ b/lib/freedom_patches/rails_multisite.rb@@ -12,27 +12,25 @@ module RailsMultisitedef self.safe_each_connectioneach_active_connection do |db|- begin- yield(db) if block_given?- rescue PG::ConnectionBad, PG::UnableToSend, PG::ServerError- break if !defined?(RailsFailover::ActiveRecord)- break if db == RailsMultisite::ConnectionManagement::DEFAULT+ yield(db) if block_given?+ rescue PG::ConnectionBad, PG::UnableToSend, PG::ServerError+ break if !defined?(RailsFailover::ActiveRecord)+ break if db == RailsMultisite::ConnectionManagement::DEFAULT- reading_role = :"#{db}_#{ActiveRecord.reading_role}"- spec = RailsMultisite::ConnectionManagement.connection_spec(db: db)- handler = ActiveRecord::Base.connection_handler+ reading_role = :"#{db}_#{ActiveRecord.reading_role}"+ spec = RailsMultisite::ConnectionManagement.connection_spec(db: db)+ handler = ActiveRecord::Base.connection_handler- RailsFailover::ActiveRecord.establish_reading_connection(- handler,- spec.to_hash,- role: reading_role,- )- ActiveRecord::Base.connected_to(role: reading_role) { yield(db) if block_given? }- rescue => e- STDERR.puts "URGENT: Failed to initialize site #{db}: " \- "#{e.class} #{e.message}\n#{e.backtrace.join("\n")}"- # the show must go on, don't stop startup if multisite fails- end+ RailsFailover::ActiveRecord.establish_reading_connection(+ handler,+ spec.to_hash,+ role: reading_role,+ )+ ActiveRecord::Base.connected_to(role: reading_role) { yield(db) if block_given? }+ rescue => e+ STDERR.puts "URGENT: Failed to initialize site #{db}: " \+ "#{e.class} #{e.message}\n#{e.backtrace.join("\n")}"+ # the show must go on, don't stop startup if multisite failsendendenddiff --git a/lib/freedom_patches/translate_accelerator.rb b/lib/freedom_patches/translate_accelerator.rbindex fafa982118a..88a07c6e68e 100644--- a/lib/freedom_patches/translate_accelerator.rb+++ b/lib/freedom_patches/translate_accelerator.rb@@ -147,11 +147,9 @@ module I18nval =@cache.getset(k) do- begin- translate_no_cache(key, locale: locale, raise: true).freeze- rescue I18n::MissingTranslationData- MissingTranslation- end+ translate_no_cache(key, locale: locale, raise: true).freeze+ rescue I18n::MissingTranslationData+ MissingTranslationendif val != MissingTranslationdiff --git a/lib/guardian/tag_guardian.rb b/lib/guardian/tag_guardian.rbindex 1d8e13b17f2..78ee36b1d86 100644--- a/lib/guardian/tag_guardian.rb+++ b/lib/guardian/tag_guardian.rb@@ -43,12 +43,10 @@ module TagGuardiandef hidden_tag_names@hidden_tag_names ||=- begin- if SiteSetting.tagging_enabled && !is_admin?- DiscourseTagging.hidden_tag_names(self)- else- []- end+ if SiteSetting.tagging_enabled && !is_admin?+ DiscourseTagging.hidden_tag_names(self)+ else+ []endendenddiff --git a/lib/guardian/user_guardian.rb b/lib/guardian/user_guardian.rbindex b14e1167b8e..ec8d6301b3f 100644--- a/lib/guardian/user_guardian.rb+++ b/lib/guardian/user_guardian.rb@@ -183,12 +183,10 @@ module UserGuardianis_staff_or_is_me = is_staff? || is_me?(user)cache_key = is_staff_or_is_me ? :staff_or_me : :other- @allowed_user_field_ids[cache_key] ||= begin- if is_staff_or_is_me- UserField.pluck(:id)- else- UserField.where("show_on_profile OR show_on_user_card").pluck(:id)- end+ @allowed_user_field_ids[cache_key] ||= if is_staff_or_is_me+ UserField.pluck(:id)+ else+ UserField.where("show_on_profile OR show_on_user_card").pluck(:id)endenddiff --git a/lib/i18n/backend/discourse_i18n.rb b/lib/i18n/backend/discourse_i18n.rbindex f72019e697e..2ab8b520309 100644--- a/lib/i18n/backend/discourse_i18n.rb+++ b/lib/i18n/backend/discourse_i18n.rb@@ -27,12 +27,10 @@ module I18nenddef pluralize(locale, entry, count)- begin- super- rescue I18n::InvalidPluralizationData => e- raise e if I18n.fallbacks[locale] == [locale]- throw(:exception, e)- end+ super+ rescue I18n::InvalidPluralizationData => e+ raise e if I18n.fallbacks[locale] == [locale]+ throw(:exception, e)enddef self.sort_locale_files(files)diff --git a/lib/i18n/locale_file_checker.rb b/lib/i18n/locale_file_checker.rbindex a66eeff7999..9e2edbd52c6 100644--- a/lib/i18n/locale_file_checker.rb+++ b/lib/i18n/locale_file_checker.rb@@ -170,13 +170,11 @@ class LocaleFileCheckerenddef plural_keys+ # rubocop:disable Security/Eval@plural_keys ||=- begin- # rubocop:disable Security/Eval- eval(File.read("#{Rails.root}/#{PLURALS_FILE}"))- .map { |locale, value| [locale.to_s, value[:i18n][:plural][:keys].map(&:to_s)] }- .to_h- end+ eval(File.read("#{Rails.root}/#{PLURALS_FILE}"))+ .map { |locale, value| [locale.to_s, value[:i18n][:plural][:keys].map(&:to_s)] }+ .to_henddef add_error(keys, type, details, pluralized:)diff --git a/lib/import_export/importer.rb b/lib/import_export/importer.rbindex 550a9b66f4c..91a94e11da6 100644--- a/lib/import_export/importer.rb+++ b/lib/import_export/importer.rb@@ -66,11 +66,9 @@ module ImportExportnew_group = Group.find_by_name(g[:name]) || Group.create!(g)user_ids.each do |external_user_id|- begin- new_group.add(User.find(new_user_id(external_user_id)))- rescue StandardError- ActiveRecord::RecordNotUnique- end+ new_group.add(User.find(new_user_id(external_user_id)))+ rescue StandardError+ ActiveRecord::RecordNotUniqueendend@@ -103,32 +101,29 @@ module ImportExport@categories.sort_by! { |c| levels[c[:id]] || 0 }@categories.each do |cat_attrs|- begin- id = cat_attrs.delete(:id)- permissions = cat_attrs.delete(:permissions_params)-- category = Category.new(cat_attrs)- category.parent_category_id =- new_category_id(cat_attrs[:parent_category_id]) if cat_attrs[- :parent_category_id- ].present?- category.user_id = new_user_id(cat_attrs[:user_id])- import_id = "#{id}#{import_source}"- category.custom_fields["import_id"] = import_id- category.permissions = permissions- category.save!- existing_categories << { category_id: category.id, value: import_id }-- if cat_attrs[:description].present?- post = category.topic.ordered_posts.first- post.raw = cat_attrs[:description]- post.skip_validation = true- post.save!- post.rebake!- end- rescue => e- puts "Failed to import category (ID = #{id}, name = #{cat_attrs[:name]}): #{e.message}"+ id = cat_attrs.delete(:id)+ permissions = cat_attrs.delete(:permissions_params)++ category = Category.new(cat_attrs)+ category.parent_category_id = new_category_id(cat_attrs[:parent_category_id]) if cat_attrs[+ :parent_category_id+ ].present?+ category.user_id = new_user_id(cat_attrs[:user_id])+ import_id = "#{id}#{import_source}"+ category.custom_fields["import_id"] = import_id+ category.permissions = permissions+ category.save!+ existing_categories << { category_id: category.id, value: import_id }++ if cat_attrs[:description].present?+ post = category.topic.ordered_posts.first+ post.raw = cat_attrs[:description]+ post.skip_validation = true+ post.save!+ post.rebake!end+ rescue => e+ puts "Failed to import category (ID = #{id}, name = #{cat_attrs[:name]}): #{e.message}"endselfdiff --git a/lib/letter_avatar.rb b/lib/letter_avatar.rbindex 1081c886eaf..353ed9e3490 100644--- a/lib/letter_avatar.rb+++ b/lib/letter_avatar.rb@@ -119,17 +119,15 @@ class LetterAvatarenddef cleanup_old- begin- skip = File.basename(cache_path)- parent_path = File.dirname(cache_path)- Dir- .entries(parent_path)- .each do |path|- FileUtils.rm_rf(parent_path + "/" + path) unless %w[. ..].include?(path) || path == skip- end- rescue Errno::ENOENT- # no worries, folder doesn't exists- end+ skip = File.basename(cache_path)+ parent_path = File.dirname(cache_path)+ Dir+ .entries(parent_path)+ .each do |path|+ FileUtils.rm_rf(parent_path + "/" + path) unless %w[. ..].include?(path) || path == skip+ end+ rescue Errno::ENOENT+ # no worries, folder doesn't existsendenddiff --git a/lib/middleware/anonymous_cache.rb b/lib/middleware/anonymous_cache.rbindex 6d50cc81dca..b24c4707b5b 100644--- a/lib/middleware/anonymous_cache.rb+++ b/lib/middleware/anonymous_cache.rb@@ -118,10 +118,8 @@ module Middlewarealias_method :key_is_mobile?, :is_mobile?def key_has_brotli?- @has_brotli ||=- begin- @env[ACCEPT_ENCODING].to_s =~ /br/ ? :true : :false- end+ @has_brotli ||= @env[ACCEPT_ENCODING].to_s =~ /br/ ? :true : :false+@has_brotli == :trueend# rubocop:enable Lint/BooleanSymbol@@ -137,19 +135,18 @@ module Middleware# rubocop:disable Lint/BooleanSymboldef is_crawler?@is_crawler ||=- begin- if @env[DISCOURSE_RENDER] == "crawler" ||- CrawlerDetection.crawler?(@user_agent, @env["HTTP_VIA"])+ if @env[DISCOURSE_RENDER] == "crawler" ||+ CrawlerDetection.crawler?(@user_agent, @env["HTTP_VIA"])+ :true+ else+ if @user_agent.downcase.include?("discourse") &&+ !@user_agent.downcase.include?("mobile"):trueelse- if @user_agent.downcase.include?("discourse") &&- !@user_agent.downcase.include?("mobile")- :true- else- :false- end+ :falseendend+@is_crawler == :trueendalias_method :key_is_crawler?, :is_crawler?diff --git a/lib/middleware/request_tracker.rb b/lib/middleware/request_tracker.rbindex 8c72a394f0d..8fcb78944fe 100644--- a/lib/middleware/request_tracker.rb+++ b/lib/middleware/request_tracker.rb@@ -405,11 +405,9 @@ class Middleware::RequestTrackerlimiters.each(&:rollback!)env["DISCOURSE_ASSET_RATE_LIMITERS"].each do |limiter|- begin- limiter.performed!- rescue RateLimiter::LimitExceeded- # skip- end+ limiter.performed!+ rescue RateLimiter::LimitExceeded+ # skipendend@@ -421,14 +419,12 @@ class Middleware::RequestTrackerdef log_later(data, env, request)Scheduler::Defer.later("Track view") do- begin- unless Discourse.pg_readonly_mode?- self.class.log_request(data)- instrument_browser_page_view(env, request, data)- end- rescue ActiveRecord::ReadOnlyError- # Just noop if ActiveRecord is preventing writes+ unless Discourse.pg_readonly_mode?+ self.class.log_request(data)+ instrument_browser_page_view(env, request, data)end+ rescue ActiveRecord::ReadOnlyError+ # Just noop if ActiveRecord is preventing writesendenddiff --git a/lib/mini_scheduler_long_running_job_logger.rb b/lib/mini_scheduler_long_running_job_logger.rbindex 0685f4930b2..85fe742610e 100644--- a/lib/mini_scheduler_long_running_job_logger.rb+++ b/lib/mini_scheduler_long_running_job_logger.rb@@ -43,14 +43,12 @@ class MiniSchedulerLongRunningJobLoggerendwarning_duration =- begin- if job_frequency_minutes < 30.minutes- 30.minutes- elsif job_frequency_minutes < 2.hours- job_frequency_minutes- else- 2.hours- end+ if job_frequency_minutes < 30.minutes+ 30.minutes+ elsif job_frequency_minutes < 2.hours+ job_frequency_minutes+ else+ 2.hoursendnext if job_started_at >= (Time.zone.now - warning_duration)diff --git a/lib/onebox/engine/google_maps_onebox.rb b/lib/onebox/engine/google_maps_onebox.rbindex 87a0acae0cc..37ad05bed5f 100644--- a/lib/onebox/engine/google_maps_onebox.rb+++ b/lib/onebox/engine/google_maps_onebox.rb@@ -171,29 +171,25 @@ module Oneboxenddef follow_redirect!+ http =+ FinalDestination::HTTP.start(+ uri.host,+ uri.port,+ use_ssl: uri.scheme == "https",+ open_timeout: timeout,+ read_timeout: timeout,+ )++ response = http.head(uri.path)+ raise "unexpected response code #{response.code}" if %w[200 301 302].exclude?(response.code)++ @url = response.code == "200" ? uri.to_s : response["Location"]+ @uri = URI(@url)+ ensurebegin- http =- FinalDestination::HTTP.start(- uri.host,- uri.port,- use_ssl: uri.scheme == "https",- open_timeout: timeout,- read_timeout: timeout,- )-- response = http.head(uri.path)- if %w[200 301 302].exclude?(response.code)- raise "unexpected response code #{response.code}"- end-- @url = response.code == "200" ? uri.to_s : response["Location"]- @uri = URI(@url)- ensure- begin- http.finish- rescue StandardError- nil- end+ http.finish+ rescue StandardError+ nilendendenddiff --git a/lib/onebox/helpers.rb b/lib/onebox/helpers.rbindex de7b77e9d11..d84bc42fe73 100644--- a/lib/onebox/helpers.rb+++ b/lib/onebox/helpers.rb@@ -212,11 +212,9 @@ module Oneboxenddef self.get_absolute_image_url(src, url)- begin- URI.parse(url).merge(src).to_s- rescue ArgumentError, URI::BadURIError, URI::InvalidURIError- src- end+ URI.parse(url).merge(src).to_s+ rescue ArgumentError, URI::BadURIError, URI::InvalidURIError+ srcenddef self.user_agentdiff --git a/lib/onebox/json_ld.rb b/lib/onebox/json_ld.rbindex 1dbc8faf554..24de0eefb9b 100644--- a/lib/onebox/json_ld.rb+++ b/lib/onebox/json_ld.rb@@ -35,12 +35,10 @@ module Oneboxenddef parse_json(json)- begin- JSON[json]- rescue JSON::ParserError => e- Discourse.warn_exception(e, message: "Error parsing JSON-LD: #{json}")- {}- end+ JSON[json]+ rescue JSON::ParserError => e+ Discourse.warn_exception(e, message: "Error parsing JSON-LD: #{json}")+ {}endendenddiff --git a/lib/plugin.rb b/lib/plugin.rbindex c384d905667..e5b1f508686 100644--- a/lib/plugin.rb+++ b/lib/plugin.rb@@ -2,44 +2,39 @@module Plugindef self.initialization_guard(&block)- begin- block.call- rescue => error- plugins_directory = Rails.root + "plugins"-- if error.backtrace && error.backtrace_locations- plugin_path =- error- .backtrace_locations- .lazy- .map do |location|- resolved_path = location.absolute_path || location.path- next if resolved_path.nil?- Pathname- .new(resolved_path)- .ascend- .lazy- .find { |path| path.parent == plugins_directory }- end- .next-- raise unless plugin_path-- stack_trace =- error- .backtrace- .each_with_index- .inject([]) do |messages, (line, index)|- if index == 0- messages << "#{line}: #{error} (#{error.class})"- else- messages << "\t#{index}: from #{line}"- end+ block.call+ rescue => error+ plugins_directory = Rails.root + "plugins"++ if error.backtrace && error.backtrace_locations+ plugin_path =+ error+ .backtrace_locations+ .lazy+ .map do |location|+ resolved_path = location.absolute_path || location.path+ next if resolved_path.nil?+ Pathname.new(resolved_path).ascend.lazy.find { |path| path.parent == plugins_directory }+ end+ .next++ raise unless plugin_path++ stack_trace =+ error+ .backtrace+ .each_with_index+ .inject([]) do |messages, (line, index)|+ if index == 0+ messages << "#{line}: #{error} (#{error.class})"+ else+ messages << "\t#{index}: from #{line}"end- .reverse- .join("\n")+ end+ .reverse+ .join("\n")- STDERR.puts <<~TEXT+ STDERR.puts <<~TEXT#{stack_trace}** INCOMPATIBLE PLUGIN **@@ -49,8 +44,8 @@ module PluginPlease try removing this plugin and rebuilding again!TEXT- else- STDERR.puts <<~TEXT+ else+ STDERR.puts <<~TEXT** PLUGIN FAILURE **You are unable to start Discourse due to this error during plugin@@ -60,8 +55,7 @@ module Plugin#{error.backtrace.join("\n")}TEXT- end- exit 1end+ exit 1endenddiff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rbindex 98a1f5ec6c9..60fa115c048 100644--- a/lib/plugin/instance.rb+++ b/lib/plugin/instance.rb@@ -677,14 +677,12 @@ class Plugin::Instancedef notify_after_initializeinitializers.each do |callback|- begin- callback.call(self)- rescue ActiveRecord::StatementInvalid => e- # When running `db:migrate` for the first time on a new database,- # plugin initializers might try to use models.- # Tolerate it.- raise e unless e.message.try(:include?, "PG::UndefinedTable")- end+ callback.call(self)+ rescue ActiveRecord::StatementInvalid => e+ # When running `db:migrate` for the first time on a new database,+ # plugin initializers might try to use models.+ # Tolerate it.+ raise e unless e.message.try(:include?, "PG::UndefinedTable")endenddiff --git a/lib/pretty_text.rb b/lib/pretty_text.rbindex 54fe655f738..7cd0428a257 100644--- a/lib/pretty_text.rb+++ b/lib/pretty_text.rb@@ -539,23 +539,21 @@ module PrettyTextdoc.css("a[href]").each do |a|- begin- href = a["href"].to_s- next if href.blank?- next if href.start_with?("mailto:")- next if href.start_with?(Discourse.base_url)- next if URI(href).host.present?-- a["href"] = (- if href.start_with?(Discourse.base_path)- "#{Discourse.base_url_no_prefix}#{href}"- else- "#{Discourse.base_url}#{href}"- end- )- rescue URI::Error- # leave it- end+ href = a["href"].to_s+ next if href.blank?+ next if href.start_with?("mailto:")+ next if href.start_with?(Discourse.base_url)+ next if URI(href).host.present?++ a["href"] = (+ if href.start_with?(Discourse.base_path)+ "#{Discourse.base_url_no_prefix}#{href}"+ else+ "#{Discourse.base_url}#{href}"+ end+ )+ rescue URI::Error+ # leave itendenddiff --git a/lib/s3_helper.rb b/lib/s3_helper.rbindex 36c496b7259..457e016f999 100644--- a/lib/s3_helper.rb+++ b/lib/s3_helper.rb@@ -450,12 +450,10 @@ class S3Helperenddef fetch_bucket_cors_rules- begin- s3_resource.client.get_bucket_cors(bucket: @s3_bucket_name).cors_rules&.map(&:to_h) || []- rescue Aws::S3::Errors::NoSuchCORSConfiguration- # no rule- []- end+ s3_resource.client.get_bucket_cors(bucket: @s3_bucket_name).cors_rules&.map(&:to_h) || []+ rescue Aws::S3::Errors::NoSuchCORSConfiguration+ # no rule+ []enddef default_s3_optionsdiff --git a/lib/s3_inventory.rb b/lib/s3_inventory.rbindex ee5371e52fb..43ed9b0e5b0 100644--- a/lib/s3_inventory.rb+++ b/lib/s3_inventory.rb@@ -46,66 +46,62 @@ class S3InventoryendDistributedMutex.synchronize("s3_inventory_list_missing_#{type}", validity: 30.minutes) do- begin- download_and_decompress_files if !@preloaded_inventory_file+ download_and_decompress_files if !@preloaded_inventory_file- multisite_prefix = Discourse.store.upload_path+ multisite_prefix = Discourse.store.upload_path- ActiveRecord::Base.transaction do- begin- connection.exec(- "CREATE TEMP TABLE #{tmp_table_name}(url text UNIQUE, etag text, PRIMARY KEY(etag, url))",- )+ ActiveRecord::Base.transaction do+ connection.exec(+ "CREATE TEMP TABLE #{tmp_table_name}(url text UNIQUE, etag text, PRIMARY KEY(etag, url))",+ )- connection.copy_data("COPY #{tmp_table_name} FROM STDIN CSV") do- for_each_inventory_row do |row|- key = row[CSV_KEY_INDEX]+ connection.copy_data("COPY #{tmp_table_name} FROM STDIN CSV") do+ for_each_inventory_row do |row|+ key = row[CSV_KEY_INDEX]- next if Rails.configuration.multisite && key.exclude?(multisite_prefix)- next if key.exclude?("#{type}/")+ next if Rails.configuration.multisite && key.exclude?(multisite_prefix)+ next if key.exclude?("#{type}/")- url = File.join(Discourse.store.absolute_base_url, key)- connection.put_copy_data("#{CGI.unescape(url)},#{row[CSV_ETAG_INDEX]}\n")- end- end+ url = File.join(Discourse.store.absolute_base_url, key)+ connection.put_copy_data("#{CGI.unescape(url)},#{row[CSV_ETAG_INDEX]}\n")+ end+ end- table_name = @model.table_name+ table_name = @model.table_name- # backfilling etags- connection.async_exec(- "UPDATE #{table_name}+ # backfilling etags+ connection.async_exec(+ "UPDATE #{table_name}SET etag = #{tmp_table_name}.etagFROM #{tmp_table_name}WHERE #{table_name}.etag IS NULL AND#{table_name}.url = #{tmp_table_name}.url",- )-- uploads = @scope.where("updated_at < ?", inventory_date)-- missing_uploads =- uploads.joins(- "LEFT JOIN #{tmp_table_name} ON #{tmp_table_name}.etag = #{table_name}.etag",- ).where("#{tmp_table_name}.etag IS NULL")-- exists_with_different_etag =- missing_uploads- .joins(- "LEFT JOIN #{tmp_table_name} inventory2 ON inventory2.url = #{table_name}.url",- )- .where.not(inventory2: { etag: nil })- .pluck(:id)-- # marking as verified/not verified- if @model == Upload- sql_params = {- inventory_date: inventory_date,- invalid_etag: Upload.verification_statuses[:invalid_etag],- s3_file_missing_confirmed: Upload.verification_statuses[:s3_file_missing_confirmed],- verified: Upload.verification_statuses[:verified],- seeded_id_threshold: @model::SEEDED_ID_THRESHOLD,- }-- DB.exec(<<~SQL, sql_params)+ )++ uploads = @scope.where("updated_at < ?", inventory_date)++ missing_uploads =+ uploads.joins(+ "LEFT JOIN #{tmp_table_name} ON #{tmp_table_name}.etag = #{table_name}.etag",+ ).where("#{tmp_table_name}.etag IS NULL")++ exists_with_different_etag =+ missing_uploads+ .joins("LEFT JOIN #{tmp_table_name} inventory2 ON inventory2.url = #{table_name}.url")+ .where.not(inventory2: { etag: nil })+ .pluck(:id)++ # marking as verified/not verified+ if @model == Upload+ sql_params = {+ inventory_date: inventory_date,+ invalid_etag: Upload.verification_statuses[:invalid_etag],+ s3_file_missing_confirmed: Upload.verification_statuses[:s3_file_missing_confirmed],+ verified: Upload.verification_statuses[:verified],+ seeded_id_threshold: @model::SEEDED_ID_THRESHOLD,+ }++ DB.exec(<<~SQL, sql_params)UPDATE #{table_name}SET verification_status = :verifiedWHERE etag IS NOT NULL@@ -121,7 +117,7 @@ class S3Inventory)SQL- DB.exec(<<~SQL, sql_params)+ DB.exec(<<~SQL, sql_params)UPDATE #{table_name}SET verification_status = :invalid_etagWHERE verification_status <> :invalid_etag@@ -135,34 +131,32 @@ class S3InventoryWHERE #{tmp_table_name}.etag = #{table_name}.etag)SQL- end+ end- if (missing_count = missing_uploads.count) > 0- missing_uploads- .select(:id, :url)- .find_each do |upload|- if exists_with_different_etag.include?(upload.id)- log "#{upload.url} has different etag"- else- log upload.url- end- end-- log "#{missing_count} of #{uploads.count} #{@scope.name.underscore.pluralize} are missing"- if exists_with_different_etag.present?- log "#{exists_with_different_etag.count} of these are caused by differing etags"- log "Null the etag column and re-run for automatic backfill"+ if (missing_count = missing_uploads.count) > 0+ missing_uploads+ .select(:id, :url)+ .find_each do |upload|+ if exists_with_different_etag.include?(upload.id)+ log "#{upload.url} has different etag"+ else+ log upload.urlendend- set_missing_s3_discourse_stats(missing_count)- ensure- connection.exec("DROP TABLE #{tmp_table_name}") unless connection.nil?+ log "#{missing_count} of #{uploads.count} #{@scope.name.underscore.pluralize} are missing"+ if exists_with_different_etag.present?+ log "#{exists_with_different_etag.count} of these are caused by differing etags"+ log "Null the etag column and re-run for automatic backfill"endend++ set_missing_s3_discourse_stats(missing_count)ensure- cleanup!+ connection.exec("DROP TABLE #{tmp_table_name}") unless connection.nil?end+ ensure+ cleanup!endenddiff --git a/lib/scheduler/defer.rb b/lib/scheduler/defer.rbindex 8cf296cace8..847b4a0460c 100644--- a/lib/scheduler/defer.rb+++ b/lib/scheduler/defer.rb@@ -128,21 +128,19 @@ module Schedulerdb ||= RailsMultisite::ConnectionManagement::DEFAULTRailsMultisite::ConnectionManagement.with_connection(db) do- begin- warning_job =- @reactor.queue(@timeout) do- Rails.logger.error "'#{desc}' is still running after #{@timeout} seconds on db #{db}, this process may need to be restarted!"- end if !non_block- job.call- rescue => ex- @stats_mutex.synchronize do- stats = @stats[desc]- stats[:errors] += 1 if stats- end- Discourse.handle_job_exception(ex, message: "Running deferred code '#{desc}'")- ensure- warning_job&.cancel+ warning_job =+ @reactor.queue(@timeout) do+ Rails.logger.error "'#{desc}' is still running after #{@timeout} seconds on db #{db}, this process may need to be restarted!"+ end if !non_block+ job.call+ rescue => ex+ @stats_mutex.synchronize do+ stats = @stats[desc]+ stats[:errors] += 1 if statsend+ Discourse.handle_job_exception(ex, message: "Running deferred code '#{desc}'")+ ensure+ warning_job&.cancelendrescue => exDiscourse.handle_job_exception(ex, message: "Processing deferred code queue")diff --git a/lib/scheduler/thread_pool.rb b/lib/scheduler/thread_pool.rbindex 7f9308c01de..7ced614f65d 100644--- a/lib/scheduler/thread_pool.rb+++ b/lib/scheduler/thread_pool.rb@@ -114,14 +114,9 @@ module Schedulerdef wrap_block(block, db)proc do- begin- RailsMultisite::ConnectionManagement.with_connection(db) { block.call }- rescue StandardError => e- Discourse.warn_exception(- e,- message: "Discourse Scheduler ThreadPool: Unhandled exception",- )- end+ RailsMultisite::ConnectionManagement.with_connection(db) { block.call }+ rescue StandardError => e+ Discourse.warn_exception(e, message: "Discourse Scheduler ThreadPool: Unhandled exception")endenddiff --git a/lib/search/grouped_search_results.rb b/lib/search/grouped_search_results.rbindex 03830d37712..bb52afd96f7 100644--- a/lib/search/grouped_search_results.rb+++ b/lib/search/grouped_search_results.rb@@ -142,15 +142,13 @@ class Searchurls = Set.newcooked.scan(Discourse::Utils::URI_REGEXP) { urls << $& }urls.each do |url|- begin- case File.extname(URI(url).path || "")- when Oneboxer::VIDEO_REGEX- cooked.gsub!(url, I18n.t("search.video"))- when Oneboxer::AUDIO_REGEX- cooked.gsub!(url, I18n.t("search.audio"))- end- rescue URI::InvalidURIError+ case File.extname(URI(url).path || "")+ when Oneboxer::VIDEO_REGEX+ cooked.gsub!(url, I18n.t("search.video"))+ when Oneboxer::AUDIO_REGEX+ cooked.gsub!(url, I18n.t("search.audio"))end+ rescue URI::InvalidURIErrorendenddiff --git a/lib/signal_trap_logger.rb b/lib/signal_trap_logger.rbindex fcedd18a48a..5012817b773 100644--- a/lib/signal_trap_logger.rb+++ b/lib/signal_trap_logger.rb@@ -35,14 +35,12 @@ class SignalTrapLogger@thread =Thread.new doloop do- begin- log_entry = @queue.pop- log_entry[:logger].public_send(log_entry[:level], log_entry[:message])- rescue => error- Rails.logger.error(- "Error in SignalTrapLogger thread: #{error.message}\n#{error.backtrace.join("\n")}",- )- end+ log_entry = @queue.pop+ log_entry[:logger].public_send(log_entry[:level], log_entry[:message])+ rescue => error+ Rails.logger.error(+ "Error in SignalTrapLogger thread: #{error.message}\n#{error.backtrace.join("\n")}",+ )endendenddiff --git a/lib/site_setting_extension.rb b/lib/site_setting_extension.rbindex d7bbda17785..014f33dc951 100644--- a/lib/site_setting_extension.rb+++ b/lib/site_setting_extension.rb@@ -321,26 +321,24 @@ module SiteSettingExtensionenddef theme_site_settings_json_uncached(theme_id)- begin- # There are a few legit scenarios where the current- # theme ID may be blank, such as safe mode. In this- # case it will be better to return default site setting- # values rather than to cause random/undefined behaviour- # in the UI.- if theme_id.blank?- MultiJson.dump(ThemeSiteSetting.generate_defaults_map)- else- MultiJson.dump(theme_site_settings[theme_id])- end- rescue => err- # If something goes wrong here we really need to be aware of it in tests.- raise err if Rails.env.test?-- Rails.logger.error(- "Error while generating theme_site_settings_json_uncached for theme ID #{theme_id}: #{err.message}",- )- nil+ # There are a few legit scenarios where the current+ # theme ID may be blank, such as safe mode. In this+ # case it will be better to return default site setting+ # values rather than to cause random/undefined behaviour+ # in the UI.+ if theme_id.blank?+ MultiJson.dump(ThemeSiteSetting.generate_defaults_map)+ else+ MultiJson.dump(theme_site_settings[theme_id])end+ rescue => err+ # If something goes wrong here we really need to be aware of it in tests.+ raise err if Rails.env.test?++ Rails.logger.error(+ "Error while generating theme_site_settings_json_uncached for theme ID #{theme_id}: #{err.message}",+ )+ nilenddef all_settings(@@ -679,12 +677,10 @@ module SiteSettingExtensionenddef process_message(message)- begin- MessageBus.on_connect.call(message.site_id)- refresh!- ensure- MessageBus.on_disconnect.call(message.site_id)- end+ MessageBus.on_connect.call(message.site_id)+ refresh!+ ensure+ MessageBus.on_disconnect.call(message.site_id)enddef process_id@@ -1361,9 +1357,10 @@ module SiteSettingExtensiondef default_uploads@default_uploads ||= {}- @default_uploads[provider.current_site] ||= begin- Upload.where("id < ?", Upload::SEEDED_ID_THRESHOLD).pluck(:id, :url).to_h- end+ @default_uploads[provider.current_site] ||= Upload+ .where("id < ?", Upload::SEEDED_ID_THRESHOLD)+ .pluck(:id, :url)+ .to_henddef uploadsdiff --git a/lib/socket_server.rb b/lib/socket_server.rbindex 4c802d8b0d6..c19d9ec2a02 100644--- a/lib/socket_server.rb+++ b/lib/socket_server.rb@@ -26,13 +26,11 @@ class SocketServerdef new_accept_threadserver = @serverThread.new do- begin- done = false- done = !accept_connection(server) while !done- ensure- self.stop- Rails.logger.info("Cleaned up socket server at #{@socket_path}")- end+ done = false+ done = !accept_connection(server) while !done+ ensure+ self.stop+ Rails.logger.info("Cleaned up socket server at #{@socket_path}")endenddiff --git a/lib/stylesheet/manager/builder.rb b/lib/stylesheet/manager/builder.rbindex 66976a1ef86..ba07a32bea6 100644--- a/lib/stylesheet/manager/builder.rb+++ b/lib/stylesheet/manager/builder.rb@@ -153,14 +153,12 @@ class Stylesheet::Manager::Builder# digest encodes the things that trigger a recompiledef digest@digest ||=- begin- if is_theme?- theme_digest- elsif is_color_scheme?- color_scheme_digest- else- default_digest- end+ if is_theme?+ theme_digest+ elsif is_color_scheme?+ color_scheme_digest+ else+ default_digestendenddiff --git a/lib/stylesheet/watcher.rb b/lib/stylesheet/watcher.rbindex 9dbc7da72c9..3ba1c14c434 100644--- a/lib/stylesheet/watcher.rb+++ b/lib/stylesheet/watcher.rb@@ -35,12 +35,10 @@ module Stylesheetdef startThread.new do- begin- worker_loop while true- rescue => e- STDERR.puts "CSS change notifier crashed \n#{e}"- start- end+ worker_loop while true+ rescue => e+ STDERR.puts "CSS change notifier crashed \n#{e}"+ startendlistener_opts = { ignore: [/node_modules/], only: /\.s?css\z/ }diff --git a/lib/svg_sprite.rb b/lib/svg_sprite.rbindex a775ccfd085..eea0e03daf3 100644--- a/lib/svg_sprite.rb+++ b/lib/svg_sprite.rb@@ -378,16 +378,11 @@ module SvgSpritetheme_sprites.map do |(_theme_id, upload_id, sprite)|- begin- [- _theme_id,- symbols_for("theme_#{_theme_id}_#{upload_id}.svg", sprite, strict: false),- ]- rescue => e- Rails.logger.warn(- "Bad XML in custom sprite in theme with ID=#{_theme_id}. Error info: #{e.inspect}",- )- end+ [_theme_id, symbols_for("theme_#{_theme_id}_#{upload_id}.svg", sprite, strict: false)]+ rescue => e+ Rails.logger.warn(+ "Bad XML in custom sprite in theme with ID=#{_theme_id}. Error info: #{e.inspect}",+ )end.compact.to_hdiff --git a/lib/tasks/assets.rake b/lib/tasks/assets.rakeindex 67bec8c3e5d..4cda3f1aefc 100644--- a/lib/tasks/assets.rake+++ b/lib/tasks/assets.rake@@ -56,16 +56,14 @@ task "assets:precompile:css" => "environment" doendtask "assets:flush_sw" => "environment" do- begin- hostname = Discourse.current_hostname- default_port = SiteSetting.force_https? ? 443 : 80- port = SiteSetting.port.to_i > 0 ? SiteSetting.port : default_port- STDERR.puts "Flushing service worker script"- `curl -s -m 1 --resolve '#{hostname}:#{port}:127.0.0.1' #{Discourse.base_url}/service-worker.js > /dev/null`- STDERR.puts "done"- rescue StandardError- STDERR.puts "Warning: unable to flush service worker script"- end+ hostname = Discourse.current_hostname+ default_port = SiteSetting.force_https? ? 443 : 80+ port = SiteSetting.port.to_i > 0 ? SiteSetting.port : default_port+ STDERR.puts "Flushing service worker script"+ `curl -s -m 1 --resolve '#{hostname}:#{port}:127.0.0.1' #{Discourse.base_url}/service-worker.js > /dev/null`+ STDERR.puts "done"+rescue StandardError+ STDERR.puts "Warning: unable to flush service worker script"enddef assets_pathdiff --git a/lib/tasks/db.rake b/lib/tasks/db.rakeindex 80121b37dd0..0280f72e405 100644--- a/lib/tasks/db.rake+++ b/lib/tasks/db.rake@@ -2,16 +2,14 @@# we should set the locale before the migrationtask "set_locale" do- begin- I18n.locale =- begin- SiteSetting.default_locale || :en- rescue StandardError- :en- end- rescue I18n::InvalidLocale- I18n.locale = :en- end+ I18n.locale =+ begin+ SiteSetting.default_locale || :en+ rescue StandardError+ :en+ end+rescue I18n::InvalidLocale+ I18n.locale = :enendmodule MultisiteTestHelpers@@ -250,12 +248,10 @@ task "db:migrate" => %w[end%i[pg_trgm unaccent].each do |extension|- begin- DB.exec "CREATE EXTENSION IF NOT EXISTS #{extension}"- rescue => e- STDERR.puts "Cannot enable database extension #{extension}"- STDERR.puts e- end+ DB.exec "CREATE EXTENSION IF NOT EXISTS #{extension}"+ rescue => e+ STDERR.puts "Cannot enable database extension #{extension}"+ STDERR.puts eendexecute_db_migration@@ -465,11 +461,9 @@ task "db:validate_indexes", [:arg] => %w[db:ensure_post_migrations environment]if fix_indexesputs "Adding missing indexes..."missing.each do |m|- begin- DB.exec(m)- rescue => e- $stderr.puts "Error running: #{m} - #{e}"- end+ DB.exec(m)+ rescue => e+ $stderr.puts "Error running: #{m} - #{e}"endendelse@@ -557,24 +551,20 @@ task "db:rebuild_indexes" => "environment" do"SELECT indexname FROM pg_indexes WHERE schemaname = 'public' AND tablename IN ('#{table_names.join("', '")}')",)index_names.each do |index_name|- begin- puts index_name- DB.exec("DROP INDEX public.#{index_name}")- rescue ActiveRecord::StatementInvalid- # It's this:- # PG::Error: ERROR: cannot drop index category_users_pkey because constraint category_users_pkey on table category_users requires it- # HINT: You can drop constraint category_users_pkey on table category_users instead.- end+ puts index_name+ DB.exec("DROP INDEX public.#{index_name}")+ rescue ActiveRecord::StatementInvalid+ # It's this:+ # PG::Error: ERROR: cannot drop index category_users_pkey because constraint category_users_pkey on table category_users requires it+ # HINT: You can drop constraint category_users_pkey on table category_users instead.end# Create the indexestable_names.each do |table_name|index_definitions[table_name].each do |index_def|- begin- DB.exec(index_def)- rescue ActiveRecord::StatementInvalid- # Trying to recreate a primary key- end+ DB.exec(index_def)+ rescue ActiveRecord::StatementInvalid+ # Trying to recreate a primary keyendendrescue StandardError@@ -587,14 +577,12 @@ enddesc "Check that the DB can be accessed"task "db:status:json" do- begin- Rake::Task["environment"].invoke- DB.query("SELECT 1")- rescue StandardError- puts({ status: "error" }.to_json)- else- puts({ status: "ok" }.to_json)- end+ Rake::Task["environment"].invoke+ DB.query("SELECT 1")+rescue StandardError+ puts({ status: "error" }.to_json)+else+ puts({ status: "ok" }.to_json)enddesc "Grow notification id column to a big int in case of overflow"diff --git a/lib/tasks/emails.rake b/lib/tasks/emails.rakeindex cbf9b73106a..e0929356fc8 100644--- a/lib/tasks/emails.rake+++ b/lib/tasks/emails.rake@@ -1,58 +1,54 @@# frozen_string_literal: truedef process_popmail(popmail)- begin- mail_string = popmail.pop- Email::Receiver.new(mail_string).process- rescue StandardError- putc "!"- else- putc "."- end+ mail_string = popmail.pop+ Email::Receiver.new(mail_string).process+rescue StandardError+ putc "!"+else+ putc "."enddesc "use this task to import a mailbox into Discourse"task "emails:import" => :environment do- begin- unless SiteSetting.email_in- puts "ERROR: you should enable the 'email_in' site setting before running this task"- exit(1)- end+ unless SiteSetting.email_in+ puts "ERROR: you should enable the 'email_in' site setting before running this task"+ exit(1)+ end- address = ENV["ADDRESS"].presence || "pop.gmail.com"- port = (ENV["PORT"].presence || 995).to_i- ssl = (ENV["SSL"].presence || "1") == "1"- username = ENV["USERNAME"].presence- password = ENV["PASSWORD"].presence-- if username.blank?- puts "ERROR: expecting USERNAME=<username> rake emails:import"- exit(2)- elsif password.blank?- puts "ERROR: expecting PASSWORD=<password> rake emails:import"- exit(3)- end+ address = ENV["ADDRESS"].presence || "pop.gmail.com"+ port = (ENV["PORT"].presence || 995).to_i+ ssl = (ENV["SSL"].presence || "1") == "1"+ username = ENV["USERNAME"].presence+ password = ENV["PASSWORD"].presence++ if username.blank?+ puts "ERROR: expecting USERNAME=<username> rake emails:import"+ exit(2)+ elsif password.blank?+ puts "ERROR: expecting PASSWORD=<password> rake emails:import"+ exit(3)+ end- RateLimiter.disable+ RateLimiter.disable- mails_left = 1- pop3 = Net::POP3.new(address, port)- pop3.enable_ssl(max_version: OpenSSL::SSL::TLS1_2_VERSION) if ssl+ mails_left = 1+ pop3 = Net::POP3.new(address, port)+ pop3.enable_ssl(max_version: OpenSSL::SSL::TLS1_2_VERSION) if ssl- while mails_left > 0- pop3.start(username, password) do |pop|- pop.delete_all { |p| process_popmail(p) }- mails_left = pop.n_mails- end+ while mails_left > 0+ pop3.start(username, password) do |pop|+ pop.delete_all { |p| process_popmail(p) }+ mails_left = pop.n_mailsend-- puts "Done"- rescue Net::POPAuthenticationError- puts "AUTH EXCEPTION: please make sure your credentials are correct."- exit(10)- ensure- RateLimiter.enableend++ puts "Done"+rescue Net::POPAuthenticationError+ puts "AUTH EXCEPTION: please make sure your credentials are correct."+ exit(10)+ensure+ RateLimiter.enableenddesc "Check if SMTP connection is successful and send test message"diff --git a/lib/tasks/import.rake b/lib/tasks/import.rakeindex e7abf431acd..4758ce59c3b 100644--- a/lib/tasks/import.rake+++ b/lib/tasks/import.rake@@ -593,32 +593,30 @@ task "import:remap_old_phpbb_permalinks" => :environment doPost.where("raw LIKE ?", "%discussions.example.com%").each do |p|- begin- new_raw = p.raw.dup- # \((https?:\/\/discussions\.example\.com\/\S*-t\d+.html)\)- new_raw.gsub!(%r{\((https?://discussions\.example\.com/\S*-t\d+.html)\)}) do- normalized_url = Permalink.normalize_url($1)- permalink =- begin- Permalink.find_by_url(normalized_url)- rescue StandardError- nil- end- if permalink && permalink.target_url- "(#{permalink.target_url})"- else- "(#{$1})"+ new_raw = p.raw.dup+ # \((https?:\/\/discussions\.example\.com\/\S*-t\d+.html)\)+ new_raw.gsub!(%r{\((https?://discussions\.example\.com/\S*-t\d+.html)\)}) do+ normalized_url = Permalink.normalize_url($1)+ permalink =+ begin+ Permalink.find_by_url(normalized_url)+ rescue StandardError+ nilend+ if permalink && permalink.target_url+ "(#{permalink.target_url})"+ else+ "(#{$1})"end+ end- if new_raw != p.raw- p.revise(Discourse.system_user, { raw: new_raw }, bypass_bump: true, skip_revision: true)- putc "."- i += 1- end- rescue StandardError- # skip+ if new_raw != p.raw+ p.revise(Discourse.system_user, { raw: new_raw }, bypass_bump: true, skip_revision: true)+ putc "."+ i += 1end+ rescue StandardError+ # skipendlog "Done! #{i} posts remapped."diff --git a/lib/tasks/posts.rake b/lib/tasks/posts.rakeindex 75de514490d..bf33b8df698 100644--- a/lib/tasks/posts.rake+++ b/lib/tasks/posts.rake@@ -334,12 +334,10 @@ task "posts:delete_all_likes" => :environment dototal = post_actions.countpost_actions.each do |post_action|- begin- post_action.remove_act!(Discourse.system_user)- print_status(likes_deleted += 1, total)- rescue StandardError- # skip- end+ post_action.remove_act!(Discourse.system_user)+ print_status(likes_deleted += 1, total)+ rescue StandardError+ # skipendUserStat.update_all(likes_given: 0, likes_received: 0) # clear user likes stats@@ -707,19 +705,17 @@ def recover_uploads_from_index(path)endFile.open(found) do |f|- begin- upload = UploadCreator.new(f, "upload").create_for(post.user_id)- if upload && upload.url- post.raw = post.raw.sub(url, upload.url)- changed = true- else- puts "Skipping #{url} in #{post.full_url} unable to create upload (unknown error)"- next- end- rescue Discourse::InvalidAccess- puts "Skipping #{url} in #{post.full_url} unable to create upload (bad format)"+ upload = UploadCreator.new(f, "upload").create_for(post.user_id)+ if upload && upload.url+ post.raw = post.raw.sub(url, upload.url)+ changed = true+ else+ puts "Skipping #{url} in #{post.full_url} unable to create upload (unknown error)"nextend+ rescue Discourse::InvalidAccess+ puts "Skipping #{url} in #{post.full_url} unable to create upload (bad format)"+ nextendendif changeddiff --git a/lib/tasks/themes.rake b/lib/tasks/themes.rakeindex 4adbd81cee9..3ee0baabb92 100644--- a/lib/tasks/themes.rake+++ b/lib/tasks/themes.rake@@ -288,40 +288,38 @@ def update_themes(version_cache: Concurrent::Map.new).includes(:remote_theme).where(enabled: true, auto_update: true).find_each do |theme|- begin- theme.transaction do- remote_theme = theme.remote_theme- next if remote_theme.blank? || remote_theme.remote_url.blank?- prefix = "[db:#{RailsMultisite::ConnectionManagement.current_db}] '#{theme.name}' - "- puts "#{prefix} checking..."-- cache_key =- "#{remote_theme.remote_url}:#{remote_theme.branch}:#{Digest::SHA256.hexdigest(remote_theme.private_key.to_s)}"-- if version_cache[cache_key] == remote_theme.remote_version && !remote_theme.out_of_date?- puts "#{prefix} up to date (cached from previous lookup)"- next- end-- remote_theme.update_remote_version-- version_cache.put_if_absent(cache_key, remote_theme.remote_version)-- if remote_theme.out_of_date?- puts "#{prefix} updating from #{remote_theme.local_version[0..7]} to #{remote_theme.remote_version[0..7]}"- remote_theme.update_from_remote(already_in_transaction: true)- else- puts "#{prefix} up to date"- end-- if remote_theme.last_error_text.present?- raise RemoteTheme::ImportError.new(remote_theme.last_error_text)- end+ theme.transaction do+ remote_theme = theme.remote_theme+ next if remote_theme.blank? || remote_theme.remote_url.blank?+ prefix = "[db:#{RailsMultisite::ConnectionManagement.current_db}] '#{theme.name}' - "+ puts "#{prefix} checking..."++ cache_key =+ "#{remote_theme.remote_url}:#{remote_theme.branch}:#{Digest::SHA256.hexdigest(remote_theme.private_key.to_s)}"++ if version_cache[cache_key] == remote_theme.remote_version && !remote_theme.out_of_date?+ puts "#{prefix} up to date (cached from previous lookup)"+ next+ end++ remote_theme.update_remote_version++ version_cache.put_if_absent(cache_key, remote_theme.remote_version)++ if remote_theme.out_of_date?+ puts "#{prefix} updating from #{remote_theme.local_version[0..7]} to #{remote_theme.remote_version[0..7]}"+ remote_theme.update_from_remote(already_in_transaction: true)+ else+ puts "#{prefix} up to date"+ end++ if remote_theme.last_error_text.present?+ raise RemoteTheme::ImportError.new(remote_theme.last_error_text)end- rescue => e- $stderr.puts "[#{RailsMultisite::ConnectionManagement.current_db}] Failed to update '#{theme.name}' (#{theme.id}): #{e}"- raise if ENV["RAISE_THEME_ERRORS"] == "1"end+ rescue => e+ $stderr.puts "[#{RailsMultisite::ConnectionManagement.current_db}] Failed to update '#{theme.name}' (#{theme.id}): #{e}"+ raise if ENV["RAISE_THEME_ERRORS"] == "1"endtruediff --git a/lib/tasks/uploads.rake b/lib/tasks/uploads.rakeindex 275790a6218..c9538b2838d 100644--- a/lib/tasks/uploads.rake+++ b/lib/tasks/uploads.rake@@ -34,29 +34,27 @@ def gather_uploads.where("url ~ '^\/uploads\/'").where("url !~ ?", "^\/uploads\/#{current_db}").find_each do |upload|- begin- old_db = upload.url[%r{\A/uploads/([^/]+)/}, 1]- from = upload.url.dup- to = upload.url.sub("/uploads/#{old_db}/", "/uploads/#{current_db}/")- source = "#{public_directory}#{from}"- destination = "#{public_directory}#{to}"-- # create destination directory & copy file unless it already exists- unless file_exists?(destination)- `mkdir -p '#{File.dirname(destination)}'`- `cp --link '#{source}' '#{destination}'`- end+ old_db = upload.url[%r{\A/uploads/([^/]+)/}, 1]+ from = upload.url.dup+ to = upload.url.sub("/uploads/#{old_db}/", "/uploads/#{current_db}/")+ source = "#{public_directory}#{from}"+ destination = "#{public_directory}#{to}"++ # create destination directory & copy file unless it already exists+ unless file_exists?(destination)+ `mkdir -p '#{File.dirname(destination)}'`+ `cp --link '#{source}' '#{destination}'`+ end- # ensure file has been successfully copied over- raise unless file_exists?(destination)+ # ensure file has been successfully copied over+ raise unless file_exists?(destination)- # remap links in db- DbHelper.remap(from, to)- rescue StandardError- putc "!"- else- putc "."- end+ # remap links in db+ DbHelper.remap(from, to)+ rescue StandardError+ putc "!"+ else+ putc "."endputs "", "Done!"@@ -72,16 +70,14 @@ task "uploads:backfill_shas" => :environment doUpload.where(sha1: nil).find_each do |u|- begin- path = Discourse.store.path_for(u)- sha1 = Upload.generate_digest(path)- u.sha1 = u.secure? ? SecureRandom.hex(20) : sha1- u.original_sha1 = u.secure? ? sha1 : nil- u.save!- putc "."- rescue => e- puts "Skipping #{u.original_filename} (#{u.url}) #{e.message}"- end+ path = Discourse.store.path_for(u)+ sha1 = Upload.generate_digest(path)+ u.sha1 = u.secure? ? SecureRandom.hex(20) : sha1+ u.original_sha1 = u.secure? ? sha1 : nil+ u.save!+ putc "."+ rescue => e+ puts "Skipping #{u.original_filename} (#{u.url}) #{e.message}"endendputs "", "Done"@@ -102,14 +98,12 @@ enddef migrate_to_s3_all_sitesRailsMultisite::ConnectionManagement.each_connection do- begin- migrate_to_s3- rescue RuntimeError => e- if ENV["SKIP_FAILED"]- puts e- else- raise e unless ENV["SKIP_FAILED"]- end+ migrate_to_s3+ rescue RuntimeError => e+ if ENV["SKIP_FAILED"]+ puts e+ else+ raise e unless ENV["SKIP_FAILED"]endendend@@ -544,11 +538,9 @@ def sync_access_control(async: true, concurrency: 10).map do |upload|Concurrent::Future.execute(executor:) doRailsMultisite::ConnectionManagement.with_connection(current_db) do- begin- Discourse.store.update_upload_access_control(upload, remove_existing_acl: true)- rescue => error- errors << "Error updating access control for upload #{upload.url}: #{error.message}"- end+ Discourse.store.update_upload_access_control(upload, remove_existing_acl: true)+ rescue => error+ errors << "Error updating access control for upload #{upload.url}: #{error.message}"endendenddiff --git a/lib/tasks/users.rake b/lib/tasks/users.rakeindex 0b438d19b9a..d1447a9ccad 100644--- a/lib/tasks/users.rake+++ b/lib/tasks/users.rake@@ -178,12 +178,10 @@ task "users:anonymize_all" => :environment dosystem_user = Discourse.system_usernon_staff_users.each do |user|- begin- UserAnonymizer.new(user, system_user).make_anonymous- print_status(anonymized += 1, total)- rescue StandardError- # skip- end+ UserAnonymizer.new(user, system_user).make_anonymous+ print_status(anonymized += 1, total)+ rescue StandardError+ # skipendputs "", "#{total} users anonymized.", ""diff --git a/lib/theme_settings_manager/string.rb b/lib/theme_settings_manager/string.rbindex 57650c8b283..db9770c14fb 100644--- a/lib/theme_settings_manager/string.rb+++ b/lib/theme_settings_manager/string.rb@@ -6,10 +6,8 @@ class ThemeSettingsManager::String < ThemeSettingsManagerenddef json_schema- begin- JSON.parse(@opts[:json_schema])- rescue StandardError- false- end+ JSON.parse(@opts[:json_schema])+ rescue StandardError+ falseendenddiff --git a/lib/topic_query/private_message_lists.rb b/lib/topic_query/private_message_lists.rbindex fe657a4a965..9c06ba82851 100644--- a/lib/topic_query/private_message_lists.rb+++ b/lib/topic_query/private_message_lists.rb@@ -236,9 +236,7 @@ class TopicQuerydef group@group ||=- begin- Group.where("name ilike ?", @options[:group_name]).select(:id, :publish_read_state).first- end+ Group.where("name ilike ?", @options[:group_name]).select(:id, :publish_read_state).firstenddef user_first_unread_pm_at(user)diff --git a/lib/topic_view.rb b/lib/topic_view.rbindex ad9ce02d46e..93e30c6e02d 100644--- a/lib/topic_view.rb+++ b/lib/topic_view.rb@@ -245,15 +245,13 @@ class TopicViewreturn [] unless SiteSetting.enable_badges && SiteSetting.show_badges_in_post_header@post_user_badges ||=- begin- UserBadge- .for_post_header_badges(@posts)- .reduce({}) do |hash, user_badge|- hash[user_badge.post_id] ||= []- hash[user_badge.post_id] << user_badge- hash- end- end+ UserBadge+ .for_post_header_badges(@posts)+ .reduce({}) do |hash, user_badge|+ hash[user_badge.post_id] ||= []+ hash[user_badge.post_id] << user_badge+ hash+ endreturn [] unless @post_user_badges@@ -290,12 +288,10 @@ class TopicViewreturn unless @contains_gaps@gaps ||=- begin- if is_mega_topic?- nil- else- Gaps.new(filtered_post_ids, apply_default_scope(unfiltered_posts).pluck(:id))- end+ if is_mega_topic?+ nil+ else+ Gaps.new(filtered_post_ids, apply_default_scope(unfiltered_posts).pluck(:id))endend@@ -310,10 +306,8 @@ class TopicViewdef next_page@next_page ||=- begin- if last_post && highest_post_number && (highest_post_number > last_post.post_number)- @page + 1- end+ if last_post && highest_post_number && (highest_post_number > last_post.post_number)+ @page + 1endend@@ -572,11 +566,10 @@ class TopicViewdef post_counts_by_user@post_counts_by_user ||=- begin- if is_mega_topic?- {}- else- sql = <<~SQL+ if is_mega_topic?+ {}+ else+ sql = <<~SQLSELECT user_id, count(*) AS count_allFROM postsWHERE topic_id = :topic_id@@ -589,14 +582,13 @@ class TopicViewLIMIT #{MAX_PARTICIPANTS}SQL- Hash[- *DB.query_single(- sql,- topic_id: @topic.id,- post_types: Topic.visible_post_types(@guardian&.user),- )- ]- end+ Hash[+ *DB.query_single(+ sql,+ topic_id: @topic.id,+ post_types: Topic.visible_post_types(@guardian&.user),+ )+ ]endend@@ -607,22 +599,20 @@ class TopicViewdef participant_count@participant_count ||=- begin- if participants.size == MAX_PARTICIPANTS- if @topic.posts_count > MAX_POSTS_COUNT_PARTICIPANTS- @topic.participant_count- else- sql = <<~SQL+ if participants.size == MAX_PARTICIPANTS+ if @topic.posts_count > MAX_POSTS_COUNT_PARTICIPANTS+ @topic.participant_count+ else+ sql = <<~SQLSELECT COUNT(DISTINCT user_id)FROM postsWHERE id IN (:post_ids)AND user_id IS NOT NULLSQL- DB.query_single(sql, post_ids: unfiltered_post_ids).first.to_i- end- else- participants.size+ DB.query_single(sql, post_ids: unfiltered_post_ids).first.to_iend+ else+ participants.sizeendend@@ -639,10 +629,7 @@ class TopicViewenddef topic_allowed_group_ids- @topic_allowed_group_ids ||=- begin- @topic.allowed_groups.map(&:id)- end+ @topic_allowed_group_ids ||= @topic.allowed_groups.map(&:id)enddef group_allowed_user_ids@@ -654,24 +641,22 @@ class TopicViewdef category_group_moderator_user_ids@category_group_moderator_user_ids ||=- begin- if SiteSetting.enable_category_group_moderation? && @topic.category.present?- posts_user_ids = Set.new(@posts.map(&:user_id))- Set.new(- GroupUser- .joins(- "INNER JOIN category_moderation_groups ON category_moderation_groups.group_id = group_users.group_id",- )- .where(- "category_moderation_groups.category_id": @topic.category.id,- user_id: posts_user_ids,- )- .distinct- .pluck(:user_id),- )- else- Set.new- end+ if SiteSetting.enable_category_group_moderation? && @topic.category.present?+ posts_user_ids = Set.new(@posts.map(&:user_id))+ Set.new(+ GroupUser+ .joins(+ "INNER JOIN category_moderation_groups ON category_moderation_groups.group_id = group_users.group_id",+ )+ .where(+ "category_moderation_groups.category_id": @topic.category.id,+ user_id: posts_user_ids,+ )+ .distinct+ .pluck(:user_id),+ )+ else+ Set.newendend@@ -845,12 +830,10 @@ class TopicViewdef unfiltered_post_ids@unfiltered_post_ids ||=- begin- if @contains_gaps- unfiltered_posts.pluck(:id)- else- filtered_post_ids- end+ if @contains_gaps+ unfiltered_posts.pluck(:id)+ else+ filtered_post_idsendenddiff --git a/lib/upload_recovery.rb b/lib/upload_recovery.rbindex 7f2c52d6e60..6261d9ee9e3 100644--- a/lib/upload_recovery.rb+++ b/lib/upload_recovery.rb@@ -11,43 +11,41 @@ class UploadRecoveryenddef recover_post(post)- begin- analyzer = PostAnalyzer.new(post.raw, post.topic_id)-- analyzer- .cooked_stripped- .css("img", "a")- .each do |media|- if media.name == "img" && orig_src = media["data-orig-src"]- if dom_class = media["class"]- next if (Post.allowed_image_classes & dom_class.split).count > 0- end+ analyzer = PostAnalyzer.new(post.raw, post.topic_id)++ analyzer+ .cooked_stripped+ .css("img", "a")+ .each do |media|+ if media.name == "img" && orig_src = media["data-orig-src"]+ if dom_class = media["class"]+ next if (Post.allowed_image_classes & dom_class.split).count > 0+ end++ if @dry_run+ puts "#{post.full_url} #{orig_src}"+ else+ recover_post_upload(post, Upload.sha1_from_short_url(orig_src))+ end+ elsif url = media["href"] || media["src"]+ data = Upload.extract_url(url)+ next unless data++ upload = Upload.get_from_url(url)+ if !upload || upload.verification_status == Upload.verification_statuses[:invalid_etag]if @dry_run- puts "#{post.full_url} #{orig_src}"+ puts "#{post.full_url} #{url}"else- recover_post_upload(post, Upload.sha1_from_short_url(orig_src))- end- elsif url = media["href"] || media["src"]- data = Upload.extract_url(url)- next unless data-- upload = Upload.get_from_url(url)-- if !upload || upload.verification_status == Upload.verification_statuses[:invalid_etag]- if @dry_run- puts "#{post.full_url} #{url}"- else- sha1 = data[2]- recover_post_upload(post, sha1)- end+ sha1 = data[2]+ recover_post_upload(post, sha1)endendend- rescue => e- raise e if @stop_on_error- puts "#{post.full_url} #{e.class}: #{e.message}"- end+ end+ rescue => e+ raise e if @stop_on_error+ puts "#{post.full_url} #{e.class}: #{e.message}"endprivate@@ -95,11 +93,9 @@ class UploadRecoverydef recover_from_local(sha1:, user_id:)@paths ||=- begin- Dir.glob(File.join(Discourse.store.tombstone_dir, "original", "**", "*.*")).concat(- Dir.glob(File.join(Discourse.store.upload_path, "original", "**", "*.*")),- )- end+ Dir.glob(File.join(Discourse.store.tombstone_dir, "original", "**", "*.*")).concat(+ Dir.glob(File.join(Discourse.store.upload_path, "original", "**", "*.*")),+ )@paths.each do |path|if path =~ /#{sha1}/diff --git a/lib/validators/form_template_yaml_validator.rb b/lib/validators/form_template_yaml_validator.rbindex 3294b0a3889..e4c722b4945 100644--- a/lib/validators/form_template_yaml_validator.rb+++ b/lib/validators/form_template_yaml_validator.rb@@ -16,26 +16,24 @@ class FormTemplateYamlValidator < ActiveModel::Validator}def validate(record)- begin- yaml = Psych.safe_load(record.template)-- unless yaml.is_a?(Array)- record.errors.add(:template, I18n.t("form_templates.errors.invalid_yaml"))- return- end-- existing_ids = []- yaml.each do |field|- check_missing_fields(record, field)- check_allowed_types(record, field)- check_ids(record, field, existing_ids)- check_descriptions_html(record, field)- end-- check_tag_groups(record, yaml.map { |f| f["tag_group"] })- rescue Psych::SyntaxError+ yaml = Psych.safe_load(record.template)++ unless yaml.is_a?(Array)record.errors.add(:template, I18n.t("form_templates.errors.invalid_yaml"))+ return+ end++ existing_ids = []+ yaml.each do |field|+ check_missing_fields(record, field)+ check_allowed_types(record, field)+ check_ids(record, field, existing_ids)+ check_descriptions_html(record, field)end++ check_tag_groups(record, yaml.map { |f| f["tag_group"] })+ rescue Psych::SyntaxError+ record.errors.add(:template, I18n.t("form_templates.errors.invalid_yaml"))enddef check_allowed_types(record, field)diff --git a/lib/validators/regexp_list_validator.rb b/lib/validators/regexp_list_validator.rbindex 23ddfc39bf4..c1b18460108 100644--- a/lib/validators/regexp_list_validator.rb+++ b/lib/validators/regexp_list_validator.rb@@ -8,13 +8,11 @@ class RegexpListValidatorvalue.split("|").all? do |regexp|- begin- Regexp.new(regexp)- rescue RegexpError => e- @regexp = regexp- @error_message = e.message- false- end+ Regexp.new(regexp)+ rescue RegexpError => e+ @regexp = regexp+ @error_message = e.message+ falseendenddiff --git a/migrations/lib/converters/base/worker.rb b/migrations/lib/converters/base/worker.rbindex 41c2560624d..a424b5dacfa 100644--- a/migrations/lib/converters/base/worker.rb+++ b/migrations/lib/converters/base/worker.rb@@ -53,21 +53,19 @@ module Migrationsfork_output_stream)ForkManager.fork do- begin- Process.setproctitle("worker_process#{@index}")+ Process.setproctitle("worker_process#{@index}")- parent_output_stream.close- fork_input_stream.close+ parent_output_stream.close+ fork_input_stream.close- Oj.load(parent_input_stream, OJ_SETTINGS) do |data|- result = @job.run(data)- Oj.to_stream(fork_output_stream, result, OJ_SETTINGS)- end- rescue SignalException- exit(1)- ensure- @job.cleanup+ Oj.load(parent_input_stream, OJ_SETTINGS) do |data|+ result = @job.run(data)+ Oj.to_stream(fork_output_stream, result, OJ_SETTINGS)end+ rescue SignalException+ exit(1)+ ensure+ @job.cleanupendenddiff --git a/migrations/lib/uploader/tasks/uploader.rb b/migrations/lib/uploader/tasks/uploader.rbindex a5153e5a487..f1edf655f4d 100644--- a/migrations/lib/uploader/tasks/uploader.rb+++ b/migrations/lib/uploader/tasks/uploader.rb@@ -153,17 +153,15 @@ module Migrationswith_retries doupload =copy_to_tempfile(path) do |file|- begin- UploadCreator.new(- file,- metadata.original_filename,- type: row[:type],- origin: metadata.origin_url,- ).create_for(Discourse::SYSTEM_USER_ID)- rescue StandardError => e- error_message = e.message- nil- end+ UploadCreator.new(+ file,+ metadata.original_filename,+ type: row[:type],+ origin: metadata.origin_url,+ ).create_for(Discourse::SYSTEM_USER_ID)+ rescue StandardError => e+ error_message = e.message+ nilendif (upload_okay = upload.present? && upload.persisted? && upload.errors.blank?)diff --git a/migrations/migrations.rb b/migrations/migrations.rbindex e45bd5eb681..9401e3c3350 100644--- a/migrations/migrations.rb+++ b/migrations/migrations.rb@@ -25,13 +25,11 @@ module Migrationsrails_root = File.expand_path("..", __dir__)# rubocop:disable Discourse/NoChdirDir.chdir(rails_root) do- begin- ENV["DISCOURSE_DEV_ALLOW_HTTPS"] = "1" # suppress warning- require File.join(rails_root, "config/environment")- rescue LoadError => e- $stderr.puts e.message- raise- end+ ENV["DISCOURSE_DEV_ALLOW_HTTPS"] = "1" # suppress warning+ require File.join(rails_root, "config/environment")+ rescue LoadError => e+ $stderr.puts e.message+ raiseend# rubocop:enable Discourse/NoChdirdiff --git a/plugins/chat/db/migrate/20210706214013_rename_topic_chats_to_chat_channels.rb b/plugins/chat/db/migrate/20210706214013_rename_topic_chats_to_chat_channels.rbindex 134417d385f..6faff5d4e5a 100644--- a/plugins/chat/db/migrate/20210706214013_rename_topic_chats_to_chat_channels.rb+++ b/plugins/chat/db/migrate/20210706214013_rename_topic_chats_to_chat_channels.rb@@ -2,28 +2,26 @@class RenameTopicChatsToChatChannels < ActiveRecord::Migration[6.1]def up- begin- Migration::SafeMigrate.disable!+ Migration::SafeMigrate.disable!- # Trash all existing chat info- DB.exec("DELETE FROM topic_chats")- DB.exec("DELETE FROM topic_chat_messages")+ # Trash all existing chat info+ DB.exec("DELETE FROM topic_chats")+ DB.exec("DELETE FROM topic_chat_messages")- # topic_chat table changes- rename_table :topic_chats, :chat_channels- rename_column :chat_channels, :topic_id, :chatable_id- change_column :chat_channels, :chatable_id, :integer, unique: false- add_column :chat_channels, :chatable_type, :string- change_column_null :chat_channels, :chatable_type, false- add_index :chat_channels, %i[chatable_id chatable_type]+ # topic_chat table changes+ rename_table :topic_chats, :chat_channels+ rename_column :chat_channels, :topic_id, :chatable_id+ change_column :chat_channels, :chatable_id, :integer, unique: false+ add_column :chat_channels, :chatable_type, :string+ change_column_null :chat_channels, :chatable_type, false+ add_index :chat_channels, %i[chatable_id chatable_type]- # topic_chat_messages table changes- rename_table :topic_chat_messages, :chat_messages- rename_column :chat_messages, :topic_id, :chat_channel_id- change_column_null :chat_messages, :post_id, true # Don't require post_id- ensure- Migration::SafeMigrate.enable!- end+ # topic_chat_messages table changes+ rename_table :topic_chat_messages, :chat_messages+ rename_column :chat_messages, :topic_id, :chat_channel_id+ change_column_null :chat_messages, :post_id, true # Don't require post_id+ ensure+ Migration::SafeMigrate.enable!enddef downdiff --git a/plugins/discourse-ai/app/controllers/discourse_ai/summarization/chat_summary_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/summarization/chat_summary_controller.rbindex 2a2b7213531..f75c4fcb540 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/summarization/chat_summary_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/summarization/chat_summary_controller.rb@@ -25,20 +25,18 @@ module DiscourseAiRateLimiter.new(current_user, "channel_summary", 6, 5.minutes).performed!hijack do- begin- strategy = DiscourseAi::Summarization::Strategies::ChatMessages.new(channel, since)-- summarized_text =- if strategy.targets_data.empty?- I18n.t("discourse_ai.summarization.chat.no_targets")- else- summarizer.summarize(current_user)&.summarized_text- end-- render json: { summary: summarized_text }- rescue LlmCreditAllocation::CreditLimitExceeded => e- render_credit_limit_error(e)- end+ strategy = DiscourseAi::Summarization::Strategies::ChatMessages.new(channel, since)++ summarized_text =+ if strategy.targets_data.empty?+ I18n.t("discourse_ai.summarization.chat.no_targets")+ else+ summarizer.summarize(current_user)&.summarized_text+ end++ render json: { summary: summarized_text }+ rescue LlmCreditAllocation::CreditLimitExceeded => e+ render_credit_limit_error(e)endendenddiff --git a/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rbindex 99294241bc2..b580d1a974b 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rb@@ -74,11 +74,9 @@ module DiscourseAienddef rate_limit!- begin- RateLimiter.new(current_user, "ai_translate_post", 3, 5.minutes).performed!- rescue RateLimiter::LimitExceeded- render_json_error(I18n.t("rate_limiter.slow_down"))- end+ RateLimiter.new(current_user, "ai_translate_post", 3, 5.minutes).performed!+ rescue RateLimiter::LimitExceeded+ render_json_error(I18n.t("rate_limiter.slow_down"))enddef find_untranslated_posts(topic, guardian)diff --git a/plugins/discourse-ai/app/jobs/regular/detect_translate_post.rb b/plugins/discourse-ai/app/jobs/regular/detect_translate_post.rbindex 9f824540b1f..e7a95948766 100644--- a/plugins/discourse-ai/app/jobs/regular/detect_translate_post.rb+++ b/plugins/discourse-ai/app/jobs/regular/detect_translate_post.rb@@ -81,15 +81,13 @@ module Jobsprivatedef localize(post, locale)- begin- DiscourseAi::Translation::PostLocalizer.localize(post, locale)- rescue FinalDestination::SSRFDetector::LookupFailedError- # do nothing, there are too many sporadic lookup failures- rescue => e- DiscourseAi::Translation::VerboseLogger.log(- "Failed to translate post #{post.id} to #{locale}: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",- )- end+ DiscourseAi::Translation::PostLocalizer.localize(post, locale)+ rescue FinalDestination::SSRFDetector::LookupFailedError+ # do nothing, there are too many sporadic lookup failures+ rescue => e+ DiscourseAi::Translation::VerboseLogger.log(+ "Failed to translate post #{post.id} to #{locale}: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",+ )endendenddiff --git a/plugins/discourse-ai/app/jobs/regular/generate_inferred_concepts.rb b/plugins/discourse-ai/app/jobs/regular/generate_inferred_concepts.rbindex 38038d10c4c..2e142c65bae 100644--- a/plugins/discourse-ai/app/jobs/regular/generate_inferred_concepts.rb+++ b/plugins/discourse-ai/app/jobs/regular/generate_inferred_concepts.rb@@ -40,13 +40,11 @@ module Jobsmanager = DiscourseAi::InferredConcepts::Manager.newitems.each do |item|- begin- process_item(item, item_type, match_only, manager)- rescue => e- Rails.logger.error(- "Error generating concepts from #{item_type.singularize} #{item.id}: #{e.message}\n#{e.backtrace.join("\n")}",- )- end+ process_item(item, item_type, match_only, manager)+ rescue => e+ Rails.logger.error(+ "Error generating concepts from #{item_type.singularize} #{item.id}: #{e.message}\n#{e.backtrace.join("\n")}",+ )endenddiff --git a/plugins/discourse-ai/app/jobs/scheduled/categories_locale_detection_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/categories_locale_detection_backfill.rbindex 7331b193fa0..04021d5e954 100644--- a/plugins/discourse-ai/app/jobs/scheduled/categories_locale_detection_backfill.rb+++ b/plugins/discourse-ai/app/jobs/scheduled/categories_locale_detection_backfill.rb@@ -32,14 +32,12 @@ module Jobsreturn if categories.empty?categories.each do |category|- begin- DiscourseAi::Translation::CategoryLocaleDetector.detect_locale(category)- rescue FinalDestination::SSRFDetector::LookupFailedError- rescue => e- DiscourseAi::Translation::VerboseLogger.log(- "Failed to detect category #{category.id}'s locale: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",- )- end+ DiscourseAi::Translation::CategoryLocaleDetector.detect_locale(category)+ rescue FinalDestination::SSRFDetector::LookupFailedError+ rescue => e+ DiscourseAi::Translation::VerboseLogger.log(+ "Failed to detect category #{category.id}'s locale: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",+ )endDiscourseAi::Translation::VerboseLogger.log("Detected #{categories.size} category locales")diff --git a/plugins/discourse-ai/app/jobs/scheduled/posts_locale_detection_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/posts_locale_detection_backfill.rbindex f36e50167ca..a4087bc88d2 100644--- a/plugins/discourse-ai/app/jobs/scheduled/posts_locale_detection_backfill.rb+++ b/plugins/discourse-ai/app/jobs/scheduled/posts_locale_detection_backfill.rb@@ -31,17 +31,15 @@ module Jobsreturn if posts.empty?posts.each do |post|- begin- next if !DiscourseAi::Translation::PostLocalizer.has_relocalize_quota?(post, "")-- DiscourseAi::Translation::PostLocaleDetector.detect_locale(post)- rescue FinalDestination::SSRFDetector::LookupFailedError- # do nothing, there are too many sporadic lookup failures- rescue => e- DiscourseAi::Translation::VerboseLogger.log(- "Failed to detect post #{post.id}'s locale: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",- )- end+ next if !DiscourseAi::Translation::PostLocalizer.has_relocalize_quota?(post, "")++ DiscourseAi::Translation::PostLocaleDetector.detect_locale(post)+ rescue FinalDestination::SSRFDetector::LookupFailedError+ # do nothing, there are too many sporadic lookup failures+ rescue => e+ DiscourseAi::Translation::VerboseLogger.log(+ "Failed to detect post #{post.id}'s locale: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",+ )endDiscourseAi::Translation::VerboseLogger.log("Detected #{posts.size} post locales")diff --git a/plugins/discourse-ai/app/jobs/scheduled/tags_locale_detection_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/tags_locale_detection_backfill.rbindex 47a6955d223..cbeafc56d60 100644--- a/plugins/discourse-ai/app/jobs/scheduled/tags_locale_detection_backfill.rb+++ b/plugins/discourse-ai/app/jobs/scheduled/tags_locale_detection_backfill.rb@@ -27,14 +27,12 @@ module Jobsreturn if tags.empty?tags.each do |tag|- begin- DiscourseAi::Translation::TagLocaleDetector.detect_locale(tag)- rescue FinalDestination::SSRFDetector::LookupFailedError- rescue => e- DiscourseAi::Translation::VerboseLogger.log(- "Failed to detect tag #{tag.id}'s locale: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",- )- end+ DiscourseAi::Translation::TagLocaleDetector.detect_locale(tag)+ rescue FinalDestination::SSRFDetector::LookupFailedError+ rescue => e+ DiscourseAi::Translation::VerboseLogger.log(+ "Failed to detect tag #{tag.id}'s locale: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",+ )endDiscourseAi::Translation::VerboseLogger.log("Detected #{tags.size} tag locales")diff --git a/plugins/discourse-ai/app/jobs/scheduled/topics_locale_detection_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/topics_locale_detection_backfill.rbindex c1a28b39a7d..b74c8f3647b 100644--- a/plugins/discourse-ai/app/jobs/scheduled/topics_locale_detection_backfill.rb+++ b/plugins/discourse-ai/app/jobs/scheduled/topics_locale_detection_backfill.rb@@ -31,15 +31,13 @@ module Jobsreturn if topics.empty?topics.each do |topic|- begin- DiscourseAi::Translation::TopicLocaleDetector.detect_locale(topic)- rescue FinalDestination::SSRFDetector::LookupFailedError- # do nothing, there are too many sporadic lookup failures- rescue => e- DiscourseAi::Translation::VerboseLogger.log(- "Failed to detect topic #{topic.id}'s locale: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",- )- end+ DiscourseAi::Translation::TopicLocaleDetector.detect_locale(topic)+ rescue FinalDestination::SSRFDetector::LookupFailedError+ # do nothing, there are too many sporadic lookup failures+ rescue => e+ DiscourseAi::Translation::VerboseLogger.log(+ "Failed to detect topic #{topic.id}'s locale: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",+ )endDiscourseAi::Translation::VerboseLogger.log("Detected #{topics.size} topic locales")diff --git a/plugins/discourse-ai/app/models/embedding_definition.rb b/plugins/discourse-ai/app/models/embedding_definition.rbindex ab8188be7c5..bdf5ac9d913 100644--- a/plugins/discourse-ai/app/models/embedding_definition.rb+++ b/plugins/discourse-ai/app/models/embedding_definition.rb@@ -34,93 +34,90 @@ class EmbeddingDefinition < ActiveRecord::Baseenddef presets- @presets ||=- begin- [- {- preset_id: "bge-large-en",- display_name: "bge-large-en",- dimensions: 1024,- max_sequence_length: 512,- pg_function: "<#>",- tokenizer_class: "DiscourseAi::Tokenizer::BgeLargeEnTokenizer",- provider: HUGGING_FACE,- search_prompt: "Represent this sentence for searching relevant passages:",- },- {- preset_id: "bge-m3",- display_name: "bge-m3",- dimensions: 1024,- max_sequence_length: 8192,- pg_function: "<#>",- tokenizer_class: "DiscourseAi::Tokenizer::BgeM3Tokenizer",- provider: HUGGING_FACE,- },- {- preset_id: "gemini-embedding-001",- display_name: "Gemini's gemini-embedding-001",- dimensions: 3072,- max_sequence_length: 1536,- pg_function: "<=>",- url:- "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent",- tokenizer_class: "DiscourseAi::Tokenizer::GeminiTokenizer",- provider: GOOGLE,- },- {- preset_id: "multilingual-e5-large",- display_name: "multilingual-e5-large",- dimensions: 1024,- max_sequence_length: 512,- pg_function: "<=>",- tokenizer_class: "DiscourseAi::Tokenizer::MultilingualE5LargeTokenizer",- provider: HUGGING_FACE,- },- # "text-embedding-3-large" real dimentions are 3072, but we only support up to 2000 in the- # indexes, so we downsample to 2000 via API.- {- preset_id: "text-embedding-3-large",- display_name: "text-embedding-3-large",- dimensions: 2000,- max_sequence_length: 8191,- pg_function: "<=>",- tokenizer_class: "DiscourseAi::Tokenizer::OpenAiCl100kTokenizer",- url: "https://api.openai.com/v1/embeddings",- provider: OPEN_AI,- matryoshka_dimensions: true,- provider_params: {- model_name: "text-embedding-3-large",- },- },- {- preset_id: "text-embedding-3-small",- display_name: "text-embedding-3-small",- dimensions: 1536,- max_sequence_length: 8191,- pg_function: "<=>",- tokenizer_class: "DiscourseAi::Tokenizer::OpenAiCl100kTokenizer",- url: "https://api.openai.com/v1/embeddings",- provider: OPEN_AI,- matryoshka_dimensions: true,- provider_params: {- model_name: "text-embedding-3-small",- },- },- {- preset_id: "text-embedding-ada-002",- display_name: "text-embedding-ada-002",- dimensions: 1536,- max_sequence_length: 8191,- pg_function: "<=>",- tokenizer_class: "DiscourseAi::Tokenizer::OpenAiCl100kTokenizer",- url: "https://api.openai.com/v1/embeddings",- provider: OPEN_AI,- provider_params: {- model_name: "text-embedding-ada-002",- },- },- ]- end+ @presets ||= [+ {+ preset_id: "bge-large-en",+ display_name: "bge-large-en",+ dimensions: 1024,+ max_sequence_length: 512,+ pg_function: "<#>",+ tokenizer_class: "DiscourseAi::Tokenizer::BgeLargeEnTokenizer",+ provider: HUGGING_FACE,+ search_prompt: "Represent this sentence for searching relevant passages:",+ },+ {+ preset_id: "bge-m3",+ display_name: "bge-m3",+ dimensions: 1024,+ max_sequence_length: 8192,+ pg_function: "<#>",+ tokenizer_class: "DiscourseAi::Tokenizer::BgeM3Tokenizer",+ provider: HUGGING_FACE,+ },+ {+ preset_id: "gemini-embedding-001",+ display_name: "Gemini's gemini-embedding-001",+ dimensions: 3072,+ max_sequence_length: 1536,+ pg_function: "<=>",+ url:+ "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent",+ tokenizer_class: "DiscourseAi::Tokenizer::GeminiTokenizer",+ provider: GOOGLE,+ },+ {+ preset_id: "multilingual-e5-large",+ display_name: "multilingual-e5-large",+ dimensions: 1024,+ max_sequence_length: 512,+ pg_function: "<=>",+ tokenizer_class: "DiscourseAi::Tokenizer::MultilingualE5LargeTokenizer",+ provider: HUGGING_FACE,+ },+ # "text-embedding-3-large" real dimentions are 3072, but we only support up to 2000 in the+ # indexes, so we downsample to 2000 via API.+ {+ preset_id: "text-embedding-3-large",+ display_name: "text-embedding-3-large",+ dimensions: 2000,+ max_sequence_length: 8191,+ pg_function: "<=>",+ tokenizer_class: "DiscourseAi::Tokenizer::OpenAiCl100kTokenizer",+ url: "https://api.openai.com/v1/embeddings",+ provider: OPEN_AI,+ matryoshka_dimensions: true,+ provider_params: {+ model_name: "text-embedding-3-large",+ },+ },+ {+ preset_id: "text-embedding-3-small",+ display_name: "text-embedding-3-small",+ dimensions: 1536,+ max_sequence_length: 8191,+ pg_function: "<=>",+ tokenizer_class: "DiscourseAi::Tokenizer::OpenAiCl100kTokenizer",+ url: "https://api.openai.com/v1/embeddings",+ provider: OPEN_AI,+ matryoshka_dimensions: true,+ provider_params: {+ model_name: "text-embedding-3-small",+ },+ },+ {+ preset_id: "text-embedding-ada-002",+ display_name: "text-embedding-ada-002",+ dimensions: 1536,+ max_sequence_length: 8191,+ pg_function: "<=>",+ tokenizer_class: "DiscourseAi::Tokenizer::OpenAiCl100kTokenizer",+ url: "https://api.openai.com/v1/embeddings",+ provider: OPEN_AI,+ provider_params: {+ model_name: "text-embedding-ada-002",+ },+ },+ ]endenddiff --git a/plugins/discourse-ai/db/migrate/20240726164937_fix_ai_summaries_sequence.rb b/plugins/discourse-ai/db/migrate/20240726164937_fix_ai_summaries_sequence.rbindex 918afc57ac0..55f359db718 100644--- a/plugins/discourse-ai/db/migrate/20240726164937_fix_ai_summaries_sequence.rb+++ b/plugins/discourse-ai/db/migrate/20240726164937_fix_ai_summaries_sequence.rb@@ -2,8 +2,7 @@class FixAiSummariesSequence < ActiveRecord::Migration[7.0]def up- begin- execute <<-SQL+ execute <<-SQLSELECTSETVAL ('ai_summaries_id_seq',@@ -27,9 +26,8 @@ class FixAiSummariesSequence < ActiveRecord::Migration[7.0]true);SQL- rescue ActiveRecord::StatementInvalid => e- # if the summary_table does not exist, we can ignore the error- end+ rescue ActiveRecord::StatementInvalid => e+ # if the summary_table does not exist, we can ignore the errorenddef downdiff --git a/plugins/discourse-ai/discourse_automation/llm_report.rb b/plugins/discourse-ai/discourse_automation/llm_report.rbindex 6384b1350df..223a52778c1 100644--- a/plugins/discourse-ai/discourse_automation/llm_report.rb+++ b/plugins/discourse-ai/discourse_automation/llm_report.rb@@ -58,77 +58,75 @@ if defined?(DiscourseAutomation)field :debug_mode, component: :booleanscript do |context, fields, automation|- begin- sender = fields.dig("sender", "value")- receivers = fields.dig("receivers", "value")- topic_id = fields.dig("topic_id", "value")- title = fields.dig("title", "value")- model = fields.dig("model", "value")- category_ids = fields.dig("categories", "value")- tags = fields.dig("tags", "value")- allow_secure_categories = !!fields.dig("allow_secure_categories", "value")- debug_mode = !!fields.dig("debug_mode", "value")- sample_size = fields.dig("sample_size", "value")- instructions = fields.dig("instructions", "value")- days = fields.dig("days", "value")- offset = fields.dig("offset", "value").to_i- priority_group = fields.dig("priority_group", "value")- tokens_per_post = fields.dig("tokens_per_post", "value")- agent_id = fields.dig("agent_id", "value")+ sender = fields.dig("sender", "value")+ receivers = fields.dig("receivers", "value")+ topic_id = fields.dig("topic_id", "value")+ title = fields.dig("title", "value")+ model = fields.dig("model", "value")+ category_ids = fields.dig("categories", "value")+ tags = fields.dig("tags", "value")+ allow_secure_categories = !!fields.dig("allow_secure_categories", "value")+ debug_mode = !!fields.dig("debug_mode", "value")+ sample_size = fields.dig("sample_size", "value")+ instructions = fields.dig("instructions", "value")+ days = fields.dig("days", "value")+ offset = fields.dig("offset", "value").to_i+ priority_group = fields.dig("priority_group", "value")+ tokens_per_post = fields.dig("tokens_per_post", "value")+ agent_id = fields.dig("agent_id", "value")- exclude_category_ids = fields.dig("exclude_categories", "value")- exclude_tags = fields.dig("exclude_tags", "value")+ exclude_category_ids = fields.dig("exclude_categories", "value")+ exclude_tags = fields.dig("exclude_tags", "value")- top_p = fields.dig("top_p", "value")- if top_p == "" || top_p.nil?- top_p = nil- else- top_p = top_p.to_f- end+ top_p = fields.dig("top_p", "value")+ if top_p == "" || top_p.nil?+ top_p = nil+ else+ top_p = top_p.to_f+ end- temperature = fields.dig("temperature", "value")- if temperature == "" || temperature.nil?- temperature = nil- else- temperature = temperature.to_f- end+ temperature = fields.dig("temperature", "value")+ if temperature == "" || temperature.nil?+ temperature = nil+ else+ temperature = temperature.to_f+ end- # Backwards-compat for scripts created before this field was added.- if agent_id == "" || agent_id.nil?- agent_id = DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::ReportRunner]- end+ # Backwards-compat for scripts created before this field was added.+ if agent_id == "" || agent_id.nil?+ agent_id = DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::ReportRunner]+ end- suppress_notifications = !!fields.dig("suppress_notifications", "value")- DiscourseAi::Automation::ReportRunner.run!(- sender_username: sender,- receivers: receivers,- topic_id: topic_id,- title: title,- agent_id: agent_id,- model: model,- category_ids: category_ids,- tags: tags,- allow_secure_categories: allow_secure_categories,- debug_mode: debug_mode,- sample_size: sample_size,- instructions: instructions,- days: days,- offset: offset,- priority_group_id: priority_group,- tokens_per_post: tokens_per_post,- exclude_category_ids: exclude_category_ids,- exclude_tags: exclude_tags,- temperature: temperature,- top_p: top_p,- suppress_notifications: suppress_notifications,- automation: self.automation,- )- rescue => e- Discourse.warn_exception e, message: "Error running LLM report!"- if Rails.env.development?- p e- puts e.backtrace- end+ suppress_notifications = !!fields.dig("suppress_notifications", "value")+ DiscourseAi::Automation::ReportRunner.run!(+ sender_username: sender,+ receivers: receivers,+ topic_id: topic_id,+ title: title,+ agent_id: agent_id,+ model: model,+ category_ids: category_ids,+ tags: tags,+ allow_secure_categories: allow_secure_categories,+ debug_mode: debug_mode,+ sample_size: sample_size,+ instructions: instructions,+ days: days,+ offset: offset,+ priority_group_id: priority_group,+ tokens_per_post: tokens_per_post,+ exclude_category_ids: exclude_category_ids,+ exclude_tags: exclude_tags,+ temperature: temperature,+ top_p: top_p,+ suppress_notifications: suppress_notifications,+ automation: self.automation,+ )+ rescue => e+ Discourse.warn_exception e, message: "Error running LLM report!"+ if Rails.env.development?+ p e+ puts e.backtraceendendenddiff --git a/plugins/discourse-ai/evals/lib/llm_repository.rb b/plugins/discourse-ai/evals/lib/llm_repository.rbindex fe957df9a28..eb79ff7d0c7 100644--- a/plugins/discourse-ai/evals/lib/llm_repository.rb+++ b/plugins/discourse-ai/evals/lib/llm_repository.rb@@ -41,12 +41,10 @@ module DiscourseAidef all_available_modelsconfigs.keys.filter_map do |config_name|- begin- hydrate(config_name)- rescue => e- puts "Failed to hydrate #{config_name}: #{e.message}" unless Rails.env.test?- nil- end+ hydrate(config_name)+ rescue => e+ puts "Failed to hydrate #{config_name}: #{e.message}" unless Rails.env.test?+ nilendenddiff --git a/plugins/discourse-ai/lib/agents/artifact_update_strategies/diff.rb b/plugins/discourse-ai/lib/agents/artifact_update_strategies/diff.rbindex d7f9b5d25ce..5a9260d26f0 100644--- a/plugins/discourse-ai/lib/agents/artifact_update_strategies/diff.rb+++ b/plugins/discourse-ai/lib/agents/artifact_update_strategies/diff.rb@@ -57,23 +57,21 @@ module DiscourseAicontent = source.public_send(section == :javascript ? :js : section)blocks.each do |block|- begin- if !block[:search]- content = block[:replace]- else- content =- DiscourseAi::Utils::DiffUtils::SimpleDiff.apply(- content,- block[:search],- block[:replace],- )- end- rescue DiscourseAi::Utils::DiffUtils::SimpleDiff::NoMatchError- @failed_searches << { section: section, search: block[:search] }- # TODO, we may need to inform caller here, LLM made a mistake which it- # should correct- Rails.logger.warn("Failed to find search: #{block[:search]}")+ if !block[:search]+ content = block[:replace]+ else+ content =+ DiscourseAi::Utils::DiffUtils::SimpleDiff.apply(+ content,+ block[:search],+ block[:replace],+ )end+ rescue DiscourseAi::Utils::DiffUtils::SimpleDiff::NoMatchError+ @failed_searches << { section: section, search: block[:search] }+ # TODO, we may need to inform caller here, LLM made a mistake which it+ # should correct+ Rails.logger.warn("Failed to find search: #{block[:search]}")endupdated_content[section == :javascript ? :js : section] = contentenddiff --git a/plugins/discourse-ai/lib/agents/tool_runner.rb b/plugins/discourse-ai/lib/agents/tool_runner.rbindex 6624588e3ad..383bca0f005 100644--- a/plugins/discourse-ai/lib/agents/tool_runner.rb+++ b/plugins/discourse-ai/lib/agents/tool_runner.rb@@ -364,20 +364,18 @@ module DiscourseAit =Thread.new do- begin- while !done- # this is not accurate. but reasonable enough for a timeout- sleep(0.001)- elapsed += 1 if !self.running_attached_function- if elapsed > timeout- mutex.synchronize { mini_racer_context.stop unless done }- break- end+ while !done+ # this is not accurate. but reasonable enough for a timeout+ sleep(0.001)+ elapsed += 1 if !self.running_attached_function+ if elapsed > timeout+ mutex.synchronize { mini_racer_context.stop unless done }+ breakend- rescue => e- STDERR.puts e- STDERR.puts "FAILED TO TERMINATE DUE TO TIMEOUT"end+ rescue => e+ STDERR.puts e+ STDERR.puts "FAILED TO TERMINATE DUE TO TIMEOUT"endrval = mini_racer_context.eval(script)diff --git a/plugins/discourse-ai/lib/agents/tool_runner/llm.rb b/plugins/discourse-ai/lib/agents/tool_runner/llm.rbindex 749cd44cf48..e9a986bd70e 100644--- a/plugins/discourse-ai/lib/agents/tool_runner/llm.rb+++ b/plugins/discourse-ai/lib/agents/tool_runner/llm.rb@@ -58,10 +58,7 @@ module DiscourseAienddef llm_user- @llm_user ||=- begin- post&.user || @bot_user- end+ @llm_user ||= post&.user || @bot_userenddef postdiff --git a/plugins/discourse-ai/lib/agents/tools/create_image.rb b/plugins/discourse-ai/lib/agents/tools/create_image.rbindex 40c038b1cee..a901a91298c 100644--- a/plugins/discourse-ai/lib/agents/tools/create_image.rb+++ b/plugins/discourse-ai/lib/agents/tools/create_image.rb@@ -60,48 +60,46 @@ module DiscourseAierrors = []max_prompts.each do |prompt|- begin- # Create tool instance with parameters- tool_params = { prompt: prompt }-- tool_instance =- tool_class.new(tool_params, bot_user: bot_user, llm: llm, context: context)-- # Invoke the tool- tool_instance.invoke { |_progress| }-- # Extract the custom_raw which contains the generated image markdown- if tool_instance.custom_raw.present?- # Parse the upload short_url from the markdown- upload_match = tool_instance.custom_raw.match(%r{!\[.*?\]\((upload://[^)]+)\)})- if upload_match- short_url = upload_match[1]- sha1 = Upload.sha1_from_short_url(short_url)- upload = Upload.find_by(sha1: sha1) if sha1- uploads << { prompt: prompt, upload: upload, url: short_url } if upload- else- # Tool returned custom_raw but not in expected format- Rails.logger.error(- "CreateImage: Tool #{tool_class.name} returned custom_raw in unexpected format. " \- "Expected markdown with upload:// URL. " \- "custom_raw preview: #{tool_instance.custom_raw.truncate(200)}",- )- errors << "Tool returned invalid image format"- end+ # Create tool instance with parameters+ tool_params = { prompt: prompt }++ tool_instance =+ tool_class.new(tool_params, bot_user: bot_user, llm: llm, context: context)++ # Invoke the tool+ tool_instance.invoke { |_progress| }++ # Extract the custom_raw which contains the generated image markdown+ if tool_instance.custom_raw.present?+ # Parse the upload short_url from the markdown+ upload_match = tool_instance.custom_raw.match(%r{!\[.*?\]\((upload://[^)]+)\)})+ if upload_match+ short_url = upload_match[1]+ sha1 = Upload.sha1_from_short_url(short_url)+ upload = Upload.find_by(sha1: sha1) if sha1+ uploads << { prompt: prompt, upload: upload, url: short_url } if uploadelse- # Tool returned no output- Rails.logger.warn(- "CreateImage: Tool #{tool_class.name} returned no custom_raw output for prompt: #{prompt.truncate(50)}",+ # Tool returned custom_raw but not in expected format+ Rails.logger.error(+ "CreateImage: Tool #{tool_class.name} returned custom_raw in unexpected format. " \+ "Expected markdown with upload:// URL. " \+ "custom_raw preview: #{tool_instance.custom_raw.truncate(200)}",)- errors << "Tool returned no output"+ errors << "Tool returned invalid image format"end- rescue => e- Rails.logger.error(- "CreateImage: Failed to generate image for prompt '#{prompt.truncate(50)}'. " \- "Tool: #{tool_class.name}, Error: #{e.class.name} - #{e.message}",+ else+ # Tool returned no output+ Rails.logger.warn(+ "CreateImage: Tool #{tool_class.name} returned no custom_raw output for prompt: #{prompt.truncate(50)}",)- errors << e.message+ errors << "Tool returned no output"end+ rescue => e+ Rails.logger.error(+ "CreateImage: Failed to generate image for prompt '#{prompt.truncate(50)}'. " \+ "Tool: #{tool_class.name}, Error: #{e.class.name} - #{e.message}",+ )+ errors << e.messageendif uploads.empty?diff --git a/plugins/discourse-ai/lib/agents/tools/image.rb b/plugins/discourse-ai/lib/agents/tools/image.rbindex 40743173c3e..a95d53aa6e6 100644--- a/plugins/discourse-ai/lib/agents/tools/image.rb+++ b/plugins/discourse-ai/lib/agents/tools/image.rb@@ -92,38 +92,36 @@ module DiscourseAierrors = []selected_prompts.each_with_index do |prompt, index|- begin- # Create tool instance with parameters- tool_params = { prompt: prompt }- tool_params[:size] = size if size-- tool_instance =- tool_class.new(tool_params, bot_user: bot_user, llm: llm, context: context)-- # Invoke the tool- tool_instance.invoke { |_progress| }-- # Extract the custom_raw which contains the generated image markdown- if tool_instance.custom_raw.present?- # Parse the upload short_url from the markdown- upload_match = tool_instance.custom_raw.match(%r{!\[.*?\]\((upload://[^)]+)\)})- if upload_match- short_url = upload_match[1]- sha1 = Upload.sha1_from_short_url(short_url)- upload = Upload.find_by(sha1: sha1) if sha1- if upload- uploads << {- prompt: prompt,- upload: upload,- seed: nil, # Custom tools don't provide seeds- }- end+ # Create tool instance with parameters+ tool_params = { prompt: prompt }+ tool_params[:size] = size if size++ tool_instance =+ tool_class.new(tool_params, bot_user: bot_user, llm: llm, context: context)++ # Invoke the tool+ tool_instance.invoke { |_progress| }++ # Extract the custom_raw which contains the generated image markdown+ if tool_instance.custom_raw.present?+ # Parse the upload short_url from the markdown+ upload_match = tool_instance.custom_raw.match(%r{!\[.*?\]\((upload://[^)]+)\)})+ if upload_match+ short_url = upload_match[1]+ sha1 = Upload.sha1_from_short_url(short_url)+ upload = Upload.find_by(sha1: sha1) if sha1+ if upload+ uploads << {+ prompt: prompt,+ upload: upload,+ seed: nil, # Custom tools don't provide seeds+ }endend- rescue => e- Rails.logger.warn("Failed to generate image for prompt #{prompt}: #{e}")- errors << e.messageend+ rescue => e+ Rails.logger.warn("Failed to generate image for prompt #{prompt}: #{e}")+ errors << e.messageendif uploads.empty?diff --git a/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb b/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rbindex 0a0b7242621..4cb0e14937f 100644--- a/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb+++ b/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb@@ -19,11 +19,9 @@ module DiscourseAidef schedule_block(&block)thread_pool.post do- begin- block.call- rescue StandardError => e- Discourse.warn_exception(e, message: "Discourse AI: Unable to stream reply")- end+ block.call+ rescue StandardError => e+ Discourse.warn_exception(e, message: "Discourse AI: Unable to stream reply")endend@@ -42,39 +40,37 @@ module DiscourseAitool_results: nil)schedule_block do- begin- if custom_tools.present? || resume_token.present?- stream_custom_tool_reply(- io: io,- agent: agent,- user: user,- topic: topic,- query: query,- custom_instructions: custom_instructions,- current_user: current_user,- custom_tools: custom_tools,- resume_token: resume_token,- tool_results: tool_results,- )- else- stream_standard_reply(- io: io,- agent: agent,- user: user,- topic: topic,- query: query,- custom_instructions: custom_instructions,- current_user: current_user,- )- end- rescue StandardError => e- # make it a tiny bit easier to debug in dev, this is tricky- # multi-threaded code that exhibits various limitations in rails- p e if Rails.env.local?- Discourse.warn_exception(e, message: "Discourse AI: Unable to stream reply")- ensure- io.close+ if custom_tools.present? || resume_token.present?+ stream_custom_tool_reply(+ io: io,+ agent: agent,+ user: user,+ topic: topic,+ query: query,+ custom_instructions: custom_instructions,+ current_user: current_user,+ custom_tools: custom_tools,+ resume_token: resume_token,+ tool_results: tool_results,+ )+ else+ stream_standard_reply(+ io: io,+ agent: agent,+ user: user,+ topic: topic,+ query: query,+ custom_instructions: custom_instructions,+ current_user: current_user,+ )end+ rescue StandardError => e+ # make it a tiny bit easier to debug in dev, this is tricky+ # multi-threaded code that exhibits various limitations in rails+ p e if Rails.env.local?+ Discourse.warn_exception(e, message: "Discourse AI: Unable to stream reply")+ ensure+ io.closeendenddiff --git a/plugins/discourse-ai/lib/completions/cancel_manager.rb b/plugins/discourse-ai/lib/completions/cancel_manager.rbindex 78c3ee5bb65..82ce562b21c 100644--- a/plugins/discourse-ai/lib/completions/cancel_manager.rb+++ b/plugins/discourse-ai/lib/completions/cancel_manager.rb@@ -28,28 +28,26 @@ module DiscourseAi@monitor_thread =Thread.new do- begin- loop do- done = false- @mutex.synchronize { done = true if @stop_monitor }- break if done- sleep delay- @mutex.synchronize { done = true if @stop_monitor }- @mutex.synchronize { done = true if cancelled? }- break if done-- should_cancel = false- RailsMultisite::ConnectionManagement.with_connection(db) do- should_cancel = block.call- end-- @mutex.synchronize { cancel! if should_cancel }-- break if cancelled?+ loop do+ done = false+ @mutex.synchronize { done = true if @stop_monitor }+ break if done+ sleep delay+ @mutex.synchronize { done = true if @stop_monitor }+ @mutex.synchronize { done = true if cancelled? }+ break if done++ should_cancel = false+ RailsMultisite::ConnectionManagement.with_connection(db) do+ should_cancel = block.callend- ensure- @mutex.synchronize { @monitor_thread = nil }++ @mutex.synchronize { cancel! if should_cancel }++ break if cancelled?end+ ensure+ @mutex.synchronize { @monitor_thread = nil }endendend@@ -97,11 +95,9 @@ module DiscourseAiendend@callbacks.each do |cb|- begin- cb.call- rescue StandardError- # ignore cause this may have already been cancelled- end+ cb.call+ rescue StandardError+ # ignore cause this may have already been cancelledendendenddiff --git a/plugins/discourse-ai/lib/completions/endpoints/base.rb b/plugins/discourse-ai/lib/completions/endpoints/base.rbindex d6ef59f6147..99f74b8aa46 100644--- a/plugins/discourse-ai/lib/completions/endpoints/base.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/base.rb@@ -245,25 +245,24 @@ module DiscourseAireturn response_dataend- begin- response.read_body do |chunk|- break if cancelled+ response.read_body do |chunk|+ break if cancelled- response_raw << chunk+ response_raw << chunk- decode_chunk(chunk).each do |partial|- break if cancelled- partials_raw << partial.to_s- response_data << partial if partial.is_a?(String)- partials = [partial]- if xml_tool_processor && partial.is_a?(String)- partials = (xml_tool_processor << partial)- break if xml_tool_processor.should_cancel?- end- partials.each { |inner_partial| blk.call(inner_partial) }+ decode_chunk(chunk).each do |partial|+ break if cancelled+ partials_raw << partial.to_s+ response_data << partial if partial.is_a?(String)+ partials = [partial]+ if xml_tool_processor && partial.is_a?(String)+ partials = (xml_tool_processor << partial)+ break if xml_tool_processor.should_cancel?end+ partials.each { |inner_partial| blk.call(inner_partial) }endend+if xml_stripperstripped = xml_stripper.finishif stripped.present?@@ -447,11 +446,9 @@ module DiscourseAiprivatedef format_possible_json_payload(payload)- begin- JSON.pretty_generate(JSON.parse(payload))- rescue JSON::ParserError- payload- end+ JSON.pretty_generate(JSON.parse(payload))+ rescue JSON::ParserError+ payloadenddef track_failures(call_status)diff --git a/plugins/discourse-ai/lib/utils/dns_srv.rb b/plugins/discourse-ai/lib/utils/dns_srv.rbindex ae9eafb249e..3c8e1753e03 100644--- a/plugins/discourse-ai/lib/utils/dns_srv.rb+++ b/plugins/discourse-ai/lib/utils/dns_srv.rb@@ -39,13 +39,11 @@ module DiscourseAienddef self.server_available?(server)- begin- conn = Faraday.new { |f| f.adapter FinalDestination::FaradayAdapter }- response = conn.get("https://#{server.target}:#{server.port}/health")- response.success?- rescue StandardError- false- end+ conn = Faraday.new { |f| f.adapter FinalDestination::FaradayAdapter }+ response = conn.get("https://#{server.target}:#{server.port}/health")+ response.success?+ rescue StandardError+ falseenddef self.server_election(resources)diff --git a/plugins/discourse-ai/lib/utils/pdf_to_images.rb b/plugins/discourse-ai/lib/utils/pdf_to_images.rbindex 18c02073e58..07e8d522868 100644--- a/plugins/discourse-ai/lib/utils/pdf_to_images.rb+++ b/plugins/discourse-ai/lib/utils/pdf_to_images.rb@@ -19,61 +19,59 @@ class DiscourseAi::Utils::PdfToImagesenddef extract_pages- begin- pdf_path =- if upload.local?- Discourse.store.path_for(upload)- else- Discourse.store.download(upload, max_file_size_kb: MAX_PDF_SIZE)- end+ pdf_path =+ if upload.local?+ Discourse.store.path_for(upload)+ else+ Discourse.store.download(upload, max_file_size_kb: MAX_PDF_SIZE)+ end- raise Discourse::InvalidParameters.new("Failed to download PDF") if pdf_path.nil?+ raise Discourse::InvalidParameters.new("Failed to download PDF") if pdf_path.nil?- temp_dir = Dir.mktmpdir("discourse-pdf-#{SecureRandom.hex(8)}")- temp_pdf = File.join(temp_dir, "source.pdf")- FileUtils.cp(pdf_path, temp_pdf)+ temp_dir = Dir.mktmpdir("discourse-pdf-#{SecureRandom.hex(8)}")+ temp_pdf = File.join(temp_dir, "source.pdf")+ FileUtils.cp(pdf_path, temp_pdf)- # Convert PDF to individual page images- output_pattern = File.join(temp_dir, "page-%04d.png")+ # Convert PDF to individual page images+ output_pattern = File.join(temp_dir, "page-%04d.png")- command = [- "magick",- "-density",- "300",- temp_pdf,- "-background",- "white",- "-auto-orient",- "-quality",- "85",- output_pattern,- ]+ command = [+ "magick",+ "-density",+ "300",+ temp_pdf,+ "-background",+ "white",+ "-auto-orient",+ "-quality",+ "85",+ output_pattern,+ ]- Discourse::Utils.execute_command(- *command,- failure_message: "Failed to convert PDF to images",- timeout: MAX_CONVERT_SECONDS,- )+ Discourse::Utils.execute_command(+ *command,+ failure_message: "Failed to convert PDF to images",+ timeout: MAX_CONVERT_SECONDS,+ )- uploads = []- Dir- .glob(File.join(temp_dir, "page-*.png"))- .sort- .each do |page_path|- upload =- UploadCreator.new(File.open(page_path), "page-#{File.basename(page_path)}").create_for(- @user.id,- )+ uploads = []+ Dir+ .glob(File.join(temp_dir, "page-*.png"))+ .sort+ .each do |page_path|+ upload =+ UploadCreator.new(File.open(page_path), "page-#{File.basename(page_path)}").create_for(+ @user.id,+ )- uploads << upload- end+ uploads << upload+ end- # Create upload references- UploadReference.ensure_exist!(upload_ids: uploads.map(&:id), target: @upload)+ # Create upload references+ UploadReference.ensure_exist!(upload_ids: uploads.map(&:id), target: @upload)- @uploaded_pages = uploads- ensure- FileUtils.rm_rf(temp_dir) if temp_dir- end+ @uploaded_pages = uploads+ ensure+ FileUtils.rm_rf(temp_dir) if temp_direndenddiff --git a/plugins/discourse-ai/spec/lib/completions/cancel_manager_spec.rb b/plugins/discourse-ai/spec/lib/completions/cancel_manager_spec.rbindex 43f3dd5b588..5d1d8661ced 100644--- a/plugins/discourse-ai/spec/lib/completions/cancel_manager_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/cancel_manager_spec.rb@@ -60,14 +60,12 @@ describe DiscourseAi::Completions::CancelManager dothread =Thread.new doloop do- begin- _client = server.accept- sleep(30) # Hold the connection longer than the test will run- break- rescue StandardError- # Server closed- break- end+ _client = server.accept+ sleep(30) # Hold the connection longer than the test will run+ break+ rescue StandardError+ # Server closed+ breakendenddiff --git a/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rbindex 5d2060053c5..39bee5a6572 100644--- a/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb+++ b/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb@@ -257,14 +257,12 @@ RSpec.describe "AI Bot - Homepage" doendit "removes agent from selector when allow_personal_messages is disabled" do- begin- agent.update!(allow_personal_messages: false)- ai_pm_homepage.visit- ai_pm_homepage.agent_selector.expand- expect(ai_pm_homepage.agent_selector).to have_no_option_name(agent.name)- ensure- agent.update!(allow_personal_messages: true)- end+ agent.update!(allow_personal_messages: false)+ ai_pm_homepage.visit+ ai_pm_homepage.agent_selector.expand+ expect(ai_pm_homepage.agent_selector).to have_no_option_name(agent.name)+ ensure+ agent.update!(allow_personal_messages: true)endit "includes agent in selector when allow_personal_messages is enabled" dodiff --git a/plugins/discourse-cakeday/app/jobs/onceoff/fix_invalid_date_of_birth.rb b/plugins/discourse-cakeday/app/jobs/onceoff/fix_invalid_date_of_birth.rbindex ecdb9e41a3d..729a0d4a0b0 100644--- a/plugins/discourse-cakeday/app/jobs/onceoff/fix_invalid_date_of_birth.rb+++ b/plugins/discourse-cakeday/app/jobs/onceoff/fix_invalid_date_of_birth.rb@@ -7,11 +7,9 @@ module Jobs.where(name: "date_of_birth").where("value != ''").find_each do |custom_field|- begin- Date.parse(custom_field.value)- rescue ArgumentError- custom_field.update!(value: "")- end+ Date.parse(custom_field.value)+ rescue ArgumentError+ custom_field.update!(value: "")endendenddiff --git a/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb b/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rbindex 95508763395..0e9e273d5ac 100644--- a/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb+++ b/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb@@ -127,35 +127,33 @@ module DiscoursePostEventraise Discourse::InvalidParameters.new(:file) if file.blank?hijack do- begin- invitees = []-- CSV.foreach(file.tempfile) do |row|- invitees << { identifier: row[0], attendance: row[1] || "going" } if row[0].present?- end-- if invitees.present?- Jobs.enqueue(- :discourse_post_event_bulk_invite,- event_id: event.id,- invitees: invitees,- current_user_id: current_user.id,- )- render json: success_json- else- render json:- failed_json.merge(- errors: [I18n.t("discourse_post_event.errors.bulk_invite.error")],- ),- status: :unprocessable_entity- end- rescue StandardError+ invitees = []++ CSV.foreach(file.tempfile) do |row|+ invitees << { identifier: row[0], attendance: row[1] || "going" } if row[0].present?+ end++ if invitees.present?+ Jobs.enqueue(+ :discourse_post_event_bulk_invite,+ event_id: event.id,+ invitees: invitees,+ current_user_id: current_user.id,+ )+ render json: success_json+ elserender json:failed_json.merge(errors: [I18n.t("discourse_post_event.errors.bulk_invite.error")],),status: :unprocessable_entityend+ rescue StandardError+ render json:+ failed_json.merge(+ errors: [I18n.t("discourse_post_event.errors.bulk_invite.error")],+ ),+ status: :unprocessable_entityendenddiff --git a/plugins/discourse-calendar/spec/jobs/export_post_event_report_csv_spec.rb b/plugins/discourse-calendar/spec/jobs/export_post_event_report_csv_spec.rbindex 20f3f51a917..b716d723da9 100644--- a/plugins/discourse-calendar/spec/jobs/export_post_event_report_csv_spec.rb+++ b/plugins/discourse-calendar/spec/jobs/export_post_event_report_csv_spec.rb@@ -26,70 +26,66 @@ describe Jobs::ExportCsvFile docontext "when the user requesting the upload is admin" doit "generates the upload and notify the user" do- begin- expect do- Jobs::ExportCsvFile.new.execute(- user_id: user.id,- entity: "post_event",- args: {- id: post_event.id,- },- )- end.to change { Upload.count }.by(1)-- system_message = user.topics_allowed.last-- expect(system_message.title).to eq(- I18n.t(- "system_messages.csv_export_succeeded.subject_template",- export_title: "Post Event",- ),- )-- upload = Upload.last-- expect(system_message.first_post.raw).to include(- I18n.t(- "system_messages.csv_export_succeeded.text_body_template",- download_link:- "[#{upload.original_filename}|attachment](#{upload.short_url}) (#{upload.filesize} Bytes)",- ).chomp,+ expect do+ Jobs::ExportCsvFile.new.execute(+ user_id: user.id,+ entity: "post_event",+ args: {+ id: post_event.id,+ },)-- expect(system_message.id).to eq(UserExport.last.topic_id)- expect(system_message.closed).to eq(true)-- files = []- Zip::File.open(Discourse.store.path_for(upload)) do |zip_file|- zip_file.each do |entry|- files << entry.name-- input_stream = entry.get_input_stream- parsed_csv = CSV.parse(input_stream.read)-- expect(parsed_csv[0]).to eq(- %w[username status first_answered_at last_updated_at],- )- invitee_1 = post_event.invitees.find_by(user_id: user_1.id)- expect(parsed_csv[1]).to eq(- [user_1.username, nil, invitee_1.created_at.to_s, invitee_1.updated_at.to_s],- )- invitee_2 = post_event.invitees.find_by(user_id: user_2.id)- expect(parsed_csv[2]).to eq(- [- user_2.username,- "not_going",- invitee_2.created_at.to_s,- invitee_2.updated_at.to_s,- ],- )- end+ end.to change { Upload.count }.by(1)++ system_message = user.topics_allowed.last++ expect(system_message.title).to eq(+ I18n.t(+ "system_messages.csv_export_succeeded.subject_template",+ export_title: "Post Event",+ ),+ )++ upload = Upload.last++ expect(system_message.first_post.raw).to include(+ I18n.t(+ "system_messages.csv_export_succeeded.text_body_template",+ download_link:+ "[#{upload.original_filename}|attachment](#{upload.short_url}) (#{upload.filesize} Bytes)",+ ).chomp,+ )++ expect(system_message.id).to eq(UserExport.last.topic_id)+ expect(system_message.closed).to eq(true)++ files = []+ Zip::File.open(Discourse.store.path_for(upload)) do |zip_file|+ zip_file.each do |entry|+ files << entry.name++ input_stream = entry.get_input_stream+ parsed_csv = CSV.parse(input_stream.read)++ expect(parsed_csv[0]).to eq(%w[username status first_answered_at last_updated_at])+ invitee_1 = post_event.invitees.find_by(user_id: user_1.id)+ expect(parsed_csv[1]).to eq(+ [user_1.username, nil, invitee_1.created_at.to_s, invitee_1.updated_at.to_s],+ )+ invitee_2 = post_event.invitees.find_by(user_id: user_2.id)+ expect(parsed_csv[2]).to eq(+ [+ user_2.username,+ "not_going",+ invitee_2.created_at.to_s,+ invitee_2.updated_at.to_s,+ ],+ )end-- expect(files.size).to eq(1)- ensure- user.uploads.each(&:destroy!)end++ expect(files.size).to eq(1)+ ensure+ user.uploads.each(&:destroy!)endendend@@ -135,19 +131,17 @@ describe Jobs::ExportCsvFile dobefore { SiteSetting.discourse_post_event_allowed_on_groups = group_1.id }it "generates the upload" do- begin- expect do- Jobs::ExportCsvFile.new.execute(- user_id: user.id,- entity: "post_event",- args: {- id: post_event.id,- },- )- end.to change { Upload.count }.by(1)- ensure- user.uploads.each(&:destroy!)- end+ expect do+ Jobs::ExportCsvFile.new.execute(+ user_id: user.id,+ entity: "post_event",+ args: {+ id: post_event.id,+ },+ )+ end.to change { Upload.count }.by(1)+ ensure+ user.uploads.each(&:destroy!)endendenddiff --git a/plugins/discourse-chat-integration/app/controllers/discourse_chat_integration/chat_controller.rb b/plugins/discourse-chat-integration/app/controllers/discourse_chat_integration/chat_controller.rbindex 139651c39b6..9c3b5dd1ffa 100644--- a/plugins/discourse-chat-integration/app/controllers/discourse_chat_integration/chat_controller.rb+++ b/plugins/discourse-chat-integration/app/controllers/discourse_chat_integration/chat_controller.rb@@ -84,29 +84,27 @@ class DiscourseChatIntegration::ChatController < ApplicationControllerenddef test- begin- channel_id = params[:channel_id].to_i- topic_id = params[:topic_id].to_i+ channel_id = params[:channel_id].to_i+ topic_id = params[:topic_id].to_i- channel = DiscourseChatIntegration::Channel.find(channel_id)- provider = DiscourseChatIntegration::Provider.get_by_name(channel.provider)+ channel = DiscourseChatIntegration::Channel.find(channel_id)+ provider = DiscourseChatIntegration::Provider.get_by_name(channel.provider)- raise Discourse::NotFound if !DiscourseChatIntegration::Provider.is_enabled(provider)+ raise Discourse::NotFound if !DiscourseChatIntegration::Provider.is_enabled(provider)- post = Topic.find(topic_id.to_i).posts.first+ post = Topic.find(topic_id.to_i).posts.first- provider.trigger_notification(post, channel, nil)+ provider.trigger_notification(post, channel, nil)- render json: success_json- rescue Discourse::InvalidParameters, ActiveRecord::RecordNotFound => err+ render json: success_json+ rescue Discourse::InvalidParameters, ActiveRecord::RecordNotFound => err+ render json: { errors: [err.message] }, status: :unprocessable_entity+ rescue DiscourseChatIntegration::ProviderError => err+ Rails.logger.error("Test provider failed #{err.info}")+ if err.info.key?(:error_key) && !err.info[:error_key].nil?+ render json: { error_key: err.info[:error_key] }, status: :unprocessable_entity+ elserender json: { errors: [err.message] }, status: :unprocessable_entity- rescue DiscourseChatIntegration::ProviderError => err- Rails.logger.error("Test provider failed #{err.info}")- if err.info.key?(:error_key) && !err.info[:error_key].nil?- render json: { error_key: err.info[:error_key] }, status: :unprocessable_entity- else- render json: { errors: [err.message] }, status: :unprocessable_entity- endendend@@ -121,54 +119,50 @@ class DiscourseChatIntegration::ChatController < ApplicationControllerenddef create_channel- begin- providers = DiscourseChatIntegration::Provider.enabled_providers.map { |x| x::PROVIDER_NAME }+ providers = DiscourseChatIntegration::Provider.enabled_providers.map { |x| x::PROVIDER_NAME }- if !defined?(params[:channel]) && defined?(params[:channel][:provider])- raise Discourse::InvalidParameters, "Provider is not valid"- end+ if !defined?(params[:channel]) && defined?(params[:channel][:provider])+ raise Discourse::InvalidParameters, "Provider is not valid"+ end- requested_provider = params[:channel][:provider]+ requested_provider = params[:channel][:provider]- if !providers.include?(requested_provider)- raise Discourse::InvalidParameters, "Provider is not valid"- end+ if !providers.include?(requested_provider)+ raise Discourse::InvalidParameters, "Provider is not valid"+ end- allowed_keys =- DiscourseChatIntegration::Provider.get_by_name(- requested_provider,- )::CHANNEL_PARAMETERS.map { |p| p[:key].to_sym }+ allowed_keys =+ DiscourseChatIntegration::Provider.get_by_name(+ requested_provider,+ )::CHANNEL_PARAMETERS.map { |p| p[:key].to_sym }- hash = params.require(:channel).permit(:provider, data: allowed_keys)+ hash = params.require(:channel).permit(:provider, data: allowed_keys)- channel = DiscourseChatIntegration::Channel.new(hash)+ channel = DiscourseChatIntegration::Channel.new(hash)- raise Discourse::InvalidParameters, "Channel is not valid" if !channel.save+ raise Discourse::InvalidParameters, "Channel is not valid" if !channel.save- render_serialized channel, DiscourseChatIntegration::ChannelSerializer, root: "channel"- rescue Discourse::InvalidParameters => e- render json: { errors: [e.message] }, status: :unprocessable_entity- end+ render_serialized channel, DiscourseChatIntegration::ChannelSerializer, root: "channel"+ rescue Discourse::InvalidParameters => e+ render json: { errors: [e.message] }, status: :unprocessable_entityenddef update_channel- begin- channel = DiscourseChatIntegration::Channel.find(params[:id].to_i)- channel.error_key = nil # Reset any error on the rule+ channel = DiscourseChatIntegration::Channel.find(params[:id].to_i)+ channel.error_key = nil # Reset any error on the rule- allowed_keys =- DiscourseChatIntegration::Provider.get_by_name(- channel.provider,- )::CHANNEL_PARAMETERS.map { |p| p[:key].to_sym }+ allowed_keys =+ DiscourseChatIntegration::Provider.get_by_name(+ channel.provider,+ )::CHANNEL_PARAMETERS.map { |p| p[:key].to_sym }- hash = params.require(:channel).permit(data: allowed_keys)+ hash = params.require(:channel).permit(data: allowed_keys)- raise Discourse::InvalidParameters, "Channel is not valid" if !channel.update(hash)+ raise Discourse::InvalidParameters, "Channel is not valid" if !channel.update(hash)- render_serialized channel, DiscourseChatIntegration::ChannelSerializer, root: "channel"- rescue Discourse::InvalidParameters => e- render json: { errors: [e.message] }, status: :unprocessable_entity- end+ render_serialized channel, DiscourseChatIntegration::ChannelSerializer, root: "channel"+ rescue Discourse::InvalidParameters => e+ render json: { errors: [e.message] }, status: :unprocessable_entityenddef destroy_channel@@ -180,30 +174,26 @@ class DiscourseChatIntegration::ChatController < ApplicationControllerenddef create_rule- begin- hash =- params.require(:rule).permit(:channel_id, :type, :filter, :group_id, :category_id, tags: [])- rule = DiscourseChatIntegration::Rule.new(hash)+ hash =+ params.require(:rule).permit(:channel_id, :type, :filter, :group_id, :category_id, tags: [])+ rule = DiscourseChatIntegration::Rule.new(hash)- raise Discourse::InvalidParameters, "Rule is not valid" if !rule.save+ raise Discourse::InvalidParameters, "Rule is not valid" if !rule.save- render_serialized rule, DiscourseChatIntegration::RuleSerializer, root: "rule"- rescue Discourse::InvalidParameters => e- render json: { errors: [e.message] }, status: :unprocessable_entity- end+ render_serialized rule, DiscourseChatIntegration::RuleSerializer, root: "rule"+ rescue Discourse::InvalidParameters => e+ render json: { errors: [e.message] }, status: :unprocessable_entityenddef update_rule- begin- rule = DiscourseChatIntegration::Rule.find(params[:id].to_i)- hash = params.require(:rule).permit(:type, :filter, :group_id, :category_id, tags: [])+ rule = DiscourseChatIntegration::Rule.find(params[:id].to_i)+ hash = params.require(:rule).permit(:type, :filter, :group_id, :category_id, tags: [])- raise Discourse::InvalidParameters, "Rule is not valid" if !rule.update(hash)+ raise Discourse::InvalidParameters, "Rule is not valid" if !rule.update(hash)- render_serialized rule, DiscourseChatIntegration::RuleSerializer, root: "rule"- rescue Discourse::InvalidParameters => e- render json: { errors: [e.message] }, status: :unprocessable_entity- end+ render_serialized rule, DiscourseChatIntegration::RuleSerializer, root: "rule"+ rescue Discourse::InvalidParameters => e+ render json: { errors: [e.message] }, status: :unprocessable_entityenddef destroy_rulediff --git a/plugins/discourse-data-explorer/plugin.rb b/plugins/discourse-data-explorer/plugin.rbindex 6de9fbce64f..ca94e9fb228 100644--- a/plugins/discourse-data-explorer/plugin.rb+++ b/plugins/discourse-data-explorer/plugin.rb@@ -131,11 +131,9 @@ after_initialize do{ skip_empty:, users_from_group:, attach_csv:, render_url_columns: true },).each do |pm|- begin- utils.send_pm(pm, automation_id: automation.id)- rescue ActiveRecord::RecordNotSaved => e- Rails.logger.warn "#{DiscourseDataExplorer::PLUGIN_NAME} - couldn't send PM for automation #{automation.id}: #{e.message}"- end+ utils.send_pm(pm, automation_id: automation.id)+ rescue ActiveRecord::RecordNotSaved => e+ Rails.logger.warn "#{DiscourseDataExplorer::PLUGIN_NAME} - couldn't send PM for automation #{automation.id}: #{e.message}"endendenddiff --git a/plugins/discourse-patreon/app/controllers/patreon/patreon_admin_controller.rb b/plugins/discourse-patreon/app/controllers/patreon/patreon_admin_controller.rbindex 074e2b049c9..3a6d3d3a3ed 100644--- a/plugins/discourse-patreon/app/controllers/patreon/patreon_admin_controller.rb+++ b/plugins/discourse-patreon/app/controllers/patreon/patreon_admin_controller.rb@@ -29,11 +29,9 @@ class Patreon::PatreonAdminController < Admin::AdminControllerenddef is_number?(string)- begin- true if Float(string)- rescue StandardError- false- end+ true if Float(string)+ rescue StandardError+ falseenddef edit@@ -65,12 +63,10 @@ class Patreon::PatreonAdminController < Admin::AdminControllerenddef sync_groups- begin- Patreon::Patron.sync_groups- render json: success_json- rescue => e- render json: { message: e.message }, status: :internal_server_error- end+ Patreon::Patron.sync_groups+ render json: success_json+ rescue => e+ render json: { message: e.message }, status: :internal_server_errorenddef update_datadiff --git a/plugins/discourse-post-voting/extensions/topic_extension.rb b/plugins/discourse-post-voting/extensions/topic_extension.rbindex 9c0f97b91e4..fdb9b06bf50 100644--- a/plugins/discourse-post-voting/extensions/topic_extension.rb+++ b/plugins/discourse-post-voting/extensions/topic_extension.rb@@ -19,9 +19,7 @@ module PostVotingdef answers@answers ||=- begin- posts.where(reply_to_post_number: nil).where.not(post_number: 1).order(post_number: :asc)- end+ posts.where(reply_to_post_number: nil).where.not(post_number: 1).order(post_number: :asc)enddef answer_count@@ -36,12 +34,7 @@ module PostVotingdef comments@comments ||=- begin- PostVotingComment- .joins(:post)- .where("posts.topic_id = ?", self.id)- .order(created_at: :asc)- end+ PostVotingComment.joins(:post).where("posts.topic_id = ?", self.id).order(created_at: :asc)enddef last_commented_ondiff --git a/plugins/discourse-post-voting/plugin.rb b/plugins/discourse-post-voting/plugin.rbindex d56c56a8391..bd6eaf9951f 100644--- a/plugins/discourse-post-voting/plugin.rb+++ b/plugins/discourse-post-voting/plugin.rb@@ -78,20 +78,19 @@ after_initialize doadd_to_class(:topic_view, :user_voted_posts) do |user|@user_voted_posts ||= {}- @user_voted_posts[user.id] ||= begin- PostVotingVote.where(user: user, post: @posts).distinct.pluck(:post_id)- end+ @user_voted_posts[user.id] ||= PostVotingVote+ .where(user: user, post: @posts)+ .distinct+ .pluck(:post_id)endadd_to_class(:topic_view, :user_voted_posts_last_timestamp) do |user|@user_voted_posts_last_timestamp ||= {}- @user_voted_posts_last_timestamp[user.id] ||= begin- PostVotingVote- .where(user: user, post: @posts)- .group(:votable_id, :created_at)- .pluck(:votable_id, :created_at)- end+ @user_voted_posts_last_timestamp[user.id] ||= PostVotingVote+ .where(user: user, post: @posts)+ .group(:votable_id, :created_at)+ .pluck(:votable_id, :created_at)endTopicView.apply_custom_default_scope do |scope, topic_view|diff --git a/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rb b/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rbindex 6dd2923ff26..499b3b28413 100644--- a/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rb+++ b/plugins/discourse-reactions/lib/discourse_reactions/post_extension.rb@@ -10,9 +10,6 @@ module DiscourseReactions::PostExtensionenddef emoji_reactions- @emoji_reactions ||=- begin- self.reactions.select { |reaction| Emoji.exists?(reaction.reaction_value) }- end+ @emoji_reactions ||= self.reactions.select { |reaction| Emoji.exists?(reaction.reaction_value) }endenddiff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/coupons_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/coupons_controller.rbindex 10481cb2a07..7c6a7af1a11 100644--- a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/coupons_controller.rb+++ b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/coupons_controller.rb@@ -9,13 +9,11 @@ module DiscourseSubscriptionsrequires_plugin PLUGIN_NAMEdef index- begin- promo_codes = ::Stripe::PromotionCode.list({ limit: 100 }, stripe_request_opts)[:data]- promo_codes = promo_codes.select { |code| code[:coupon][:valid] == true }- render_json_dump promo_codes- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message- end+ promo_codes = ::Stripe::PromotionCode.list({ limit: 100 }, stripe_request_opts)[:data]+ promo_codes = promo_codes.select { |code| code[:coupon][:valid] == true }+ render_json_dump promo_codes+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef creatediff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/plans_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/plans_controller.rbindex b7a023b987a..1e503f3ca43 100644--- a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/plans_controller.rb+++ b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/plans_controller.rb@@ -8,85 +8,77 @@ module DiscourseSubscriptionsrequires_plugin PLUGIN_NAMEdef index- begin- plans = ::Stripe::Price.list(product_params, stripe_request_opts)+ plans = ::Stripe::Price.list(product_params, stripe_request_opts)- render_json_dump plans.data- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message- end+ render_json_dump plans.data+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef create- begin- price_object = {- nickname: params[:nickname],- unit_amount: params[:amount],- product: params[:product],- currency: params[:currency],- active: params[:active],- metadata: {- group_name: params[:metadata][:group_name],- trial_period_days: params[:trial_period_days],- },- }-- price_object[:recurring] = { interval: params[:interval] } if params[:type] == "recurring"-- plan = ::Stripe::Price.create(price_object, stripe_request_opts)-- render_json_dump plan- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message- end+ price_object = {+ nickname: params[:nickname],+ unit_amount: params[:amount],+ product: params[:product],+ currency: params[:currency],+ active: params[:active],+ metadata: {+ group_name: params[:metadata][:group_name],+ trial_period_days: params[:trial_period_days],+ },+ }++ price_object[:recurring] = { interval: params[:interval] } if params[:type] == "recurring"++ plan = ::Stripe::Price.create(price_object, stripe_request_opts)++ render_json_dump plan+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef show- begin- plan = ::Stripe::Price.retrieve(params[:id], stripe_request_opts)-- if plan[:metadata] && plan[:metadata][:trial_period_days]- trial_days = plan[:metadata][:trial_period_days]- elsif plan[:recurring] && plan[:recurring][:trial_period_days]- trial_days = plan[:recurring][:trial_period_days]- end-- interval = nil- interval = plan[:recurring][:interval] if plan[:recurring] && plan[:recurring][:interval]-- serialized =- plan.to_h.merge(- trial_period_days: trial_days,- currency: plan[:currency].upcase,- interval: interval,- )-- render_json_dump serialized- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message+ plan = ::Stripe::Price.retrieve(params[:id], stripe_request_opts)++ if plan[:metadata] && plan[:metadata][:trial_period_days]+ trial_days = plan[:metadata][:trial_period_days]+ elsif plan[:recurring] && plan[:recurring][:trial_period_days]+ trial_days = plan[:recurring][:trial_period_days]end++ interval = nil+ interval = plan[:recurring][:interval] if plan[:recurring] && plan[:recurring][:interval]++ serialized =+ plan.to_h.merge(+ trial_period_days: trial_days,+ currency: plan[:currency].upcase,+ interval: interval,+ )++ render_json_dump serialized+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef update- begin- plan =- ::Stripe::Price.update(- params[:id],- {- nickname: params[:nickname],- active: params[:active],- metadata: {- group_name: params[:metadata][:group_name],- trial_period_days: params[:trial_period_days],- },+ plan =+ ::Stripe::Price.update(+ params[:id],+ {+ nickname: params[:nickname],+ active: params[:active],+ metadata: {+ group_name: params[:metadata][:group_name],+ trial_period_days: params[:trial_period_days],},- stripe_request_opts,- )+ },+ stripe_request_opts,+ )- render_json_dump plan- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message- end+ render_json_dump plan+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageendprivatediff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/products_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/products_controller.rbindex c6c37b78859..368b8743f5f 100644--- a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/products_controller.rb+++ b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/products_controller.rb@@ -8,69 +8,59 @@ module DiscourseSubscriptionsrequires_plugin PLUGIN_NAMEdef index- begin- product_ids = Product.all.pluck(:external_id)- products = []-- if product_ids.present? && is_stripe_configured?- products = ::Stripe::Product.list({ ids: product_ids, limit: 100 }, stripe_request_opts)- products = products[:data]- elsif !is_stripe_configured?- products = nil- end-- render_json_dump products- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message+ product_ids = Product.all.pluck(:external_id)+ products = []++ if product_ids.present? && is_stripe_configured?+ products = ::Stripe::Product.list({ ids: product_ids, limit: 100 }, stripe_request_opts)+ products = products[:data]+ elsif !is_stripe_configured?+ products = nilend++ render_json_dump products+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef create- begin- create_params = product_params.merge!(type: "service")+ create_params = product_params.merge!(type: "service")- create_params.except!(:statement_descriptor) if params[:statement_descriptor].blank?+ create_params.except!(:statement_descriptor) if params[:statement_descriptor].blank?- product = ::Stripe::Product.create(create_params, stripe_request_opts)+ product = ::Stripe::Product.create(create_params, stripe_request_opts)- Product.create(external_id: product[:id])+ Product.create(external_id: product[:id])- render_json_dump product- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message- end+ render_json_dump product+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef show- begin- product = ::Stripe::Product.retrieve(params[:id], stripe_request_opts)+ product = ::Stripe::Product.retrieve(params[:id], stripe_request_opts)- render_json_dump product- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message- end+ render_json_dump product+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef update- begin- product = ::Stripe::Product.update(params[:id], product_params, stripe_request_opts)+ product = ::Stripe::Product.update(params[:id], product_params, stripe_request_opts)- render_json_dump product- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message- end+ render_json_dump product+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef destroy- begin- product = ::Stripe::Product.delete(params[:id], {}, stripe_request_opts)+ product = ::Stripe::Product.delete(params[:id], {}, stripe_request_opts)- Product.delete_by(external_id: params[:id])+ Product.delete_by(external_id: params[:id])- render_json_dump product- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message- end+ render_json_dump product+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageendprivatediff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/subscriptions_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/subscriptions_controller.rbindex 3e16a81b516..6e2b47cf2f7 100644--- a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/subscriptions_controller.rb+++ b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/subscriptions_controller.rb@@ -11,41 +11,34 @@ module DiscourseSubscriptionsPAGE_LIMIT = 10def index- begin- subscription_ids = Subscription.all.pluck(:external_id)- subscriptions = {- has_more: false,- data: [],- length: 0,- last_record: params[:last_record],- }-- if subscription_ids.present? && is_stripe_configured?- while subscriptions[:length] < PAGE_LIMIT- current_set = get_subscriptions(subscriptions[:last_record])-- until valid_subscriptions =- find_valid_subscriptions(current_set[:data], subscription_ids)- current_set = get_subscriptions(current_set[:data].last)- break if current_set[:has_more] == false- end-- subscriptions[:data] = subscriptions[:data].concat(valid_subscriptions.to_a)- subscriptions[:last_record] = current_set[:data].last[:id] if current_set[- :data- ].present?- subscriptions[:length] = subscriptions[:data].length- subscriptions[:has_more] = current_set[:has_more]- break if subscriptions[:has_more] == false+ subscription_ids = Subscription.all.pluck(:external_id)+ subscriptions = { has_more: false, data: [], length: 0, last_record: params[:last_record] }++ if subscription_ids.present? && is_stripe_configured?+ while subscriptions[:length] < PAGE_LIMIT+ current_set = get_subscriptions(subscriptions[:last_record])++ until valid_subscriptions =+ find_valid_subscriptions(current_set[:data], subscription_ids)+ current_set = get_subscriptions(current_set[:data].last)+ break if current_set[:has_more] == falseend- elsif !is_stripe_configured?- subscriptions = nil- end- render_json_dump subscriptions- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message+ subscriptions[:data] = subscriptions[:data].concat(valid_subscriptions.to_a)+ subscriptions[:last_record] = current_set[:data].last[:id] if current_set[+ :data+ ].present?+ subscriptions[:length] = subscriptions[:data].length+ subscriptions[:has_more] = current_set[:has_more]+ break if subscriptions[:has_more] == false+ end+ elsif !is_stripe_configured?+ subscriptions = nilend++ render_json_dump subscriptions+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef destroydiff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin_controller.rbindex 38b02f60e2f..0c5ce5afa4c 100644--- a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin_controller.rb+++ b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin_controller.rb@@ -14,12 +14,10 @@ module DiscourseSubscriptionsenddef create_campaign- begin- DiscourseSubscriptions::Campaign.new.create_campaign- render json: success_json- rescue => e- render_json_error e.message- end+ DiscourseSubscriptions::Campaign.new.create_campaign+ render json: success_json+ rescue => e+ render_json_error e.messageendendenddiff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/subscribe_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/subscribe_controller.rbindex 4799a361161..c6a883527ef 100644--- a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/subscribe_controller.rb+++ b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/subscribe_controller.rb@@ -10,20 +10,18 @@ module DiscourseSubscriptionsrequires_login except: %i[index contributors show]def index- begin- product_ids = Product.all.pluck(:external_id)- products = []-- if product_ids.present? && is_stripe_configured?- response = ::Stripe::Product.list({ ids: product_ids, active: true }, stripe_request_opts)+ product_ids = Product.all.pluck(:external_id)+ products = []- products = response[:data].map { |p| serialize_product(p) }- end+ if product_ids.present? && is_stripe_configured?+ response = ::Stripe::Product.list({ ids: product_ids, active: true }, stripe_request_opts)- render_json_dump products- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message+ products = response[:data].map { |p| serialize_product(p) }end++ render_json_dump products+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef contributors@@ -264,16 +262,14 @@ module DiscourseSubscriptionsenddef retrieve_transaction(transaction)- begin- case transaction- when /^sub_/- ::Stripe::Subscription.retrieve(transaction, stripe_request_opts)- when /^in_/- ::Stripe::Invoice.retrieve(transaction, stripe_request_opts)- end- rescue ::Stripe::InvalidRequestError => e- e.message+ case transaction+ when /^sub_/+ ::Stripe::Subscription.retrieve(transaction, stripe_request_opts)+ when /^in_/+ ::Stripe::Invoice.retrieve(transaction, stripe_request_opts)end+ rescue ::Stripe::InvalidRequestError => e+ e.messageenddef metadata_userdiff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/payments_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/payments_controller.rbindex 6cbfa726031..3800098acf3 100644--- a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/payments_controller.rb+++ b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/payments_controller.rb@@ -10,54 +10,50 @@ module DiscourseSubscriptionsrequires_logindef index- begin- customer = Customer.where(user_id: current_user.id)- customer_ids = customer.map { |c| c.customer_id } if customer- product_ids = Product.all.pluck(:external_id)-- data = []-- if customer_ids.present? && product_ids.present?- customer_ids.each do |customer_id|- # lots of matching because the Stripe API doesn't make it easy to match products => payments except from invoices- all_invoices = ::Stripe::Invoice.list({ customer: customer_id }, stripe_request_opts)- invoices_with_products = parse_invoices(all_invoices, product_ids)- invoice_ids = invoices_with_products.map { |invoice| invoice[:id] }- payments =- ::Stripe::PaymentIntent.list({ customer: customer_id }, stripe_request_opts)- payments_from_invoices =- payments[:data].select { |payment| invoice_ids.include?(payment[:invoice]) }-- if SiteSetting.discourse_subscriptions_enable_verbose_logging- Rails.logger.warn("Payments from invoices: #{payments_from_invoices}")- end+ customer = Customer.where(user_id: current_user.id)+ customer_ids = customer.map { |c| c.customer_id } if customer+ product_ids = Product.all.pluck(:external_id)++ data = []++ if customer_ids.present? && product_ids.present?+ customer_ids.each do |customer_id|+ # lots of matching because the Stripe API doesn't make it easy to match products => payments except from invoices+ all_invoices = ::Stripe::Invoice.list({ customer: customer_id }, stripe_request_opts)+ invoices_with_products = parse_invoices(all_invoices, product_ids)+ invoice_ids = invoices_with_products.map { |invoice| invoice[:id] }+ payments = ::Stripe::PaymentIntent.list({ customer: customer_id }, stripe_request_opts)+ payments_from_invoices =+ payments[:data].select { |payment| invoice_ids.include?(payment[:invoice]) }- # Pricing table one-off purchases do not have invoices- payments_without_invoices =- payments[:data].select { |payment| payment[:invoice].nil? }+ if SiteSetting.discourse_subscriptions_enable_verbose_logging+ Rails.logger.warn("Payments from invoices: #{payments_from_invoices}")+ end- if SiteSetting.discourse_subscriptions_enable_verbose_logging- Rails.logger.warn("Payments without invoices: #{payments_without_invoices}")- end+ # Pricing table one-off purchases do not have invoices+ payments_without_invoices = payments[:data].select { |payment| payment[:invoice].nil? }- data = data | payments_from_invoices | payments_without_invoices+ if SiteSetting.discourse_subscriptions_enable_verbose_logging+ Rails.logger.warn("Payments without invoices: #{payments_without_invoices}")end++ data = data | payments_from_invoices | payments_without_invoicesend+ end- if SiteSetting.discourse_subscriptions_pricing_table_enabled && current_user.email- related_guest_payments = fetch_guest_payments(current_user.email)- if SiteSetting.discourse_subscriptions_enable_verbose_logging- Rails.logger.warn("Related guest payments: #{related_guest_payments}")- end- data = data | related_guest_payments+ if SiteSetting.discourse_subscriptions_pricing_table_enabled && current_user.email+ related_guest_payments = fetch_guest_payments(current_user.email)+ if SiteSetting.discourse_subscriptions_enable_verbose_logging+ Rails.logger.warn("Related guest payments: #{related_guest_payments}")end+ data = data | related_guest_payments+ end- data = data.sort_by { |pmt| pmt[:created] }.reverse+ data = data.sort_by { |pmt| pmt[:created] }.reverse- render_json_dump data- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message- end+ render_json_dump data+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageendprivatediff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/subscriptions_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/subscriptions_controller.rbindex 0983b79412f..d3fd52a65a8 100644--- a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/subscriptions_controller.rb+++ b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/subscriptions_controller.rb@@ -12,70 +12,65 @@ module DiscourseSubscriptionsrequires_logindef index- begin- customer = Customer.where(user_id: current_user.id)- customer_ids = customer.map { |c| c.id } if customer- stripe_customer_ids = customer.map { |c| c.customer_id }.uniq if customer- subscription_ids =- Subscription.where("customer_id in (?)", customer_ids).pluck(- :external_id,- ) if customer_ids-- subscriptions = []-- if subscription_ids- prices = []- price_params = { limit: 100, expand: ["data.product"] }- loop do- response = ::Stripe::Price.list(price_params, stripe_request_opts)- prices.concat(response[:data])- break unless response[:has_more]- price_params[:starting_after] = response[:data].last.id- end- all_subscriptions = []-- stripe_customer_ids.each do |stripe_customer_id|- customer_subscriptions =- ::Stripe::Subscription.list(- { customer: stripe_customer_id, status: "all" },- stripe_request_opts,- )- all_subscriptions.concat(customer_subscriptions[:data])- end-- subscriptions = all_subscriptions.select { |sub| subscription_ids.include?(sub[:id]) }- subscriptions.map! do |subscription|- plan = prices.find { |p| p[:id] == subscription[:items][:data][0][:price][:id] }- subscription.to_h.except!(:plan)- subscription.to_h.merge(plan: plan, product: plan[:product].to_h.slice(:id, :name))- end+ customer = Customer.where(user_id: current_user.id)+ customer_ids = customer.map { |c| c.id } if customer+ stripe_customer_ids = customer.map { |c| c.customer_id }.uniq if customer+ subscription_ids =+ Subscription.where("customer_id in (?)", customer_ids).pluck(:external_id) if customer_ids++ subscriptions = []++ if subscription_ids+ prices = []+ price_params = { limit: 100, expand: ["data.product"] }+ loop do+ response = ::Stripe::Price.list(price_params, stripe_request_opts)+ prices.concat(response[:data])+ break unless response[:has_more]+ price_params[:starting_after] = response[:data].last.id+ end+ all_subscriptions = []++ stripe_customer_ids.each do |stripe_customer_id|+ customer_subscriptions =+ ::Stripe::Subscription.list(+ { customer: stripe_customer_id, status: "all" },+ stripe_request_opts,+ )+ all_subscriptions.concat(customer_subscriptions[:data])end- render_json_dump subscriptions- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message+ subscriptions = all_subscriptions.select { |sub| subscription_ids.include?(sub[:id]) }+ subscriptions.map! do |subscription|+ plan = prices.find { |p| p[:id] == subscription[:items][:data][0][:price][:id] }+ subscription.to_h.except!(:plan)+ subscription.to_h.merge(plan: plan, product: plan[:product].to_h.slice(:id, :name))+ endend++ render_json_dump subscriptions+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef destroy# we cancel but don't remove until the end of the period# full removal is done via webhooks- begin- subscription =- ::Stripe::Subscription.update(- params[:id],- { cancel_at_period_end: true },- stripe_request_opts,- )-- if subscription- render_json_dump subscription- else- render_json_error I18n.t("discourse_subscriptions.customer_not_found")- end- rescue ::Stripe::InvalidRequestError => e- render_json_error e.message++ subscription =+ ::Stripe::Subscription.update(+ params[:id],+ { cancel_at_period_end: true },+ stripe_request_opts,+ )++ if subscription+ render_json_dump subscription+ else+ render_json_error I18n.t("discourse_subscriptions.customer_not_found")end+ rescue ::Stripe::InvalidRequestError => e+ render_json_error e.messageenddef updatediff --git a/plugins/discourse-subscriptions/app/serializers/discourse_subscriptions/payment_serializer.rb b/plugins/discourse-subscriptions/app/serializers/discourse_subscriptions/payment_serializer.rbindex 5e19823651a..4587af70778 100644--- a/plugins/discourse-subscriptions/app/serializers/discourse_subscriptions/payment_serializer.rb+++ b/plugins/discourse-subscriptions/app/serializers/discourse_subscriptions/payment_serializer.rb@@ -30,11 +30,9 @@ module DiscourseSubscriptionsprivatedef user- begin- User.find(object.user_id)- rescue StandardError- nil- end+ User.find(object.user_id)+ rescue StandardError+ nilenddef currency_unitdiff --git a/plugins/discourse-subscriptions/app/services/discourse_subscriptions/campaign.rb b/plugins/discourse-subscriptions/app/services/discourse_subscriptions/campaign.rbindex 0d250c34fbf..68297da1151 100644--- a/plugins/discourse-subscriptions/app/services/discourse_subscriptions/campaign.rb+++ b/plugins/discourse-subscriptions/app/services/discourse_subscriptions/campaign.rb@@ -37,16 +37,14 @@ module DiscourseSubscriptionsenddef create_campaign- begin- group = create_campaign_group- product = create_campaign_product- create_campaign_prices(product, group)-- SiteSetting.discourse_subscriptions_campaign_enabled = true- SiteSetting.discourse_subscriptions_campaign_product = product[:id]- rescue ::Stripe::InvalidRequestError => e- e- end+ group = create_campaign_group+ product = create_campaign_product+ create_campaign_prices(product, group)++ SiteSetting.discourse_subscriptions_campaign_enabled = true+ SiteSetting.discourse_subscriptions_campaign_product = product[:id]+ rescue ::Stripe::InvalidRequestError => e+ eendprotecteddiff --git a/plugins/discourse-subscriptions/plugin.rb b/plugins/discourse-subscriptions/plugin.rbindex fb8aae8f5b0..5dce15af784 100644--- a/plugins/discourse-subscriptions/plugin.rb+++ b/plugins/discourse-subscriptions/plugin.rb@@ -78,14 +78,12 @@ after_initialize doDiscourse::Application.routes.append { mount DiscourseSubscriptions::Engine, at: "s" }add_to_serializer(:site, :show_campaign_banner) do- begin- enabled = SiteSetting.discourse_subscriptions_enabled- campaign_enabled = SiteSetting.discourse_subscriptions_campaign_enabled- goal_met = Discourse.redis.get("subscriptions_goal_met_date")-- enabled && campaign_enabled && (!goal_met || 7.days.ago <= Date.parse(goal_met))- rescue StandardError- false- end+ enabled = SiteSetting.discourse_subscriptions_enabled+ campaign_enabled = SiteSetting.discourse_subscriptions_campaign_enabled+ goal_met = Discourse.redis.get("subscriptions_goal_met_date")++ enabled && campaign_enabled && (!goal_met || 7.days.ago <= Date.parse(goal_met))+ rescue StandardError+ falseendenddiff --git a/plugins/discourse-templates/lib/tasks/discourse-templates.rake b/plugins/discourse-templates/lib/tasks/discourse-templates.rakeindex 25573b6eeda..755cc65aa84 100644--- a/plugins/discourse-templates/lib/tasks/discourse-templates.rake+++ b/plugins/discourse-templates/lib/tasks/discourse-templates.rake@@ -177,9 +177,8 @@ enddef purge_old_dataputs "Removing canned replies data"- begin- ActiveRecord::Base.transaction do- DB.exec <<~SQL+ ActiveRecord::Base.transaction do+ DB.exec <<~SQLDELETE FROM site_settings#{" "}WHERE name IN ('canned_replies_groups',#{" "}@@ -188,20 +187,19 @@ def purge_old_data)SQL- canned_replies_plugin_name = "discourse-canned-replies"- canned_replies_store_name = "replies"- old_replies =- PluginStoreRow.find_by(- plugin_name: canned_replies_plugin_name,- key: canned_replies_store_name,- )+ canned_replies_plugin_name = "discourse-canned-replies"+ canned_replies_store_name = "replies"+ old_replies =+ PluginStoreRow.find_by(+ plugin_name: canned_replies_plugin_name,+ key: canned_replies_store_name,+ )- old_replies.presence&.destroy!+ old_replies.presence&.destroy!- puts "Finished!"- rescue StandardError => e- puts e- puts "Transaction aborted! All changes were rolled back!"- end+ puts "Finished!"+ rescue StandardError => e+ puts e+ puts "Transaction aborted! All changes were rolled back!"endenddiff --git a/script/biggest_objects.rb b/script/biggest_objects.rbindex 220fff3c00d..7585b3e666f 100644--- a/script/biggest_objects.rb+++ b/script/biggest_objects.rb@@ -20,11 +20,9 @@ ObjectSpace.trace_object_allocations doRailsMultisite::ConnectionManagement.each_connection do(ActiveRecord::Base.connection.tables - %w[schema_migrations versions]).each do |table|- begin- table.classify.constantize.first- rescue StandardError- nil- end+ table.classify.constantize.first+ rescue StandardError+ nilendendenddiff --git a/script/boot_mem.rb b/script/boot_mem.rbindex 44fb2b84074..0962e58aec1 100644--- a/script/boot_mem.rb+++ b/script/boot_mem.rb@@ -21,11 +21,9 @@ MemoryProfiler# load up all models and schema(ActiveRecord::Base.connection.tables - %w[schema_migrations versions]).each do |table|- begin- table.classify.constantize.first- rescue StandardError- nil- end+ table.classify.constantize.first+ rescue StandardError+ nilendend.pretty_printdiff --git a/script/bulk_import/base.rb b/script/bulk_import/base.rbindex b368f821782..b953f26335f 100644--- a/script/bulk_import/base.rb+++ b/script/bulk_import/base.rb@@ -2189,24 +2189,20 @@ class BulkImport::Basebegin@raw_connection.copy_data(sql, @encoder) dorows.each do |row|- begin- if (mapped = yield(row))- processed = send(process_method_name, mapped)- imported_ids << mapped[:imported_id] unless mapped[:imported_id].nil?- imported_ids |= mapped[:imported_ids] unless mapped[:imported_ids].nil?- unless processed[:skip]- @raw_connection.put_copy_data columns.map { |c| processed[c] }- end- end- rows_created += 1- if rows_created % 100 == 0- print "\r%7d - %6d/sec" % [rows_created, rows_created.to_f / (Time.now - start)]- end- rescue => e- puts "\n"- puts "ERROR: #{e.message}"- puts e.backtrace.join("\n")+ if (mapped = yield(row))+ processed = send(process_method_name, mapped)+ imported_ids << mapped[:imported_id] unless mapped[:imported_id].nil?+ imported_ids |= mapped[:imported_ids] unless mapped[:imported_ids].nil?+ @raw_connection.put_copy_data columns.map { |c| processed[c] } unless processed[:skip]end+ rows_created += 1+ if rows_created % 100 == 0+ print "\r%7d - %6d/sec" % [rows_created, rows_created.to_f / (Time.now - start)]+ end+ rescue => e+ puts "\n"+ puts "ERROR: #{e.message}"+ puts e.backtrace.join("\n")endendrescue => ediff --git a/script/bulk_import/phpbb_postgresql.rb b/script/bulk_import/phpbb_postgresql.rbindex d123ea28cb8..3363343f151 100644--- a/script/bulk_import/phpbb_postgresql.rb+++ b/script/bulk_import/phpbb_postgresql.rb@@ -423,12 +423,10 @@ class BulkImport::PhpBB < BulkImport::Baseprotecteddef bbcode_to_md(text)- begin- text.bbcode_to_md(false)- rescue => e- puts "Problem converting \n#{text}\n using ruby-bbcode-to-md"- text- end+ text.bbcode_to_md(false)+ rescue => e+ puts "Problem converting \n#{text}\n using ruby-bbcode-to-md"+ textenddef add_default_smiliesdiff --git a/script/bulk_import/uploads_importer.rb b/script/bulk_import/uploads_importer.rbindex 4b8eaa8d929..4dca236128a 100644--- a/script/bulk_import/uploads_importer.rb+++ b/script/bulk_import/uploads_importer.rb@@ -217,17 +217,15 @@ module BulkImporterror_message = nilupload =copy_to_tempfile(path) do |file|- begin- UploadCreator.new(- file,- metadata.original_filename,- type: row["type"],- origin: metadata.origin_url,- ).create_for(Discourse::SYSTEM_USER_ID)- rescue StandardError => e- error_message = e.message- nil- end+ UploadCreator.new(+ file,+ metadata.original_filename,+ type: row["type"],+ origin: metadata.origin_url,+ ).create_for(Discourse::SYSTEM_USER_ID)+ rescue StandardError => e+ error_message = e.message+ nilendif (upload_okay = upload.present? && upload.persisted? && upload.errors.blank?)diff --git a/script/cache_critical_dns b/script/cache_critical_dnsindex 2e38583ee4b..6abab249d0a 100755--- a/script/cache_critical_dns+++ b/script/cache_critical_dns@@ -186,12 +186,12 @@ class SRVNametargets = dns_client.getresources(@name, Resolv::DNS::Resource::IN::SRV)targets.delete_if { |t| !@prio_filter.within_threshold?(t.priority) }targets.each do |t|- begin+Name.new(t.target.to_s).resolve.each do |ra|results << ResolvedAddress.new(address: ra.address, priority: t.priority)endrescue Resolv::ResolvError, Resolv::ResolvTimeout- end+endendenddiff --git a/script/db_timestamps_mover.rb b/script/db_timestamps_mover.rbindex fc92d54b19b..417e8954271 100644--- a/script/db_timestamps_mover.rb+++ b/script/db_timestamps_mover.rb@@ -117,19 +117,15 @@ class TimestampsUpdaterenddef is_i?(string)- begin- true if Integer(string)- rescue StandardError- false- end+ true if Integer(string)+rescue StandardError+ falseenddef is_date?(string)- begin- true if Date.parse(string)- rescue StandardError- false- end+ true if Date.parse(string)+rescue StandardError+ falseenddef create_updaterdiff --git a/script/discourse b/script/discourseindex 1e1c21a2368..e6189cc7d7d 100755--- a/script/discourse+++ b/script/discourse@@ -366,7 +366,7 @@ class DiscourseCLI < Thorenddef do_remap(from, to)- begin+remap_options = {verbose: true,skip_max_length_violations: options[:skip_max_length_violations],@@ -390,7 +390,7 @@ class DiscourseCLI < Thorputs "Error: #{ex}"puts "The remap has only been partially applied due to the error above. Please re-run the script again."exit(1)- end+endenddiff --git a/script/import_scripts/answerhub.rb b/script/import_scripts/answerhub.rbindex a95d0c474d1..488c5d4e355 100644--- a/script/import_scripts/answerhub.rb+++ b/script/import_scripts/answerhub.rb@@ -232,20 +232,18 @@ class ImportScripts::AnswerHub < ImportScripts::Basecreated_at: p["c_creation_date"],post_create_action:proc do |post_info|- begin- if p["c_type"] == "answer" && p["c_marked"] == 1- post = Post.find(post_info[:id])- if post- user_id =- user_id_from_imported_user_id(p["c_author"]) || Discourse::SYSTEM_USER_ID- current_user = User.find(user_id)- solved = DiscourseSolved.accept_answer!(post, current_user)- # puts "SOLVED: #{solved}"- end+ if p["c_type"] == "answer" && p["c_marked"] == 1+ post = Post.find(post_info[:id])+ if post+ user_id =+ user_id_from_imported_user_id(p["c_author"]) || Discourse::SYSTEM_USER_ID+ current_user = User.find(user_id)+ solved = DiscourseSolved.accept_answer!(post, current_user)+ # puts "SOLVED: #{solved}"end- rescue ActiveRecord::RecordInvalid- puts "SOLVED: Skipped post_id: #{post.id} because invalid"end+ rescue ActiveRecord::RecordInvalid+ puts "SOLVED: Skipped post_id: #{post.id} because invalid"end,}end@@ -356,38 +354,36 @@ class ImportScripts::AnswerHub < ImportScripts::Baseavatars = @client.query(query)avatars.each do |a|- begin- user_id = user_id_from_imported_user_id(a["c_user"])- user = User.find(user_id)- if user- filename = "avatar-#{user_id}.png"- path = File.join(AVATAR_DIR, filename)- next if !File.exist?(path)-- # Scrape Avatars - Avatars are saved in the db, but it might be easier to just scrape them- if SCRAPE_AVATARS == 1- File.open(path, "wb") do |f|- f << open(- "https://#{ANSWERHUB_DOMAIN}/forums/users/#{a["c_user"]}/photo/view.html?s=240",- ).read- end+ user_id = user_id_from_imported_user_id(a["c_user"])+ user = User.find(user_id)+ if user+ filename = "avatar-#{user_id}.png"+ path = File.join(AVATAR_DIR, filename)+ next if !File.exist?(path)++ # Scrape Avatars - Avatars are saved in the db, but it might be easier to just scrape them+ if SCRAPE_AVATARS == 1+ File.open(path, "wb") do |f|+ f << open(+ "https://#{ANSWERHUB_DOMAIN}/forums/users/#{a["c_user"]}/photo/view.html?s=240",+ ).readend+ end- upload = @uploader.create_upload(user.id, path, filename)+ upload = @uploader.create_upload(user.id, path, filename)- if upload.persisted?- user.import_mode = false- user.create_user_avatar- user.import_mode = true- user.user_avatar.update(custom_upload_id: upload.id)- user.update(uploaded_avatar_id: upload.id)- else- Rails.logger.error("Could not persist avatar for user #{user.username}")- end+ if upload.persisted?+ user.import_mode = false+ user.create_user_avatar+ user.import_mode = true+ user.user_avatar.update(custom_upload_id: upload.id)+ user.update(uploaded_avatar_id: upload.id)+ else+ Rails.logger.error("Could not persist avatar for user #{user.username}")end- rescue ActiveRecord::RecordNotFound- puts "Could not find User for user_id: #{a["c_user"]}"end+ rescue ActiveRecord::RecordNotFound+ puts "Could not find User for user_id: #{a["c_user"]}"endenddiff --git a/script/import_scripts/base.rb b/script/import_scripts/base.rbindex c43cf9c4c0f..7656168cd24 100644--- a/script/import_scripts/base.rb+++ b/script/import_scripts/base.rb@@ -217,25 +217,23 @@ class ImportScripts::Basereturn false if import_ids.empty?ActiveRecord::Base.transaction do- begin- connection = ActiveRecord::Base.connection.raw_connection- connection.exec("CREATE TEMP TABLE import_ids(val text PRIMARY KEY)")+ connection = ActiveRecord::Base.connection.raw_connection+ connection.exec("CREATE TEMP TABLE import_ids(val text PRIMARY KEY)")- import_id_clause =- import_ids.map { |id| "('#{PG::Connection.escape_string(id.to_s)}')" }.join(",")+ import_id_clause =+ import_ids.map { |id| "('#{PG::Connection.escape_string(id.to_s)}')" }.join(",")- connection.exec("INSERT INTO import_ids VALUES #{import_id_clause}")+ connection.exec("INSERT INTO import_ids VALUES #{import_id_clause}")- existing = "#{type.to_s.classify}CustomField".constantize- existing = existing.where(name: "import_id").joins("JOIN import_ids ON val = value").count+ existing = "#{type.to_s.classify}CustomField".constantize+ existing = existing.where(name: "import_id").joins("JOIN import_ids ON val = value").count- if existing == import_ids.length- puts "Skipping #{import_ids.length} already imported #{type}"- true- end- ensure- connection.exec("DROP TABLE import_ids") unless connection.nil?+ if existing == import_ids.length+ puts "Skipping #{import_ids.length} already imported #{type}"+ trueend+ ensure+ connection.exec("DROP TABLE import_ids") unless connection.nil?endenddiff --git a/script/import_scripts/drupal.rb b/script/import_scripts/drupal.rbindex 42b165c6880..5c0d2e222e6 100644--- a/script/import_scripts/drupal.rb+++ b/script/import_scripts/drupal.rb@@ -408,17 +408,15 @@ class ImportScripts::Drupal < ImportScripts::Baseputs "", "creating permalinks..."Topic.listable_topics.find_each do |topic|- begin- tcf = topic.custom_fields- if tcf && tcf["import_id"]- node_id = tcf["import_id"][/nid:(\d+)/, 1]- slug = "/node/#{node_id}"- Permalink.create(url: slug, topic_id: topic.id)- end- rescue => e- puts e.message- puts "Permalink creation failed for id #{topic.id}"+ tcf = topic.custom_fields+ if tcf && tcf["import_id"]+ node_id = tcf["import_id"][/nid:(\d+)/, 1]+ slug = "/node/#{node_id}"+ Permalink.create(url: slug, topic_id: topic.id)end+ rescue => e+ puts e.message+ puts "Permalink creation failed for id #{topic.id}"endend@@ -471,35 +469,33 @@ class ImportScripts::Drupal < ImportScripts::Basemax = Post.countPost.find_each do |post|- begin- raw = post.raw- new_raw = raw.dup-- # replace old topic to new topic links- new_raw.gsub!(%r{https://site.com/forum/topic/(\d+)}im) do- post_id = post_id_from_imported_post_id("nid:#{$1}")- next unless post_id- topic = Post.find(post_id).topic- "https://community.site.com/t/-/#{topic.id}"- end+ raw = post.raw+ new_raw = raw.dup++ # replace old topic to new topic links+ new_raw.gsub!(%r{https://site.com/forum/topic/(\d+)}im) do+ post_id = post_id_from_imported_post_id("nid:#{$1}")+ next unless post_id+ topic = Post.find(post_id).topic+ "https://community.site.com/t/-/#{topic.id}"+ end- # replace old comment to reply links- new_raw.gsub!(%r{https://site.com/comment/(\d+)#comment-\d+}im) do- post_id = post_id_from_imported_post_id("cid:#{$1}")- next unless post_id- post_ref = Post.find(post_id)- "https://community.site.com/t/-/#{post_ref.topic_id}/#{post_ref.post_number}"- end+ # replace old comment to reply links+ new_raw.gsub!(%r{https://site.com/comment/(\d+)#comment-\d+}im) do+ post_id = post_id_from_imported_post_id("cid:#{$1}")+ next unless post_id+ post_ref = Post.find(post_id)+ "https://community.site.com/t/-/#{post_ref.topic_id}/#{post_ref.post_number}"+ end- if raw != new_raw- post.raw = new_raw- post.save- end- rescue StandardError- puts "", "Failed rewrite on post: #{post.id}"- ensure- print_status(current += 1, max)+ if raw != new_raw+ post.raw = new_raw+ post.saveend+ rescue StandardError+ puts "", "Failed rewrite on post: #{post.id}"+ ensure+ print_status(current += 1, max)endend@@ -508,14 +504,12 @@ class ImportScripts::Drupal < ImportScripts::Basecurrent = 0max = User.countUser.find_each do |user|- begin- user.create_user_avatar(user_id: user.id) unless user.user_avatar- user.user_avatar.update_gravatar!- rescue StandardError- puts "", 'Failed avatar update on user #{user.id}'- ensure- print_status(current += 1, max)- end+ user.create_user_avatar(user_id: user.id) unless user.user_avatar+ user.user_avatar.update_gravatar!+ rescue StandardError+ puts "", 'Failed avatar update on user #{user.id}'+ ensure+ print_status(current += 1, max)endenddiff --git a/script/import_scripts/google_groups.rb b/script/import_scripts/google_groups.rbindex d6a095f5091..90ccc5f241e 100755--- a/script/import_scripts/google_groups.rb+++ b/script/import_scripts/google_groups.rb@@ -39,33 +39,27 @@ MAX_GET_RETRIES = 5MAX_FIND_RETRIES = 3def get(url)- begin- retries ||= 0- driver.get(url)- rescue Net::ReadTimeout- sleep retries- retry if (retries += 1) < MAX_GET_RETRIES- end+ retries ||= 0+ driver.get(url)+rescue Net::ReadTimeout+ sleep retries+ retry if (retries += 1) < MAX_GET_RETRIESenddef extract(css, parent_element = driver)- begin- retries ||= 0- parent_element.find_elements(css: css).map { |element| yield(element) }- rescue Net::ReadTimeout, Selenium::WebDriver::Error::StaleElementReferenceError- sleep retries- retry if (retries += 1) < MAX_FIND_RETRIES- end+ retries ||= 0+ parent_element.find_elements(css: css).map { |element| yield(element) }+rescue Net::ReadTimeout, Selenium::WebDriver::Error::StaleElementReferenceError+ sleep retries+ retry if (retries += 1) < MAX_FIND_RETRIESenddef find(css, parent_element = driver)- begin- retries ||= 0- parent_element.find_element(css: css)- rescue Net::ReadTimeout, Selenium::WebDriver::Error::ElementNotInteractableError- sleep retries- retry if (retries += 1) < MAX_FIND_RETRIES- end+ retries ||= 0+ parent_element.find_element(css: css)+rescue Net::ReadTimeout, Selenium::WebDriver::Error::ElementNotInteractableError+ sleep retries+ retry if (retries += 1) < MAX_FIND_RETRIESenddef base_urldiff --git a/script/import_scripts/jforum.rb b/script/import_scripts/jforum.rbindex fc407a425b8..c66e80b9db2 100644--- a/script/import_scripts/jforum.rb+++ b/script/import_scripts/jforum.rb@@ -87,10 +87,7 @@ class ImportScripts::JForum < ImportScripts::Baseenddef user_fields- @user_fields ||=- begin- UserField.all.index_by(&:name)- end+ @user_fields ||= UserField.all.index_by(&:name)enddef user_custom_fields(row)diff --git a/script/import_scripts/lithium.rb b/script/import_scripts/lithium.rbindex 2ece7668a63..b44bf6bc704 100644--- a/script/import_scripts/lithium.rb+++ b/script/import_scripts/lithium.rb@@ -924,31 +924,29 @@ SQLPost.where("id > ?", @max_start_id).find_each do |post|- begin- id = post.custom_fields["import_unique_id"]- next unless id- raw = mysql_query("select body from message2 where unique_id = '#{id}'").first["body"]- unless raw- puts "Missing raw for post: #{post.id}"- next- end- new_raw = postprocess_post_raw(raw, post.user_id)- files = attachments.select { |a| a["message_uid"].to_s == id }- new_raw << html_for_attachments(post.user_id, files)- unless post.raw == new_raw- post.raw = new_raw- post.cooked = post.cook(new_raw)- cpp = CookedPostProcessor.new(post)- cpp.link_post_uploads- post.custom_fields["import_post_process"] = true- post.save- end- rescue PrettyText::JavaScriptError- puts "GOT A JS error on post: #{post.id}"- nil- ensure- print_status(current += 1, max)+ id = post.custom_fields["import_unique_id"]+ next unless id+ raw = mysql_query("select body from message2 where unique_id = '#{id}'").first["body"]+ unless raw+ puts "Missing raw for post: #{post.id}"+ next+ end+ new_raw = postprocess_post_raw(raw, post.user_id)+ files = attachments.select { |a| a["message_uid"].to_s == id }+ new_raw << html_for_attachments(post.user_id, files)+ unless post.raw == new_raw+ post.raw = new_raw+ post.cooked = post.cook(new_raw)+ cpp = CookedPostProcessor.new(post)+ cpp.link_post_uploads+ post.custom_fields["import_post_process"] = true+ post.saveend+ rescue PrettyText::JavaScriptError+ puts "GOT A JS error on post: #{post.id}"+ nil+ ensure+ print_status(current += 1, max)endSiteSetting.authorized_extensions = default_extensionsdiff --git a/script/import_scripts/mbox/importer.rb b/script/import_scripts/mbox/importer.rbindex 6f8e60eb4fe..69edf2531ee 100644--- a/script/import_scripts/mbox/importer.rb+++ b/script/import_scripts/mbox/importer.rb@@ -97,18 +97,16 @@ module ImportScripts::Mboxnext if all_records_exist?(:posts, rows.map { |row| row["msg_id"] })create_posts(rows, total: total_count, offset: offset) do |row|- begin- if row["email_date"].blank?- puts "Date is missing. Skipping #{row["msg_id"]}"- nil- elsif row["in_reply_to"].blank?- map_first_post(row)- else- map_reply(row)- end- rescue => e- puts "Failed to map post for #{row["msg_id"]}", e, e.backtrace.join("\n")+ if row["email_date"].blank?+ puts "Date is missing. Skipping #{row["msg_id"]}"+ nil+ elsif row["in_reply_to"].blank?+ map_first_post(row)+ else+ map_reply(row)end+ rescue => e+ puts "Failed to map post for #{row["msg_id"]}", e, e.backtrace.join("\n")endendenddiff --git a/script/import_scripts/mbox/support/indexer.rb b/script/import_scripts/mbox/support/indexer.rbindex 84e9e6f1f57..df9f6a7f429 100644--- a/script/import_scripts/mbox/support/indexer.rb+++ b/script/import_scripts/mbox/support/indexer.rb@@ -65,67 +65,65 @@ module ImportScripts::Mboxdef index_emails(directory, category_name)all_messages(directory, category_name) do |receiver, filename, opts|- begin- msg_id = receiver.message_id- parsed_email = receiver.mail-- from_email, from_display_name = receiver.parse_from_field(parsed_email)-- if @settings.fix_mailman_via_addresses- # Detect cases like this and attempt to get actual sender from other headers:- # From: Jane Smith via ListName <[email protected]>-- if receiver.mail["X-Mailman-Version"] && from_display_name =~ /\bvia \S+$/i- email_from_from_line = opts[:from_line].scan(/From (\S+)/).flatten.first- a = Mail::Address.new(email_from_from_line)- from_email = a.address- from_display_name = a.display_name- # if name is not available there, look for it in Reply-To- if from_display_name.nil?- reply_to = receiver.mail.to_s.scan(/[\n\r]Reply-To: ([^\r\n]+)/).flatten.first- from_display_name = Mail::Address.new(reply_to).display_name- end+ msg_id = receiver.message_id+ parsed_email = receiver.mail++ from_email, from_display_name = receiver.parse_from_field(parsed_email)++ if @settings.fix_mailman_via_addresses+ # Detect cases like this and attempt to get actual sender from other headers:+ # From: Jane Smith via ListName <[email protected]>++ if receiver.mail["X-Mailman-Version"] && from_display_name =~ /\bvia \S+$/i+ email_from_from_line = opts[:from_line].scan(/From (\S+)/).flatten.first+ a = Mail::Address.new(email_from_from_line)+ from_email = a.address+ from_display_name = a.display_name+ # if name is not available there, look for it in Reply-To+ if from_display_name.nil?+ reply_to = receiver.mail.to_s.scan(/[\n\r]Reply-To: ([^\r\n]+)/).flatten.first+ from_display_name = Mail::Address.new(reply_to).display_nameendend+ end- from_email = from_email.sub(/^(.*)=/, "") if @settings.elide_equals_in_addresses-- body, elided, format = receiver.select_body- reply_message_ids = extract_reply_message_ids(parsed_email)-- email = {- msg_id: msg_id,- from_email: from_email,- from_name: from_display_name,- subject: extract_subject(receiver, category_name),- email_date: timestamp(parsed_email.date),- raw_message: receiver.raw_email,- body: body,- elided: elided,- format: format,- attachment_count: receiver.attachments.count,- charset: parsed_email.charset&.downcase,- category: category_name,- filename: File.basename(filename),- first_line_number: opts[:first_line_number],- last_line_number: opts[:last_line_number],- index_duration: (monotonic_time - opts[:start_time]).round(4),- }-- @database.transaction do |db|- db.insert_email(email)- db.insert_replies(msg_id, reply_message_ids) unless reply_message_ids.empty?- end- rescue StandardError => e- if opts[:first_line_number] && opts[:last_line_number]- STDERR.puts "Failed to index message in #{filename} at lines #{opts[:first_line_number]}-#{opts[:last_line_number]}"- else- STDERR.puts "Failed to index message in #{filename}"- end-- STDERR.puts e.message- STDERR.puts e.backtrace.inspect+ from_email = from_email.sub(/^(.*)=/, "") if @settings.elide_equals_in_addresses++ body, elided, format = receiver.select_body+ reply_message_ids = extract_reply_message_ids(parsed_email)++ email = {+ msg_id: msg_id,+ from_email: from_email,+ from_name: from_display_name,+ subject: extract_subject(receiver, category_name),+ email_date: timestamp(parsed_email.date),+ raw_message: receiver.raw_email,+ body: body,+ elided: elided,+ format: format,+ attachment_count: receiver.attachments.count,+ charset: parsed_email.charset&.downcase,+ category: category_name,+ filename: File.basename(filename),+ first_line_number: opts[:first_line_number],+ last_line_number: opts[:last_line_number],+ index_duration: (monotonic_time - opts[:start_time]).round(4),+ }++ @database.transaction do |db|+ db.insert_email(email)+ db.insert_replies(msg_id, reply_message_ids) unless reply_message_ids.empty?end+ rescue StandardError => e+ if opts[:first_line_number] && opts[:last_line_number]+ STDERR.puts "Failed to index message in #{filename} at lines #{opts[:first_line_number]}-#{opts[:last_line_number]}"+ else+ STDERR.puts "Failed to index message in #{filename}"+ end++ STDERR.puts e.message+ STDERR.puts e.backtrace.inspectendenddiff --git a/script/import_scripts/modx.rb b/script/import_scripts/modx.rbindex 2beb481a7d9..de66bb4fd7a 100644--- a/script/import_scripts/modx.rb+++ b/script/import_scripts/modx.rb@@ -490,17 +490,15 @@ FROM #{TABLE_PREFIX}discuss_usersmax = Post.countPost.find_each do |post|- begin- new_raw = postprocess_post_raw(post.raw)- if new_raw != post.raw- post.raw = new_raw- post.save- end- rescue PrettyText::JavaScriptError- nil- ensure- print_status(current += 1, max)+ new_raw = postprocess_post_raw(post.raw)+ if new_raw != post.raw+ post.raw = new_raw+ post.saveend+ rescue PrettyText::JavaScriptError+ nil+ ensure+ print_status(current += 1, max)endenddiff --git a/script/import_scripts/mylittleforum.rb b/script/import_scripts/mylittleforum.rbindex fd797fef07d..6855bfc9104 100644--- a/script/import_scripts/mylittleforum.rb+++ b/script/import_scripts/mylittleforum.rb@@ -826,13 +826,9 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Baseenddef append_missing_upload(filename)- begin- File.open(@missing_uploads_path, "a") { |f| f.puts(filename) }- rescue => e- print_warning(- "Could not append to missing uploads list #{@missing_uploads_path}: #{e.message}",- )- end+ File.open(@missing_uploads_path, "a") { |f| f.puts(filename) }+ rescue => e+ print_warning("Could not append to missing uploads list #{@missing_uploads_path}: #{e.message}")enddef find_uploads_table_name@@ -1020,35 +1016,33 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Base.where("raw LIKE '%/images/uploaded/%'").find_in_batches(batch_size: BATCH_SIZE) do |posts|posts.each do |post|+ old_raw = post.raw.to_s+ next if old_raw.blank?+ #next unless old_raw =~ @legacy_upload_regex+ next if old_raw.exclude?("/images/uploaded/")begin- old_raw = post.raw.to_s- next if old_raw.blank?- #next unless old_raw =~ @legacy_upload_regex- next if old_raw.exclude?("/images/uploaded/")- begin- total_legacy = old_raw.scan(@legacy_upload_regex).length- mapped_legacy =- old_raw- .scan(@legacy_upload_regex)- .count { |m| @upload_map[m.is_a?(Array) ? m.last : m] }- if total_legacy > 0- print_warning(- "Repair post #{post.id}: legacy=#{total_legacy}, mapped=#{mapped_legacy}",- )- end- rescue StandardError+ total_legacy = old_raw.scan(@legacy_upload_regex).length+ mapped_legacy =+ old_raw+ .scan(@legacy_upload_regex)+ .count { |m| @upload_map[m.is_a?(Array) ? m.last : m] }+ if total_legacy > 0+ print_warning(+ "Repair post #{post.id}: legacy=#{total_legacy}, mapped=#{mapped_legacy}",+ )end+ rescue StandardError+ end- new_raw = rewrite_legacy_uploads(old_raw)- next if new_raw == old_raw+ new_raw = rewrite_legacy_uploads(old_raw)+ next if new_raw == old_raw- post.raw = new_raw- post.save!- post.rebake!- print "."- rescue => e- print_warning("Repair failed for post #{post.id}: #{e.message}")- end+ post.raw = new_raw+ post.save!+ post.rebake!+ print "."+ rescue => e+ print_warning("Repair failed for post #{post.id}: #{e.message}")endenddiff --git a/script/import_scripts/nodebb/nodebb.rb b/script/import_scripts/nodebb/nodebb.rbindex f6db2b0e41f..a3241fde877 100644--- a/script/import_scripts/nodebb/nodebb.rb+++ b/script/import_scripts/nodebb/nodebb.rb@@ -476,18 +476,16 @@ class ImportScripts::NodeBB < ImportScripts::Basestart_time = Time.nowPost.find_each do |post|- begin- next if post.custom_fields["import_post_processing"]+ next if post.custom_fields["import_post_processing"]- new_raw = postprocess_post(post)- if new_raw != post.raw- post.raw = new_raw- post.custom_fields["import_post_processing"] = true- post.save- end- ensure- print_status(current += 1, max, start_time)+ new_raw = postprocess_post(post)+ if new_raw != post.raw+ post.raw = new_raw+ post.custom_fields["import_post_processing"] = true+ post.saveend+ ensure+ print_status(current += 1, max, start_time)endenddiff --git a/script/import_scripts/phpbb3/database/database_3_1.rb b/script/import_scripts/phpbb3/database/database_3_1.rbindex 3255e484b1a..4cf0f91f791 100644--- a/script/import_scripts/phpbb3/database/database_3_1.rb+++ b/script/import_scripts/phpbb3/database/database_3_1.rb@@ -33,13 +33,11 @@ module ImportScripts::PhpBB3def profile_fields_query(profile_fields)@profile_fields_query ||=- begin- if profile_fields.present?- columns = profile_fields.map { |field| "pf_#{field[:phpbb_field_name]}" }- ", #{columns.join(", ")}"- else- ""- end+ if profile_fields.present?+ columns = profile_fields.map { |field| "pf_#{field[:phpbb_field_name]}" }+ ", #{columns.join(", ")}"+ else+ ""endendenddiff --git a/script/import_scripts/phpbb3/importer.rb b/script/import_scripts/phpbb3/importer.rbindex a4f64f82c46..1b42af3b0ff 100644--- a/script/import_scripts/phpbb3/importer.rb+++ b/script/import_scripts/phpbb3/importer.rb@@ -83,12 +83,10 @@ module ImportScripts::PhpBB3break if rows.size < 1create_users(rows, total: total_count, offset: offset) do |row|- begin- next if user_id_from_imported_user_id(@settings.prefix(row[:user_id]))- importer.map_user(row)- rescue => e- log_error("Failed to map user with ID #{row[:user_id]}", e)- end+ next if user_id_from_imported_user_id(@settings.prefix(row[:user_id]))+ importer.map_user(row)+ rescue => e+ log_error("Failed to map user with ID #{row[:user_id]}", e)endendend@@ -104,12 +102,10 @@ module ImportScripts::PhpBB3break if rows.size < 1create_users(rows, total: total_count, offset: offset) do |row|- begin- next if user_id_from_imported_user_id(@settings.prefix(row[:post_username]))- importer.map_anonymous_user(row)- rescue => e- log_error("Failed to map anonymous user with ID #{row[:user_id]}", e)- end+ next if user_id_from_imported_user_id(@settings.prefix(row[:post_username]))+ importer.map_anonymous_user(row)+ rescue => e+ log_error("Failed to map anonymous user with ID #{row[:user_id]}", e)endendend@@ -119,34 +115,32 @@ module ImportScripts::PhpBB3rows = @database.fetch_groupscreate_groups(rows) do |row|- begin- next if row[:group_type] == 3-- group_name =- if @settings.site_name.present?- "#{@settings.site_name}_#{row[:group_name]}"- else- row[:group_name]- end[- 0..19- ].gsub(/[^a-zA-Z0-9\-_. ]/, "_")-- bio_raw =- begin- @importers.text_processor.process_raw_text(row[:group_desc])- rescue StandardError- row[:group_desc]- end+ next if row[:group_type] == 3++ group_name =+ if @settings.site_name.present?+ "#{@settings.site_name}_#{row[:group_name]}"+ else+ row[:group_name]+ end[+ 0..19+ ].gsub(/[^a-zA-Z0-9\-_. ]/, "_")++ bio_raw =+ begin+ @importers.text_processor.process_raw_text(row[:group_desc])+ rescue StandardError+ row[:group_desc]+ end- {- id: @settings.prefix(row[:group_id]),- name: group_name,- full_name: row[:group_name],- bio_raw: bio_raw,- }- rescue => e- log_error("Failed to map group with ID #{row[:group_id]}", e)- end+ {+ id: @settings.prefix(row[:group_id]),+ name: group_name,+ full_name: row[:group_name],+ bio_raw: bio_raw,+ }+ rescue => e+ log_error("Failed to map group with ID #{row[:group_id]}", e)endend@@ -210,12 +204,10 @@ module ImportScripts::PhpBB3break if rows.size < 1create_posts(rows, total: total_count, offset: offset) do |row|- begin- next if post_id_from_imported_post_id(@settings.prefix(row[:post_id]))- importer.map_post(row)- rescue => e- log_error("Failed to map post with ID #{row[:post_id]}", e)- end+ next if post_id_from_imported_post_id(@settings.prefix(row[:post_id]))+ importer.map_post(row)+ rescue => e+ log_error("Failed to map post with ID #{row[:post_id]}", e)endendend@@ -231,12 +223,10 @@ module ImportScripts::PhpBB3break if rows.size < 1create_posts(rows, total: total_count, offset: offset) do |row|- begin- next if post_id_from_imported_post_id(@settings.prefix("pm:#{row[:msg_id]}"))- importer.map_message(row)- rescue => e- log_error("Failed to map message with ID #{row[:msg_id]}", e)- end+ next if post_id_from_imported_post_id(@settings.prefix("pm:#{row[:msg_id]}"))+ importer.map_message(row)+ rescue => e+ log_error("Failed to map message with ID #{row[:msg_id]}", e)endendend@@ -252,11 +242,9 @@ module ImportScripts::PhpBB3break if rows.size < 1create_bookmarks(rows, total: total_count, offset: offset) do |row|- begin- importer.map_bookmark(row)- rescue => e- log_error("Failed to map bookmark (#{row[:user_id]}, #{row[:topic_first_post_id]})", e)- end+ importer.map_bookmark(row)+ rescue => e+ log_error("Failed to map bookmark (#{row[:user_id]}, #{row[:topic_first_post_id]})", e)endendenddiff --git a/script/import_scripts/phpbb3/importers/user_importer.rb b/script/import_scripts/phpbb3/importers/user_importer.rbindex 9c9d24ce833..cb87dd195d1 100644--- a/script/import_scripts/phpbb3/importers/user_importer.rb+++ b/script/import_scripts/phpbb3/importers/user_importer.rb@@ -106,21 +106,16 @@ module ImportScripts::PhpBB3enddef user_fields- @user_fields ||=- begin- UserField.all.index_by(&:name)- end+ @user_fields ||= UserField.all.index_by(&:name)enddef field_mappings@field_mappings ||=- begin- @settings.custom_fields.map do |field|- {- phpbb_field_name: :"pf_#{field[:phpbb_field_name]}",- discourse_user_field: user_fields[field[:discourse_field_name]],- }- end+ @settings.custom_fields.map do |field|+ {+ phpbb_field_name: :"pf_#{field[:phpbb_field_name]}",+ discourse_user_field: user_fields[field[:discourse_field_name]],+ }endenddiff --git a/script/import_scripts/phpbb3/support/text_processor.rb b/script/import_scripts/phpbb3/support/text_processor.rbindex 8e7330bfa26..fb17846d3e0 100644--- a/script/import_scripts/phpbb3/support/text_processor.rb+++ b/script/import_scripts/phpbb3/support/text_processor.rb@@ -72,19 +72,15 @@ module ImportScripts::PhpBB3enddef process_post(raw, attachments)- begin- process_raw_text(raw, attachments)- rescue StandardError- raw- end+ process_raw_text(raw, attachments)+ rescue StandardError+ rawenddef process_private_msg(raw, attachments)- begin- process_raw_text(raw, attachments)- rescue StandardError- raw- end+ process_raw_text(raw, attachments)+ rescue StandardError+ rawendprotected@@ -100,12 +96,10 @@ module ImportScripts::PhpBB3enddef bbcode_to_md(text)- begin- text.bbcode_to_md(false)- rescue => e- puts "Problem converting \n#{text}\n using ruby-bbcode-to-md"- text- end+ text.bbcode_to_md(false)+ rescue => e+ puts "Problem converting \n#{text}\n using ruby-bbcode-to-md"+ textenddef process_smilies(text)diff --git a/script/import_scripts/question2answer.rb b/script/import_scripts/question2answer.rbindex 8a0170a9d71..f8b84477598 100644--- a/script/import_scripts/question2answer.rb+++ b/script/import_scripts/question2answer.rb@@ -284,16 +284,14 @@ class ImportScripts::Question2Answer < ImportScripts::Baseputs "", "importing best answers..."ans = mysql_query("select postid, selchildid from qa_posts where selchildid is not null").to_aans.each do |answer|- begin- post = Post.find_by(id: post_id_from_imported_post_id("#{answer["selchildid"]}"))- post.custom_fields["is_accepted_answer"] = "true"- post.save- topic = Topic.find(post.topic_id)- topic.custom_fields["accepted_answer_post_id"] = post.id- topic.save- rescue => e- puts "error acting on post #{e}"- end+ post = Post.find_by(id: post_id_from_imported_post_id("#{answer["selchildid"]}"))+ post.custom_fields["is_accepted_answer"] = "true"+ post.save+ topic = Topic.find(post.topic_id)+ topic.custom_fields["accepted_answer_post_id"] = post.id+ topic.save+ rescue => e+ puts "error acting on post #{e}"endend@@ -322,17 +320,15 @@ class ImportScripts::Question2Answer < ImportScripts::Basemax = Post.countPost.find_each do |post|- begin- new_raw = postprocess_post_raw(post.raw)- if new_raw != post.raw- post.raw = new_raw- post.save- end- rescue PrettyText::JavaScriptError- nil- ensure- print_status(current += 1, max)+ new_raw = postprocess_post_raw(post.raw)+ if new_raw != post.raw+ post.raw = new_raw+ post.saveend+ rescue PrettyText::JavaScriptError+ nil+ ensure+ print_status(current += 1, max)endenddiff --git a/script/import_scripts/smf2.rb b/script/import_scripts/smf2.rbindex 93d324de916..a3081a96512 100644--- a/script/import_scripts/smf2.rb+++ b/script/import_scripts/smf2.rb@@ -260,14 +260,12 @@ class ImportScripts::Smf2 < ImportScripts::BaseORDER BY id_attach ASCSQLattachments.map! do |a|- begin- import_attachment(post, a)- rescue StandardError- (- puts $!- nil- )- end+ import_attachment(post, a)+ rescue StandardError+ (+ puts $!+ nil+ )endbeginpost[:raw] = convert_message_body(message[:body], attachments, ignore_quotes: ignore_quotes)diff --git a/script/import_scripts/vbulletin.rb b/script/import_scripts/vbulletin.rbindex e49f5f0e9ac..af317e53fe4 100644--- a/script/import_scripts/vbulletin.rb+++ b/script/import_scripts/vbulletin.rb@@ -186,24 +186,22 @@ class ImportScripts::VBulletin < ImportScripts::Baseputs "", "Creating groups membership..."Group.find_each do |group|- begin- next if group.automatic- puts "\t#{group.name}"- next if GroupUser.where(group_id: group.id).count > 0- user_ids_in_group = User.where(primary_group_id: group.id).pluck(:id).to_a- next if user_ids_in_group.size == 0- values =- user_ids_in_group- .map { |user_id| "(#{group.id}, #{user_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)" }- .join(",")-- DB.exec <<~SQL+ next if group.automatic+ puts "\t#{group.name}"+ next if GroupUser.where(group_id: group.id).count > 0+ user_ids_in_group = User.where(primary_group_id: group.id).pluck(:id).to_a+ next if user_ids_in_group.size == 0+ values =+ user_ids_in_group+ .map { |user_id| "(#{group.id}, #{user_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)" }+ .join(",")++ DB.exec <<~SQLINSERT INTO group_users (group_id, user_id, created_at, updated_at) VALUES #{values}SQL- rescue Exception => e- puts e.message- puts e.backtrace.join("\n")- end+ rescue Exception => e+ puts e.message+ puts e.backtrace.join("\n")endGroup.reset_all_counters!@@ -738,18 +736,16 @@ class ImportScripts::VBulletin < ImportScripts::Basemax = Post.countPost.find_each do |post|- begin- old_raw = post.raw.dup- new_raw = postprocess_post_raw(post.raw)- if new_raw != old_raw- post.raw = new_raw- post.save- end- rescue PrettyText::JavaScriptError- nil- ensure- print_status(current += 1, max)+ old_raw = post.raw.dup+ new_raw = postprocess_post_raw(post.raw)+ if new_raw != old_raw+ post.raw = new_raw+ post.saveend+ rescue PrettyText::JavaScriptError+ nil+ ensure+ print_status(current += 1, max)endenddiff --git a/script/import_scripts/vbulletin3.rb b/script/import_scripts/vbulletin3.rbindex 074efce8fb6..c2ab07eedf2 100644--- a/script/import_scripts/vbulletin3.rb+++ b/script/import_scripts/vbulletin3.rb@@ -364,26 +364,24 @@ EOMputs "", "creating groups membership..."Group.find_each do |group|- begin- next if group.automatic- puts "\t#{group.name}"- next if GroupUser.where(group_id: group.id).count > 0- user_ids_in_group = User.where(primary_group_id: group.id).pluck(:id).to_a- next if user_ids_in_group.size == 0- values =- user_ids_in_group- .map { |user_id| "(#{group.id}, #{user_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)" }- .join(",")-- DB.exec <<~SQL+ next if group.automatic+ puts "\t#{group.name}"+ next if GroupUser.where(group_id: group.id).count > 0+ user_ids_in_group = User.where(primary_group_id: group.id).pluck(:id).to_a+ next if user_ids_in_group.size == 0+ values =+ user_ids_in_group+ .map { |user_id| "(#{group.id}, #{user_id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)" }+ .join(",")++ DB.exec <<~SQLINSERT INTO group_users (group_id, user_id, created_at, updated_at) VALUES #{values}SQL- Group.reset_counters(group.id, :group_users)- rescue Exception => e- puts e.message- puts e.backtrace.join("\n")- end+ Group.reset_counters(group.id, :group_users)+ rescue Exception => e+ puts e.message+ puts e.backtrace.join("\n")endend@@ -1337,18 +1335,16 @@ LEFT OUTER JOIN #{TABLE_PREFIX}avatar a ON a.avatarid = u.avataridstart = Time.nowPost.find_each do |post|- begin- old_raw = post.raw.dup- new_raw = postprocess_post_raw(post, post.raw)- if new_raw != old_raw- post.raw = new_raw- post.save- end- rescue PrettyText::JavaScriptError- nil- ensure- print_status(current += 1, max, start)+ old_raw = post.raw.dup+ new_raw = postprocess_post_raw(post, post.raw)+ if new_raw != old_raw+ post.raw = new_raw+ post.saveend+ rescue PrettyText::JavaScriptError+ nil+ ensure+ print_status(current += 1, max, start)endenddiff --git a/script/import_scripts/vbulletin5.rb b/script/import_scripts/vbulletin5.rbindex 147f20d0bb1..e0b35acc09b 100644--- a/script/import_scripts/vbulletin5.rb+++ b/script/import_scripts/vbulletin5.rb@@ -477,17 +477,15 @@ class ImportScripts::VBulletin < ImportScripts::Basemax = Post.countPost.find_each do |post|- begin- new_raw = postprocess_post_raw(post.raw)- if new_raw != post.raw- post.raw = new_raw- post.save- end- rescue PrettyText::JavaScriptError- nil- ensure- print_status(current += 1, max)+ new_raw = postprocess_post_raw(post.raw)+ if new_raw != post.raw+ post.raw = new_raw+ post.saveend+ rescue PrettyText::JavaScriptError+ nil+ ensure+ print_status(current += 1, max)endenddiff --git a/script/import_scripts/zendesk_api.rb b/script/import_scripts/zendesk_api.rbindex 9b111dffa8e..efe27b18e10 100644--- a/script/import_scripts/zendesk_api.rb+++ b/script/import_scripts/zendesk_api.rb@@ -430,17 +430,15 @@ class ImportScripts::ZendeskApi < ImportScripts::Baseretry_count = 0- begin- while retry_count < 5- begin- response = connection.request(get)- puts("Retry successful!") if retry_count > 0- break- rescue => e- puts "Request failed #{url}. Waiting and will retry. #{e.class.name} #{e.message}"- sleep(20)- retry_count += 1- end+ while retry_count < 5+ begin+ response = connection.request(get)+ puts("Retry successful!") if retry_count > 0+ break+ rescue => e+ puts "Request failed #{url}. Waiting and will retry. #{e.class.name} #{e.message}"+ sleep(20)+ retry_count += 1endenddiff --git a/script/local_minio_s3.rb b/script/local_minio_s3.rbindex 18bd52f7c13..f2b5de3e2e9 100755--- a/script/local_minio_s3.rb+++ b/script/local_minio_s3.rb@@ -5,17 +5,15 @@ require "minio_runner"class ExecuteLocalMinioS3def run- begin- start_minio- save_old_config- change_to_minio_settings- puts "Press any key when done..."- gets- restore_old- rescue SystemExit, Interrupt- restore_old- raise- end+ start_minio+ save_old_config+ change_to_minio_settings+ puts "Press any key when done..."+ gets+ restore_old+ rescue SystemExit, Interrupt+ restore_old+ raiseenddef start_miniodiff --git a/script/memory-analysis b/script/memory-analysisindex 84e47676aa3..8159e4fe054 100755--- a/script/memory-analysis+++ b/script/memory-analysis@@ -91,11 +91,10 @@ class Statsdef thread_class@thread_class ||=- begin- @classes.find do |addr, n|+ @classes.find do |addr, n|n == "Thread"end.first- end+enddef detect_threads(line)diff --git a/script/mwrap_sidekiq b/script/mwrap_sidekiqindex 8c2a73a5b7b..581385077da 100755--- a/script/mwrap_sidekiq+++ b/script/mwrap_sidekiq@@ -84,7 +84,7 @@ def mwrap_logendThread.new do- begin+puts "Starting Logging Thread"path = "/tmp/mwrap_#{Process.pid}"`mkdir -p #{path}`@@ -99,7 +99,7 @@ Thread.new dorescue => eSTDERR.puts "ERROR crashed logger #{e}"STDERR.puts e.backtrace- end+endThread.new dodiff --git a/script/profile_db_generator.rb b/script/profile_db_generator.rbindex 7631754cecc..e3a46439880 100644--- a/script/profile_db_generator.rb+++ b/script/profile_db_generator.rb@@ -22,9 +22,7 @@ def unbundled_require(gem)spec.activateend- begin- require gem- end+ require gemenddef sentencediff --git a/script/require_profiler.rb b/script/require_profiler.rbindex b8f3437efb6..328a7e1767a 100644--- a/script/require_profiler.rb+++ b/script/require_profiler.rb@@ -127,11 +127,9 @@ endRequireProfiler.profile doBundler.definition.dependencies.each do |dep|- begin- require dep.name- rescue Exception- # don't care- end+ require dep.name+ rescue Exception+ # don't careendenddiff --git a/script/test_mem.rb b/script/test_mem.rbindex 284e99993f3..b8f42dc7ee5 100644--- a/script/test_mem.rb+++ b/script/test_mem.rb@@ -9,11 +9,9 @@ I18n.t(:posts)# load up all models and schema(ActiveRecord::Base.connection.tables - %w[schema_migrations]).each do |table|- begin- table.classify.constantize.first- rescue StandardError- nil- end+ table.classify.constantize.first+rescue StandardError+ nilend# router warm updiff --git a/spec/jobs/about_stats_spec.rb b/spec/jobs/about_stats_spec.rbindex fa6ecaa0168..42ab437a88c 100644--- a/spec/jobs/about_stats_spec.rb+++ b/spec/jobs/about_stats_spec.rb@@ -2,15 +2,13 @@RSpec.describe Jobs::AboutStats doit "caches the stats" do- begin- stats = About.fetch_stats.to_json- cache_key = About.stats_cache_key- Discourse.redis.del(cache_key)+ stats = About.fetch_stats.to_json+ cache_key = About.stats_cache_key+ Discourse.redis.del(cache_key)- expect(described_class.new.execute({})).to eq(stats)- expect(Discourse.redis.get(cache_key)).to eq(stats)- ensure- Discourse.redis.del(cache_key)- end+ expect(described_class.new.execute({})).to eq(stats)+ expect(Discourse.redis.get(cache_key)).to eq(stats)+ ensure+ Discourse.redis.del(cache_key)endenddiff --git a/spec/jobs/bookmark_reminder_notifications_spec.rb b/spec/jobs/bookmark_reminder_notifications_spec.rbindex 655c44e8628..6f50fb51bf0 100644--- a/spec/jobs/bookmark_reminder_notifications_spec.rb+++ b/spec/jobs/bookmark_reminder_notifications_spec.rb@@ -50,13 +50,11 @@ RSpec.describe Jobs::BookmarkReminderNotifications docontext "when the number of notifications exceed max_reminder_notifications_per_run" doit "does not send them in the current run, but will send them in the next" do- begin- Jobs::BookmarkReminderNotifications.max_reminder_notifications_per_run = 2- job.execute- expect(bookmark1.reload.reminder_last_sent_at).not_to eq(nil)- expect(bookmark2.reload.reminder_last_sent_at).not_to eq(nil)- expect(bookmark3.reload.reminder_last_sent_at).to eq(nil)- end+ Jobs::BookmarkReminderNotifications.max_reminder_notifications_per_run = 2+ job.execute+ expect(bookmark1.reload.reminder_last_sent_at).not_to eq(nil)+ expect(bookmark2.reload.reminder_last_sent_at).not_to eq(nil)+ expect(bookmark3.reload.reminder_last_sent_at).to eq(nil)endenddiff --git a/spec/jobs/clean_up_uploads_spec.rb b/spec/jobs/clean_up_uploads_spec.rbindex 3606df58d2d..834964265c1 100644--- a/spec/jobs/clean_up_uploads_spec.rb+++ b/spec/jobs/clean_up_uploads_spec.rb@@ -106,57 +106,55 @@ RSpec.describe Jobs::CleanUpUploads doendit "does not clean up upload site settings" do- begin- original_provider = SiteSetting.provider- SiteSetting.provider = SiteSettings::DbProvider.new(SiteSetting)- SiteSetting.clean_orphan_uploads_grace_period_hours = 1-- system_upload = fabricate_upload(id: -999)- logo_upload = fabricate_upload- logo_small_upload = fabricate_upload- digest_logo_upload = fabricate_upload- mobile_logo_upload = fabricate_upload- large_icon_upload = fabricate_upload- opengraph_image_upload = fabricate_upload- x_summary_large_image_upload = fabricate_upload- favicon_upload = fabricate_upload- apple_touch_icon_upload = fabricate_upload-- SiteSetting.logo = logo_upload- SiteSetting.logo_small = logo_small_upload- SiteSetting.digest_logo = digest_logo_upload- SiteSetting.mobile_logo = mobile_logo_upload- SiteSetting.large_icon = large_icon_upload- SiteSetting.opengraph_image = opengraph_image_upload-- SiteSetting.x_summary_large_image = x_summary_large_image_upload-- SiteSetting.favicon = favicon_upload- SiteSetting.apple_touch_icon = apple_touch_icon_upload-- Jobs::CleanUpUploads.new.execute(nil)-- [- logo_upload,- logo_small_upload,- digest_logo_upload,- mobile_logo_upload,- large_icon_upload,- opengraph_image_upload,- x_summary_large_image_upload,- favicon_upload,- apple_touch_icon_upload,- system_upload,- ].each { |record| expect(Upload.exists?(id: record.id)).to eq(true) }-- fabricate_upload- SiteSetting.opengraph_image = ""-- Jobs::CleanUpUploads.new.execute(nil)- ensure- SiteSetting.delete_all- SiteSetting.provider = original_provider- end+ original_provider = SiteSetting.provider+ SiteSetting.provider = SiteSettings::DbProvider.new(SiteSetting)+ SiteSetting.clean_orphan_uploads_grace_period_hours = 1++ system_upload = fabricate_upload(id: -999)+ logo_upload = fabricate_upload+ logo_small_upload = fabricate_upload+ digest_logo_upload = fabricate_upload+ mobile_logo_upload = fabricate_upload+ large_icon_upload = fabricate_upload+ opengraph_image_upload = fabricate_upload+ x_summary_large_image_upload = fabricate_upload+ favicon_upload = fabricate_upload+ apple_touch_icon_upload = fabricate_upload++ SiteSetting.logo = logo_upload+ SiteSetting.logo_small = logo_small_upload+ SiteSetting.digest_logo = digest_logo_upload+ SiteSetting.mobile_logo = mobile_logo_upload+ SiteSetting.large_icon = large_icon_upload+ SiteSetting.opengraph_image = opengraph_image_upload++ SiteSetting.x_summary_large_image = x_summary_large_image_upload++ SiteSetting.favicon = favicon_upload+ SiteSetting.apple_touch_icon = apple_touch_icon_upload++ Jobs::CleanUpUploads.new.execute(nil)++ [+ logo_upload,+ logo_small_upload,+ digest_logo_upload,+ mobile_logo_upload,+ large_icon_upload,+ opengraph_image_upload,+ x_summary_large_image_upload,+ favicon_upload,+ apple_touch_icon_upload,+ system_upload,+ ].each { |record| expect(Upload.exists?(id: record.id)).to eq(true) }++ fabricate_upload+ SiteSetting.opengraph_image = ""++ Jobs::CleanUpUploads.new.execute(nil)+ ensure+ SiteSetting.delete_all+ SiteSetting.provider = original_providerendit "does not clean up selectable avatars" dodiff --git a/spec/lib/discourse_event_spec.rb b/spec/lib/discourse_event_spec.rbindex b476011a535..9c55dc1b33a 100644--- a/spec/lib/discourse_event_spec.rb+++ b/spec/lib/discourse_event_spec.rb@@ -3,13 +3,11 @@RSpec.describe DiscourseEvent dodescribe "#events" doit "defaults to {}" do- begin- original_events = DiscourseEvent.events- DiscourseEvent.instance_variable_set(:@events, nil)- expect(DiscourseEvent.events).to eq({})- ensure- DiscourseEvent.instance_variable_set(:@events, original_events)- end+ original_events = DiscourseEvent.events+ DiscourseEvent.instance_variable_set(:@events, nil)+ expect(DiscourseEvent.events).to eq({})+ ensure+ DiscourseEvent.instance_variable_set(:@events, original_events)enddescribe "key value" do@@ -99,17 +97,15 @@ RSpec.describe DiscourseEvent doendit "allows using kwargs" do- begin- handler =- Proc.new do |name:, message:|- expect(name).to eq("Supervillain")- expect(message).to eq("Two Face")- end-- DiscourseEvent.on(:acid_face, &handler)- DiscourseEvent.trigger(:acid_face, name: "Supervillain", message: "Two Face")- ensure- DiscourseEvent.off(:acid_face, &handler)- end+ handler =+ Proc.new do |name:, message:|+ expect(name).to eq("Supervillain")+ expect(message).to eq("Two Face")+ end++ DiscourseEvent.on(:acid_face, &handler)+ DiscourseEvent.trigger(:acid_face, name: "Supervillain", message: "Two Face")+ ensure+ DiscourseEvent.off(:acid_face, &handler)endenddiff --git a/spec/lib/distributed_mutex_spec.rb b/spec/lib/distributed_mutex_spec.rbindex f75a0b75f17..b1ba62cf505 100644--- a/spec/lib/distributed_mutex_spec.rb+++ b/spec/lib/distributed_mutex_spec.rb@@ -93,22 +93,20 @@ RSpec.describe DistributedMutex do3.times do |i|execution.spawn do- begin- redis = Concurrency::RedisWrapper.new(connections[i], execution)+ redis = Concurrency::RedisWrapper.new(connections[i], execution)- 2.times do- DistributedMutex.synchronize("mutex_key", redis: redis) do- raise "already locked #{execution.path}" if locked- locked = true+ 2.times do+ DistributedMutex.synchronize("mutex_key", redis: redis) do+ raise "already locked #{execution.path}" if locked+ locked = true- execution.yield+ execution.yield- raise "already unlocked #{execution.path}" unless locked- locked = false- end+ raise "already unlocked #{execution.path}" unless locked+ locked = falseend- rescue Redis::ConnectionErrorend+ rescue Redis::ConnectionErrorendendenddiff --git a/spec/lib/file_helper_spec.rb b/spec/lib/file_helper_spec.rbindex 7957521ac4a..e5b74e125e4 100644--- a/spec/lib/file_helper_spec.rb+++ b/spec/lib/file_helper_spec.rb@@ -17,17 +17,15 @@ RSpec.describe FileHelper dostub_request(:get, url).to_return(status: 404, body: "404")expect do- begin- FileHelper.download(- url,- max_file_size: 10_000,- tmp_file_name: "trouttmp",- follow_redirect: true,- )- rescue => e- expect(e.io.status[0]).to eq("404")- raise- end+ FileHelper.download(+ url,+ max_file_size: 10_000,+ tmp_file_name: "trouttmp",+ follow_redirect: true,+ )+ rescue => e+ expect(e.io.status[0]).to eq("404")+ raiseend.to raise_error(OpenURI::HTTPError, "404 Error")end@@ -73,45 +71,39 @@ RSpec.describe FileHelper dostub_request(:get, url).to_return(status: 404, body: "404")expect do- begin- FileHelper.download(- url,- max_file_size: 10_000,- tmp_file_name: "trouttmp",- follow_redirect: false,- )- rescue => e- expect(e.io.status[0]).to eq("404")- raise- end+ FileHelper.download(+ url,+ max_file_size: 10_000,+ tmp_file_name: "trouttmp",+ follow_redirect: false,+ )+ rescue => e+ expect(e.io.status[0]).to eq("404")+ raiseend.to raise_error(OpenURI::HTTPError)endit "returns a file with the image" do- begin- tmpfile = FileHelper.download(url, max_file_size: 10_000, tmp_file_name: "trouttmp")+ tmpfile = FileHelper.download(url, max_file_size: 10_000, tmp_file_name: "trouttmp")- expect(Base64.encode64(tmpfile.read)).to eq(Base64.encode64(png))- ensure- tmpfile&.close- tmpfile&.unlink- end+ expect(Base64.encode64(tmpfile.read)).to eq(Base64.encode64(png))+ ensure+ tmpfile&.close+ tmpfile&.unlinkendit "works with a protocol relative url" do- begin- tmpfile =- FileHelper.download(- "//eviltrout.com/trout.png",- max_file_size: 10_000,- tmp_file_name: "trouttmp",- )+ tmpfile =+ FileHelper.download(+ "//eviltrout.com/trout.png",+ max_file_size: 10_000,+ tmp_file_name: "trouttmp",+ )- expect(Base64.encode64(tmpfile.read)).to eq(Base64.encode64(png))- ensure- tmpfile&.close- tmpfile&.unlink- end+ expect(Base64.encode64(tmpfile.read)).to eq(Base64.encode64(png))+ ensure+ tmpfile&.close+ tmpfile&.unlinkenddescribe "when max_file_size is exceeded" do@@ -127,20 +119,18 @@ RSpec.describe FileHelper doendit "is able to retain the tmpfile" do- begin- tmpfile =- FileHelper.download(- "//eviltrout.com/trout.png",- max_file_size: 1,- tmp_file_name: "trouttmp",- retain_on_max_file_size_exceeded: true,- )-- expect(tmpfile.closed?).to eq(false)- ensure- tmpfile&.close- tmpfile&.unlink- end+ tmpfile =+ FileHelper.download(+ "//eviltrout.com/trout.png",+ max_file_size: 1,+ tmp_file_name: "trouttmp",+ retain_on_max_file_size_exceeded: true,+ )++ expect(tmpfile.closed?).to eq(false)+ ensure+ tmpfile&.close+ tmpfile&.unlinkendend@@ -148,16 +138,14 @@ RSpec.describe FileHelper dolet(:url) { "https://eviltrout.com/trout.jpg" }it "should prioritize the content type returned by the response" do- begin- stub_request(:get, url).to_return(body: png, headers: { "content-type": "image/png" })+ stub_request(:get, url).to_return(body: png, headers: { "content-type": "image/png" })- tmpfile = FileHelper.download(url, max_file_size: 10_000, tmp_file_name: "trouttmp")+ tmpfile = FileHelper.download(url, max_file_size: 10_000, tmp_file_name: "trouttmp")- expect(File.extname(tmpfile)).to eq(".png")- ensure- tmpfile&.close- tmpfile&.unlink- end+ expect(File.extname(tmpfile)).to eq(".png")+ ensure+ tmpfile&.close+ tmpfile&.unlinkendendenddiff --git a/spec/lib/file_store/local_store_spec.rb b/spec/lib/file_store/local_store_spec.rbindex 40e5a1b316e..0978ae61ff0 100644--- a/spec/lib/file_store/local_store_spec.rb+++ b/spec/lib/file_store/local_store_spec.rb@@ -36,48 +36,44 @@ RSpec.describe FileStore::LocalStore doendit "moves the file to the tombstone" do- begin- upload =- UploadCreator.new(file_from_fixtures("smallest.png"), "smallest.png").create_for(- Fabricate(:user).id,- )+ upload =+ UploadCreator.new(file_from_fixtures("smallest.png"), "smallest.png").create_for(+ Fabricate(:user).id,+ )- path = store.path_for(upload)- mtime = File.mtime(path)+ path = store.path_for(upload)+ mtime = File.mtime(path)- sleep 0.01 # Delay a little for mtime to be updated- store.remove_upload(upload)- tombstone_path = path.sub("/uploads/", "/uploads/tombstone/")+ sleep 0.01 # Delay a little for mtime to be updated+ store.remove_upload(upload)+ tombstone_path = path.sub("/uploads/", "/uploads/tombstone/")- expect(File.exist?(tombstone_path)).to eq(true)- expect(File.mtime(tombstone_path)).to_not eq(mtime)- ensure- [path, tombstone_path].each { |file_path| File.delete(file_path) if File.exist?(file_path) }- end+ expect(File.exist?(tombstone_path)).to eq(true)+ expect(File.mtime(tombstone_path)).to_not eq(mtime)+ ensure+ [path, tombstone_path].each { |file_path| File.delete(file_path) if File.exist?(file_path) }endenddescribe "#remove_optimized_image" doit "moves the file to the tombstone" do- begin- upload =- UploadCreator.new(file_from_fixtures("smallest.png"), "smallest.png").create_for(- Fabricate(:user).id,- )+ upload =+ UploadCreator.new(file_from_fixtures("smallest.png"), "smallest.png").create_for(+ Fabricate(:user).id,+ )- upload.create_thumbnail!(1, 1)- upload.reload+ upload.create_thumbnail!(1, 1)+ upload.reload- optimized_image = upload.thumbnail(1, 1)- path = store.path_for(optimized_image)+ optimized_image = upload.thumbnail(1, 1)+ path = store.path_for(optimized_image)- store.remove_optimized_image(optimized_image)- tombstone_path = path.sub("/uploads/", "/uploads/tombstone/")+ store.remove_optimized_image(optimized_image)+ tombstone_path = path.sub("/uploads/", "/uploads/tombstone/")- expect(File.exist?(tombstone_path)).to eq(true)- ensure- [path, tombstone_path].each { |file_path| File.delete(file_path) if File.exist?(file_path) }- end+ expect(File.exist?(tombstone_path)).to eq(true)+ ensure+ [path, tombstone_path].each { |file_path| File.delete(file_path) if File.exist?(file_path) }endenddiff --git a/spec/lib/guardian_spec.rb b/spec/lib/guardian_spec.rbindex c4299edc742..343ba1ab098 100644--- a/spec/lib/guardian_spec.rb+++ b/spec/lib/guardian_spec.rb@@ -1869,12 +1869,10 @@ RSpec.describe Guardian doendit "should not allow an admin to grant admin access to a non real user" do- begin- Discourse.system_user.update!(admin: false)- expect(Guardian.new(admin).can_grant_admin?(Discourse.system_user)).to be(false)- ensure- Discourse.system_user.update!(admin: true)- end+ Discourse.system_user.update!(admin: false)+ expect(Guardian.new(admin).can_grant_admin?(Discourse.system_user)).to be(false)+ ensure+ Discourse.system_user.update!(admin: true)endend@@ -1925,12 +1923,10 @@ RSpec.describe Guardian doendit "should not allow an admin to grant moderation to a non real user" do- begin- Discourse.system_user.update!(moderator: false)- expect(Guardian.new(admin).can_grant_moderation?(Discourse.system_user)).to be(false)- ensure- Discourse.system_user.update!(moderator: true)- end+ Discourse.system_user.update!(moderator: false)+ expect(Guardian.new(admin).can_grant_moderation?(Discourse.system_user)).to be(false)+ ensure+ Discourse.system_user.update!(moderator: true)endenddiff --git a/spec/lib/migration/column_dropper_spec.rb b/spec/lib/migration/column_dropper_spec.rbindex eef390e073b..f14e21b34d3 100644--- a/spec/lib/migration/column_dropper_spec.rb+++ b/spec/lib/migration/column_dropper_spec.rb@@ -89,18 +89,16 @@ RSpec.describe Migration::ColumnDropper doendit "should prevent updates to the readonly column" do- begin- DB.exec <<~SQL+ DB.exec <<~SQLUPDATE #{table_name}SET email = '[email protected]'WHERE topic_id = 1;SQL- rescue PG::RaiseException => e- [- "Discourse: email in #{table_name} is readonly",- "discourse_functions.raise_table_with_readonly_column_email_readonly()",- ].each { |message| expect(e.message).to include(message) }- end+ rescue PG::RaiseException => e+ [+ "Discourse: email in #{table_name} is readonly",+ "discourse_functions.raise_table_with_readonly_column_email_readonly()",+ ].each { |message| expect(e.message).to include(message) }endit "should allow updates to the other columns" dodiff --git a/spec/lib/migration/safe_migrate_spec.rb b/spec/lib/migration/safe_migrate_spec.rbindex 0b61efceafc..c576be31151 100644--- a/spec/lib/migration/safe_migrate_spec.rb+++ b/spec/lib/migration/safe_migrate_spec.rb@@ -80,11 +80,9 @@ RSpec.describe Migration::SafeMigrate doerror = nilcapture_stdout do- begin- migrate_up(path)- rescue StandardError => e- error = e- end+ migrate_up(path)+ rescue StandardError => e+ error = eendexpect(error.cause.cause.message).to include(@@ -99,11 +97,9 @@ RSpec.describe Migration::SafeMigrate doerror = nilcapture_stdout do- begin- migrate_up(path)- rescue StandardError => e- error = e- end+ migrate_up(path)+ rescue StandardError => e+ error = eendexpect(error.cause.cause.message).to include(diff --git a/spec/lib/migration/table_dropper_spec.rb b/spec/lib/migration/table_dropper_spec.rbindex 6b15603c1c4..add89c3c153 100644--- a/spec/lib/migration/table_dropper_spec.rb+++ b/spec/lib/migration/table_dropper_spec.rb@@ -68,16 +68,14 @@ RSpec.describe Migration::TableDropper doendit "should prevent insertions to the table" do- begin- DB.exec <<~SQL+ DB.exec <<~SQLINSERT INTO #{table_name} (topic_id) VALUES (2)SQL- rescue PG::RaiseException => e- [- "Discourse: #{table_name} is read only",- "discourse_functions.raise_table_with_old_name_readonly()",- ].each { |message| expect(e.message).to include(message) }- end+ rescue PG::RaiseException => e+ [+ "Discourse: #{table_name} is read only",+ "discourse_functions.raise_table_with_old_name_readonly()",+ ].each { |message| expect(e.message).to include(message) }endendenddiff --git a/spec/lib/post_destroyer_spec.rb b/spec/lib/post_destroyer_spec.rbindex 3fcd3c7229a..fabe31a8d3e 100644--- a/spec/lib/post_destroyer_spec.rb+++ b/spec/lib/post_destroyer_spec.rb@@ -420,55 +420,53 @@ RSpec.describe PostDestroyer dodescribe "basic destroying" doit "as the creator of the post, doesn't delete the post" do- begin- post2 = create_post- user_stat = post2.user.user_stat-- called = 0- topic_destroyed = ->(topic, user) do- expect(topic).to eq(post2.topic)- expect(user).to eq(post2.user)- called += 1- end-- DiscourseEvent.on(:topic_destroyed, &topic_destroyed)-- @orig = post2.cooked- # Guardian.new(post2.user).can_delete_post?(post2) == false- PostDestroyer.new(post2.user, post2).destroy- post2.reload-- expect(post2.deleted_at).to be_blank- expect(post2.deleted_by).to be_blank- expect(post2.user_deleted).to eq(true)- expect(post2.raw).to eq(I18n.t("js.topic.deleted_by_author_simple"))- expect(post2.version).to eq(2)- expect(called).to eq(1)- expect(user_stat.reload.post_count).to eq(0)- expect(user_stat.reload.topic_count).to eq(1)+ post2 = create_post+ user_stat = post2.user.user_stat- called = 0- topic_recovered = ->(topic, user) do- expect(topic).to eq(post2.topic)- expect(user).to eq(post2.user)- called += 1- end+ called = 0+ topic_destroyed = ->(topic, user) do+ expect(topic).to eq(post2.topic)+ expect(user).to eq(post2.user)+ called += 1+ end- DiscourseEvent.on(:topic_recovered, &topic_recovered)+ DiscourseEvent.on(:topic_destroyed, &topic_destroyed)- # lets try to recover- PostDestroyer.new(post2.user, post2).recover- post2.reload- expect(post2.version).to eq(3)- expect(post2.user_deleted).to eq(false)- expect(post2.cooked).to eq(@orig)- expect(called).to eq(1)- expect(user_stat.reload.post_count).to eq(0)- expect(user_stat.reload.topic_count).to eq(1)- ensure- DiscourseEvent.off(:topic_destroyed, &topic_destroyed)- DiscourseEvent.off(:topic_recovered, &topic_recovered)+ @orig = post2.cooked+ # Guardian.new(post2.user).can_delete_post?(post2) == false+ PostDestroyer.new(post2.user, post2).destroy+ post2.reload++ expect(post2.deleted_at).to be_blank+ expect(post2.deleted_by).to be_blank+ expect(post2.user_deleted).to eq(true)+ expect(post2.raw).to eq(I18n.t("js.topic.deleted_by_author_simple"))+ expect(post2.version).to eq(2)+ expect(called).to eq(1)+ expect(user_stat.reload.post_count).to eq(0)+ expect(user_stat.reload.topic_count).to eq(1)++ called = 0+ topic_recovered = ->(topic, user) do+ expect(topic).to eq(post2.topic)+ expect(user).to eq(post2.user)+ called += 1end++ DiscourseEvent.on(:topic_recovered, &topic_recovered)++ # lets try to recover+ PostDestroyer.new(post2.user, post2).recover+ post2.reload+ expect(post2.version).to eq(3)+ expect(post2.user_deleted).to eq(false)+ expect(post2.cooked).to eq(@orig)+ expect(called).to eq(1)+ expect(user_stat.reload.post_count).to eq(0)+ expect(user_stat.reload.topic_count).to eq(1)+ ensure+ DiscourseEvent.off(:topic_destroyed, &topic_destroyed)+ DiscourseEvent.off(:topic_recovered, &topic_recovered)endit "maintains history when a user destroys a hidden post" dodiff --git a/spec/lib/pretty_text_spec.rb b/spec/lib/pretty_text_spec.rbindex f410a7d50bc..44a95670406 100644--- a/spec/lib/pretty_text_spec.rb+++ b/spec/lib/pretty_text_spec.rb@@ -704,14 +704,12 @@ RSpec.describe PrettyText doendit "does censor code fences" do- begin- %w[apple banana].each do |w|- Fabricate(:watched_word, word: w, action: WatchedWord.actions[:censor])- end- expect(PrettyText.cook("# banana")).not_to include("banana")- ensure- Discourse.redis.flushdb+ %w[apple banana].each do |w|+ Fabricate(:watched_word, word: w, action: WatchedWord.actions[:censor])end+ expect(PrettyText.cook("# banana")).not_to include("banana")+ ensure+ Discourse.redis.flushdbendit "strips out unicode bidirectional (bidi) override characters and replaces with a highlighted span" dodiff --git a/spec/lib/search_spec.rb b/spec/lib/search_spec.rbindex 6191893f50e..f55a99f04f6 100644--- a/spec/lib/search_spec.rb+++ b/spec/lib/search_spec.rb@@ -2130,25 +2130,23 @@ RSpec.describe Search doendit "finds chinese topic based on title if tokenization is forced" do- begin- SiteSetting.search_tokenize_chinese = true- default_min_search_term_length = SiteSetting.defaults.get(:min_search_term_length)- SiteSetting.defaults.set_regardless_of_locale(:min_search_term_length, 1)- SiteSetting.refresh!+ SiteSetting.search_tokenize_chinese = true+ default_min_search_term_length = SiteSetting.defaults.get(:min_search_term_length)+ SiteSetting.defaults.set_regardless_of_locale(:min_search_term_length, 1)+ SiteSetting.refresh!- topic = Fabricate(:topic, title: "My Title Discourse社區指南")- post = Fabricate(:post, topic: topic)+ topic = Fabricate(:topic, title: "My Title Discourse社區指南")+ post = Fabricate(:post, topic: topic)- expect(Search.execute("社區指南").posts.first.id).to eq(post.id)- expect(Search.execute("指南").posts.first.id).to eq(post.id)- ensure- if default_min_search_term_length- SiteSetting.defaults.set_regardless_of_locale(- :min_search_term_length,- default_min_search_term_length,- )- SiteSetting.refresh!- end+ expect(Search.execute("社區指南").posts.first.id).to eq(post.id)+ expect(Search.execute("指南").posts.first.id).to eq(post.id)+ ensure+ if default_min_search_term_length+ SiteSetting.defaults.set_regardless_of_locale(+ :min_search_term_length,+ default_min_search_term_length,+ )+ SiteSetting.refresh!endendenddiff --git a/spec/lib/upload_creator_spec.rb b/spec/lib/upload_creator_spec.rbindex 259a9452669..d4b8dccf8cc 100644--- a/spec/lib/upload_creator_spec.rb+++ b/spec/lib/upload_creator_spec.rb@@ -647,16 +647,14 @@ RSpec.describe UploadCreator doendit "removes event handlers" do- begin- UploadCreator.new(file, "file.svg").clean_svg!- file_content = file.read- expect(file_content).not_to include("onload")- expect(file_content).to include("#pathdef")- expect(file_content).not_to include("evil.svg")- expect(file_content).not_to include(b64)- ensure- file.unlink- end+ UploadCreator.new(file, "file.svg").clean_svg!+ file_content = file.read+ expect(file_content).not_to include("onload")+ expect(file_content).to include("#pathdef")+ expect(file_content).not_to include("evil.svg")+ expect(file_content).not_to include(b64)+ ensure+ file.unlinkendenddiff --git a/spec/lib/url_helper_spec.rb b/spec/lib/url_helper_spec.rbindex c4b5fdadd12..2d29593db6d 100644--- a/spec/lib/url_helper_spec.rb+++ b/spec/lib/url_helper_spec.rb@@ -42,18 +42,16 @@ RSpec.describe UrlHelper dodescribe "#absolute" doit "returns an absolute URL for CDN" do- begin- Rails.configuration.action_controller.asset_host = "//cdn.awesome.com"- expect(UrlHelper.absolute("/test.jpg")).to eq("https://cdn.awesome.com/test.jpg")+ Rails.configuration.action_controller.asset_host = "//cdn.awesome.com"+ expect(UrlHelper.absolute("/test.jpg")).to eq("https://cdn.awesome.com/test.jpg")- Rails.configuration.action_controller.asset_host = "https://cdn.awesome.com"- expect(UrlHelper.absolute("/test.jpg")).to eq("https://cdn.awesome.com/test.jpg")+ Rails.configuration.action_controller.asset_host = "https://cdn.awesome.com"+ expect(UrlHelper.absolute("/test.jpg")).to eq("https://cdn.awesome.com/test.jpg")- Rails.configuration.action_controller.asset_host = "http://cdn.awesome.com"- expect(UrlHelper.absolute("/test.jpg")).to eq("http://cdn.awesome.com/test.jpg")- ensure- Rails.configuration.action_controller.asset_host = nil- end+ Rails.configuration.action_controller.asset_host = "http://cdn.awesome.com"+ expect(UrlHelper.absolute("/test.jpg")).to eq("http://cdn.awesome.com/test.jpg")+ ensure+ Rails.configuration.action_controller.asset_host = nilendit "does not change non-relative url" dodiff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rbindex e23bd4fbd84..df97287108a 100644--- a/spec/models/group_spec.rb+++ b/spec/models/group_spec.rb@@ -447,33 +447,29 @@ RSpec.describe Group doendit "does not reset the localized name" do- begin- I18n.locale = SiteSetting.default_locale = "fi"+ I18n.locale = SiteSetting.default_locale = "fi"- group = Group.find(Group::AUTO_GROUPS[:everyone])- group.update!(name: I18n.t("groups.default_names.everyone"))+ group = Group.find(Group::AUTO_GROUPS[:everyone])+ group.update!(name: I18n.t("groups.default_names.everyone"))- Group.refresh_automatic_group!(:everyone)+ Group.refresh_automatic_group!(:everyone)- expect(group.reload.name).to eq(I18n.t("groups.default_names.everyone"))+ expect(group.reload.name).to eq(I18n.t("groups.default_names.everyone"))- I18n.locale = SiteSetting.default_locale = "en"+ I18n.locale = SiteSetting.default_locale = "en"- Group.refresh_automatic_group!(:everyone)+ Group.refresh_automatic_group!(:everyone)- expect(group.reload.name).to eq(I18n.t("groups.default_names.everyone"))- end+ expect(group.reload.name).to eq(I18n.t("groups.default_names.everyone"))endit "uses the localized name if name has not been taken" do- begin- I18n.locale = SiteSetting.default_locale = "de"+ I18n.locale = SiteSetting.default_locale = "de"- group = Group.refresh_automatic_group!(:staff)+ group = Group.refresh_automatic_group!(:staff)- expect(group.name).to_not eq("staff")- expect(group.name).to eq(I18n.t("groups.default_names.staff"))- end+ expect(group.name).to_not eq("staff")+ expect(group.name).to eq(I18n.t("groups.default_names.staff"))endit "does not use the localized name if name has already been taken when switching to a the english locale" dodiff --git a/spec/models/post_mover_spec.rb b/spec/models/post_mover_spec.rbindex a57887de033..be6fe40516f 100644--- a/spec/models/post_mover_spec.rb+++ b/spec/models/post_mover_spec.rb@@ -3354,65 +3354,57 @@ RSpec.describe PostMover doendit "does not rate limit when moving to a new topic" do- begin- PostMover.new(- original_topic,- Discourse.system_user,- original_topic.posts.map(&:id),- options: {- freeze_original: true,- },- ).to_new_topic("Hi I'm a new topic, with a copy of the old posts")- rescue RateLimiter::LimitExceeded- fail "Rate limit exceeded"- end+ PostMover.new(+ original_topic,+ Discourse.system_user,+ original_topic.posts.map(&:id),+ options: {+ freeze_original: true,+ },+ ).to_new_topic("Hi I'm a new topic, with a copy of the old posts")+ rescue RateLimiter::LimitExceeded+ fail "Rate limit exceeded"endit "does not rate limit when moving to an existing topic" do- begin- PostMover.new(- original_topic,- Discourse.system_user,- original_topic.posts.map(&:id),- options: {- freeze_original: true,- },- ).to_topic(destination_topic.id)- rescue RateLimiter::LimitExceeded- fail "Rate limit exceeded"- end+ PostMover.new(+ original_topic,+ Discourse.system_user,+ original_topic.posts.map(&:id),+ options: {+ freeze_original: true,+ },+ ).to_topic(destination_topic.id)+ rescue RateLimiter::LimitExceeded+ fail "Rate limit exceeded"endit "does not rate limit when moving to a new PM" do- begin- PostMover.new(- original_topic,- Discourse.system_user,- original_topic.posts.map(&:id),- move_to_pm: true,- options: {- freeze_original: true,- },- ).to_new_topic("Hi I'm a new PM, with a copy of the old posts")- rescue RateLimiter::LimitExceeded- fail "Rate limit exceeded"- end+ PostMover.new(+ original_topic,+ Discourse.system_user,+ original_topic.posts.map(&:id),+ move_to_pm: true,+ options: {+ freeze_original: true,+ },+ ).to_new_topic("Hi I'm a new PM, with a copy of the old posts")+ rescue RateLimiter::LimitExceeded+ fail "Rate limit exceeded"endit "does not rate limit when moving to an existing PM" do- begin- PostMover.new(- original_topic,- Discourse.system_user,- original_topic.posts.map(&:id),- move_to_pm: true,- options: {- freeze_original: true,- },- ).to_topic(destination_topic.id)- rescue RateLimiter::LimitExceeded- fail "Rate limit exceeded"- end+ PostMover.new(+ original_topic,+ Discourse.system_user,+ original_topic.posts.map(&:id),+ move_to_pm: true,+ options: {+ freeze_original: true,+ },+ ).to_topic(destination_topic.id)+ rescue RateLimiter::LimitExceeded+ fail "Rate limit exceeded"endendenddiff --git a/spec/models/topic_user_spec.rb b/spec/models/topic_user_spec.rbindex c69901be854..5950d2fda81 100644--- a/spec/models/topic_user_spec.rb+++ b/spec/models/topic_user_spec.rb@@ -571,31 +571,29 @@ RSpec.describe TopicUser doendit "correctly triggers an event on first visit" do- begin- tracked_user = Fabricate(:user)- post = create_post-- called = 0- visits = []- user_first_visit = ->(topic_id, user_id) do- visits << "#{topic_id}-#{user_id}"- called += 1- end+ tracked_user = Fabricate(:user)+ post = create_post++ called = 0+ visits = []+ user_first_visit = ->(topic_id, user_id) do+ visits << "#{topic_id}-#{user_id}"+ called += 1+ end- DiscourseEvent.on(:topic_first_visited_by_user, &user_first_visit)+ DiscourseEvent.on(:topic_first_visited_by_user, &user_first_visit)- expect(called).to eq(0)+ expect(called).to eq(0)- TopicUser.change(tracked_user, post.topic.id, total_msecs_viewed: 1)+ TopicUser.change(tracked_user, post.topic.id, total_msecs_viewed: 1)- expect(visits).to eq(["#{post.topic.id}-#{tracked_user.id}"])- expect(called).to eq(1)+ expect(visits).to eq(["#{post.topic.id}-#{tracked_user.id}"])+ expect(called).to eq(1)- TopicUser.change(tracked_user, post.topic.id, total_msecs_viewed: 2)+ TopicUser.change(tracked_user, post.topic.id, total_msecs_viewed: 2)- expect(called).to eq(1)- ensure- DiscourseEvent.off(:topic_first_visited_by_user, &user_first_visit)- end+ expect(called).to eq(1)+ ensure+ DiscourseEvent.off(:topic_first_visited_by_user, &user_first_visit)endenddiff --git a/spec/models/upload_spec.rb b/spec/models/upload_spec.rbindex e0f65414cc6..80d45fd8c6e 100644--- a/spec/models/upload_spec.rb+++ b/spec/models/upload_spec.rb@@ -333,14 +333,12 @@ RSpec.describe Upload doendit "works when using a cdn" do- begin- original_asset_host = Rails.configuration.action_controller.asset_host- Rails.configuration.action_controller.asset_host = "http://my.cdn.com"+ original_asset_host = Rails.configuration.action_controller.asset_host+ Rails.configuration.action_controller.asset_host = "http://my.cdn.com"- expect(Upload.get_from_url(URI.join("http://my.cdn.com", upload.url).to_s)).to eq(upload)- ensure- Rails.configuration.action_controller.asset_host = original_asset_host- end+ expect(Upload.get_from_url(URI.join("http://my.cdn.com", upload.url).to_s)).to eq(upload)+ ensure+ Rails.configuration.action_controller.asset_host = original_asset_hostendit "should return the right upload when using the full URL" do@@ -393,17 +391,15 @@ RSpec.describe Upload doendit "should return the right upload when using one CDN for both s3 and assets" do- begin- original_asset_host = Rails.configuration.action_controller.asset_host- cdn_url = "http://my.cdn.com"- Rails.configuration.action_controller.asset_host = cdn_url- SiteSetting.s3_cdn_url = cdn_url- upload+ original_asset_host = Rails.configuration.action_controller.asset_host+ cdn_url = "http://my.cdn.com"+ Rails.configuration.action_controller.asset_host = cdn_url+ SiteSetting.s3_cdn_url = cdn_url+ upload- expect(Upload.get_from_url(URI.join(cdn_url, path).to_s)).to eq(upload)- ensure- Rails.configuration.action_controller.asset_host = original_asset_host- end+ expect(Upload.get_from_url(URI.join(cdn_url, path).to_s)).to eq(upload)+ ensure+ Rails.configuration.action_controller.asset_host = original_asset_hostendendend@@ -436,16 +432,14 @@ RSpec.describe Upload doendit "works when using a CDN" do- begin- original_asset_host = Rails.configuration.action_controller.asset_host- Rails.configuration.action_controller.asset_host = "http://my.cdn.com"+ original_asset_host = Rails.configuration.action_controller.asset_host+ Rails.configuration.action_controller.asset_host = "http://my.cdn.com"- expect(- Upload.get_from_urls([URI.join("http://my.cdn.com", upload.url).to_s]),- ).to contain_exactly(upload)- ensure- Rails.configuration.action_controller.asset_host = original_asset_host- end+ expect(+ Upload.get_from_urls([URI.join("http://my.cdn.com", upload.url).to_s]),+ ).to contain_exactly(upload)+ ensure+ Rails.configuration.action_controller.asset_host = original_asset_hostendit "works with full URLs" dodiff --git a/spec/rails_helper.rb b/spec/rails_helper.rbindex a06a69474d0..3ba9976837b 100644--- a/spec/rails_helper.rb+++ b/spec/rails_helper.rb@@ -45,16 +45,14 @@ class RspecErrorTrackerenddef call(env)- begin- @app.call(env)-- # This is a little repetitive, but since WebMock::NetConnectNotAllowedError- # and also Mocha::ExpectationError inherit from Exception instead of StandardError- # they do not get captured by the rescue => e shorthand :(- rescue WebMock::NetConnectNotAllowedError, Mocha::ExpectationError, StandardError => e- RspecErrorTracker.report_exception(env["PATH_INFO"], e)- raise e- end+ @app.call(env)++ # This is a little repetitive, but since WebMock::NetConnectNotAllowedError+ # and also Mocha::ExpectationError inherit from Exception instead of StandardError+ # they do not get captured by the rescue => e shorthand :(+ rescue WebMock::NetConnectNotAllowedError, Mocha::ExpectationError, StandardError => e+ RspecErrorTracker.report_exception(env["PATH_INFO"], e)+ raise eendenddiff --git a/spec/requests/admin/backups_controller_spec.rb b/spec/requests/admin/backups_controller_spec.rbindex ea8f1365c66..219e1912f4a 100644--- a/spec/requests/admin/backups_controller_spec.rb+++ b/spec/requests/admin/backups_controller_spec.rb@@ -64,16 +64,14 @@ RSpec.describe Admin::BackupsController docontext "with json format" doit "returns a list of all the backups" do- begin- create_backup_files(backup_filename, backup_filename2)+ create_backup_files(backup_filename, backup_filename2)- get "/admin/backups.json"- expect(response.status).to eq(200)+ get "/admin/backups.json"+ expect(response.status).to eq(200)- filenames = response.parsed_body.map { |backup| backup["filename"] }- expect(filenames).to include(backup_filename)- expect(filenames).to include(backup_filename2)- end+ filenames = response.parsed_body.map { |backup| backup["filename"] }+ expect(filenames).to include(backup_filename)+ expect(filenames).to include(backup_filename2)endendend@@ -206,29 +204,25 @@ RSpec.describe Admin::BackupsController dobefore { sign_in(admin) }it "uses send_file to transmit the backup" do- begin- token = EmailBackupToken.set(admin.id)- create_backup_files(backup_filename)+ token = EmailBackupToken.set(admin.id)+ create_backup_files(backup_filename)- expect do- get "/admin/backups/#{backup_filename}.json", params: { token: token }- end.to change {- UserHistory.where(action: UserHistory.actions[:backup_download]).count- }.by(1)+ expect do+ get "/admin/backups/#{backup_filename}.json", params: { token: token }+ end.to change { UserHistory.where(action: UserHistory.actions[:backup_download]).count }.by(+ 1,+ )- expect(response.headers["Content-Length"]).to eq("11")- expect(response.headers["Content-Disposition"]).to match(/attachment; filename/)- end+ expect(response.headers["Content-Length"]).to eq("11")+ expect(response.headers["Content-Disposition"]).to match(/attachment; filename/)endit "returns 422 when token is bad" do- begin- get "/admin/backups/#{backup_filename}.json", params: { token: "bad_value" }+ get "/admin/backups/#{backup_filename}.json", params: { token: "bad_value" }- expect(response.status).to eq(422)- expect(response.headers["Content-Disposition"]).not_to match(/attachment; filename/)- expect(response.body).to include(I18n.t("download_backup_mailer.no_token"))- end+ expect(response.status).to eq(422)+ expect(response.headers["Content-Disposition"]).not_to match(/attachment; filename/)+ expect(response.body).to include(I18n.t("download_backup_mailer.no_token"))endit "returns 404 when the backup does not exist" do@@ -248,20 +242,16 @@ RSpec.describe Admin::BackupsController doshared_examples "backup inaccessible" doit "denies access with a 404 response" do- begin- token = EmailBackupToken.set(admin.id)- create_backup_files(backup_filename)+ token = EmailBackupToken.set(admin.id)+ create_backup_files(backup_filename)- expect do- get "/admin/backups/#{backup_filename}.json", params: { token: token }- end.not_to change {- UserHistory.where(action: UserHistory.actions[:backup_download]).count- }+ expect do+ get "/admin/backups/#{backup_filename}.json", params: { token: token }+ end.not_to change { UserHistory.where(action: UserHistory.actions[:backup_download]).count }- expect(response.status).to eq(404)- expect(response.parsed_body["errors"]).to include(I18n.t("not_found"))- expect(response.headers["Content-Disposition"]).not_to match(/attachment; filename/)- end+ expect(response.status).to eq(404)+ expect(response.parsed_body["errors"]).to include(I18n.t("not_found"))+ expect(response.headers["Content-Disposition"]).not_to match(/attachment; filename/)endend@@ -283,18 +273,16 @@ RSpec.describe Admin::BackupsController dobefore { sign_in(admin) }it "removes the backup if found" do- begin- path = backup_path(backup_filename)- create_backup_files(backup_filename)- expect(File.exist?(path)).to eq(true)+ path = backup_path(backup_filename)+ create_backup_files(backup_filename)+ expect(File.exist?(path)).to eq(true)- expect do delete "/admin/backups/#{backup_filename}.json" end.to change {- UserHistory.where(action: UserHistory.actions[:backup_destroy]).count- }.by(1)+ expect do delete "/admin/backups/#{backup_filename}.json" end.to change {+ UserHistory.where(action: UserHistory.actions[:backup_destroy]).count+ }.by(1)- expect(response.status).to eq(200)- expect(File.exist?(path)).to eq(false)- end+ expect(response.status).to eq(200)+ expect(File.exist?(path)).to eq(false)endit "doesn't remove the backup if not found" do@@ -322,19 +310,17 @@ RSpec.describe Admin::BackupsController doshared_examples "backup deletion not allowed" doit "prevents deletion with a 404 response" do- begin- path = backup_path(backup_filename)- create_backup_files(backup_filename)- expect(File.exist?(path)).to eq(true)+ path = backup_path(backup_filename)+ create_backup_files(backup_filename)+ expect(File.exist?(path)).to eq(true)- expect do delete "/admin/backups/#{backup_filename}.json" end.not_to change {- UserHistory.where(action: UserHistory.actions[:backup_destroy]).count- }+ expect do delete "/admin/backups/#{backup_filename}.json" end.not_to change {+ UserHistory.where(action: UserHistory.actions[:backup_destroy]).count+ }- expect(response.status).to eq(404)- expect(response.parsed_body["errors"]).to include(I18n.t("not_found"))- expect(File.exist?(path)).to eq(true)- end+ expect(response.status).to eq(404)+ expect(response.parsed_body["errors"]).to include(I18n.t("not_found"))+ expect(File.exist?(path)).to eq(true)endenddiff --git a/spec/requests/api/site_spec.rb b/spec/requests/api/site_spec.rbindex 2e1500fe9a1..41c04f6ad17 100644--- a/spec/requests/api/site_spec.rb+++ b/spec/requests/api/site_spec.rb@@ -21,19 +21,17 @@ RSpec.describe "site" doproduces "application/json"response "200", "success response" do- begin- Site.preloaded_category_custom_fields << "no_oddjob"-- expected_response_schema = load_spec_schema("site_response")- schema expected_response_schema-- it_behaves_like "a JSON endpoint", 200 do- let(:expected_response_schema) { expected_response_schema }- let(:expected_request_schema) { expected_request_schema }- end- ensure- Site.reset_preloaded_category_custom_fields+ Site.preloaded_category_custom_fields << "no_oddjob"++ expected_response_schema = load_spec_schema("site_response")+ schema expected_response_schema++ it_behaves_like "a JSON endpoint", 200 do+ let(:expected_response_schema) { expected_response_schema }+ let(:expected_request_schema) { expected_request_schema }end+ ensure+ Site.reset_preloaded_category_custom_fieldsendendenddiff --git a/spec/requests/static_controller_spec.rb b/spec/requests/static_controller_spec.rbindex d80eea5fe76..c7491c885bb 100644--- a/spec/requests/static_controller_spec.rb+++ b/spec/requests/static_controller_spec.rb@@ -69,37 +69,33 @@ RSpec.describe StaticController dolet(:site) { RailsMultisite::ConnectionManagement.current_db }it "can serve assets" do- begin- assets_path = Rails.public_path.join("assets")+ assets_path = Rails.public_path.join("assets")- FileUtils.mkdir_p(assets_path)+ FileUtils.mkdir_p(assets_path)- file_path = assets_path.join("test.js.br")- File.write(file_path, "fake brotli file")+ file_path = assets_path.join("test.js.br")+ File.write(file_path, "fake brotli file")- get "/cdn_asset/#{site}/test.js.br"+ get "/cdn_asset/#{site}/test.js.br"- expect(response.status).to eq(200)- expect(response.headers["Cache-Control"]).to match(/public/)- ensure- File.delete(file_path)- end+ expect(response.status).to eq(200)+ expect(response.headers["Cache-Control"]).to match(/public/)+ ensure+ File.delete(file_path)endit "does not serve files outside the assets directory via path traversal" do- begin- secret_dir = Rails.public_path.join("assets-secret")- FileUtils.mkdir_p(secret_dir)- secret_file = secret_dir.join("leak.txt")- File.write(secret_file, "secret content")+ secret_dir = Rails.public_path.join("assets-secret")+ FileUtils.mkdir_p(secret_dir)+ secret_file = secret_dir.join("leak.txt")+ File.write(secret_file, "secret content")- get "/cdn_asset/#{site}/../assets-secret/leak.txt"+ get "/cdn_asset/#{site}/../assets-secret/leak.txt"- expect(response.status).to eq(404)- ensure- File.delete(secret_file) if secret_file && File.exist?(secret_file)- FileUtils.rm_rf(secret_dir) if secret_dir && Dir.exist?(secret_dir)- end+ expect(response.status).to eq(404)+ ensure+ File.delete(secret_file) if secret_file && File.exist?(secret_file)+ FileUtils.rm_rf(secret_dir) if secret_dir && Dir.exist?(secret_dir)endcontext "with fallback_assets_path" dodiff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rbindex 0a8901cc215..291cca31e8f 100644--- a/spec/requests/topics_controller_spec.rb+++ b/spec/requests/topics_controller_spec.rb@@ -393,28 +393,26 @@ RSpec.describe TopicsController doendit "triggers an event on merge" do- begin- called = false+ called = false- assert = ->(original_topic, destination_topic) do- called = true- expect(original_topic).to eq(topic)- expect(destination_topic).to eq(dest_topic)- end+ assert = ->(original_topic, destination_topic) do+ called = true+ expect(original_topic).to eq(topic)+ expect(destination_topic).to eq(dest_topic)+ end- DiscourseEvent.on(:topic_merged, &assert)+ DiscourseEvent.on(:topic_merged, &assert)- post "/t/#{topic.id}/move-posts.json",- params: {- post_ids: [p2.id],- destination_topic_id: dest_topic.id,- }+ post "/t/#{topic.id}/move-posts.json",+ params: {+ post_ids: [p2.id],+ destination_topic_id: dest_topic.id,+ }- expect(called).to eq(true)- expect(response.status).to eq(200)- ensure- DiscourseEvent.off(:topic_merged, &assert)- end+ expect(called).to eq(true)+ expect(response.status).to eq(200)+ ensure+ DiscourseEvent.off(:topic_merged, &assert)endenddiff --git a/spec/support/dom_matcher.rb b/spec/support/dom_matcher.rbindex 08a874f6b6f..ad64bbdc934 100644--- a/spec/support/dom_matcher.rb+++ b/spec/support/dom_matcher.rb@@ -3,11 +3,9 @@ include Rails::Dom::Testing::Assertions::DomAssertionsRSpec::Matchers.define :be_same_dom do |expected|match do |actual|- begin- assert_dom_equal(expected, actual)- rescue Minitest::Assertion- false- end+ assert_dom_equal(expected, actual)+ rescue Minitest::Assertion+ falseendfailure_message { |actual| "Expected DOM:\n#{expected}\nto be the same as:\n#{actual}" }diff --git a/spec/system/page_objects/cdp.rb b/spec/system/page_objects/cdp.rbindex b8108eaa463..cd25775f999 100644--- a/spec/system/page_objects/cdp.rb+++ b/spec/system/page_objects/cdp.rb@@ -71,91 +71,85 @@ module PageObjectsdef with_network_disconnectedpage.driver.with_playwright_page do |pw_page|- begin- cdp_client = pw_page.context.new_cdp_session(pw_page)-- cdp_client.send_message(- "Network.emulateNetworkConditions",- params: {- offline: true,- latency: 0,- downloadThroughput: -1,- uploadThroughput: -1,- },- )-- yield- ensure- cdp_client.send_message(- "Network.emulateNetworkConditions",- params: {- offline: false,- latency: 0,- downloadThroughput: -1,- uploadThroughput: -1,- },- )- end+ cdp_client = pw_page.context.new_cdp_session(pw_page)++ cdp_client.send_message(+ "Network.emulateNetworkConditions",+ params: {+ offline: true,+ latency: 0,+ downloadThroughput: -1,+ uploadThroughput: -1,+ },+ )++ yield+ ensure+ cdp_client.send_message(+ "Network.emulateNetworkConditions",+ params: {+ offline: false,+ latency: 0,+ downloadThroughput: -1,+ uploadThroughput: -1,+ },+ )endenddef with_slow_downloadpage.driver.with_playwright_page do |pw_page|- begin- cdp_client = pw_page.context.new_cdp_session(pw_page)-- cdp_client.send_message(- "Network.emulateNetworkConditions",- params: {- offline: false,- latency: 20_000,- downloadThroughput: 1,- uploadThroughput: -1,- },- )-- yield- ensure- cdp_client.send_message(- "Network.emulateNetworkConditions",- params: {- offline: false,- latency: 0,- downloadThroughput: -1,- uploadThroughput: -1,- },- )- end+ cdp_client = pw_page.context.new_cdp_session(pw_page)++ cdp_client.send_message(+ "Network.emulateNetworkConditions",+ params: {+ offline: false,+ latency: 20_000,+ downloadThroughput: 1,+ uploadThroughput: -1,+ },+ )++ yield+ ensure+ cdp_client.send_message(+ "Network.emulateNetworkConditions",+ params: {+ offline: false,+ latency: 0,+ downloadThroughput: -1,+ uploadThroughput: -1,+ },+ )endenddef with_slow_uploadpage.driver.with_playwright_page do |pw_page|- begin- cdp_client = pw_page.context.new_cdp_session(pw_page)-- cdp_client.send_message(- "Network.emulateNetworkConditions",- params: {- offline: false,- latency: 20_000,- downloadThroughput: -1,- uploadThroughput: 1,- },- )-- yield- ensure- cdp_client.send_message(- "Network.emulateNetworkConditions",- params: {- offline: false,- latency: 0,- downloadThroughput: -1,- uploadThroughput: -1,- },- )- end+ cdp_client = pw_page.context.new_cdp_session(pw_page)++ cdp_client.send_message(+ "Network.emulateNetworkConditions",+ params: {+ offline: false,+ latency: 20_000,+ downloadThroughput: -1,+ uploadThroughput: 1,+ },+ )++ yield+ ensure+ cdp_client.send_message(+ "Network.emulateNetworkConditions",+ params: {+ offline: false,+ latency: 0,+ downloadThroughput: -1,+ uploadThroughput: -1,+ },+ )endendenddiff --git a/spec/system/user_page/user_preferences_account_spec.rb b/spec/system/user_page/user_preferences_account_spec.rbindex b3f6d0c2f50..0530e1b4b5e 100644--- a/spec/system/user_page/user_preferences_account_spec.rb+++ b/spec/system/user_page/user_preferences_account_spec.rb@@ -128,30 +128,28 @@ describe "User preferences | Account" doendit "shows provider names without links when provider_url is not implemented" do- begin- authenticator =- Class- .new(Auth::ManagedAuthenticator) do- def name- "test_no_url"- end-- def enabled?- true- end+ authenticator =+ Class+ .new(Auth::ManagedAuthenticator) do+ def name+ "test_no_url"+ end++ def enabled?+ trueend- .new+ end+ .new- provider = Auth::AuthProvider.new(authenticator:, icon: "flash")- DiscoursePluginRegistry.register_auth_provider(provider)+ provider = Auth::AuthProvider.new(authenticator:, icon: "flash")+ DiscoursePluginRegistry.register_auth_provider(provider)- user_account_preferences_page.visit(user)+ user_account_preferences_page.visit(user)- name = find(".pref-associated-accounts table tr.test-no-url .associated-account__name")- expect(name).not_to have_css("a")- ensure- DiscoursePluginRegistry.reset!- end+ name = find(".pref-associated-accounts table tr.test-no-url .associated-account__name")+ expect(name).not_to have_css("a")+ ensure+ DiscoursePluginRegistry.reset!endendend