Skip to content

A platform for community discussion. Free, open, simple.

DEV: Enable Style/RedundantBegin rubocop rule (#40096)

Jarek Radoszfbb3bf3fe858
diff --git a/.rubocop.yml b/.rubocop.yml
index a02a3da8b1b..435e774ff1e 100644
--- a/.rubocop.yml
+++ b/.rubocop.yml
@@ -65,3 +65,6 @@ Lint/SymbolConversion:
Style/RedundantParentheses:
Enabled: true
+
+Style/RedundantBegin:
+ Enabled: true
diff --git a/app/controllers/admin/backups_controller.rb b/app/controllers/admin/backups_controller.rb
index 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::AdminController
end
def 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"))
end
end
diff --git a/app/controllers/admin/themes_controller.rb b/app/controllers/admin/themes_controller.rb
index 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::AdminController
end
hijack 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.message
end
end
elsif params[:bundle] ||
@@ -388,39 +386,35 @@ class Admin::ThemesController < Admin::AdminController
theme_id = @theme.id
hijack 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.message
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.message
end
end
diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb
index 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::StaffController
options[:prepare_for_destroy] = true
hijack 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 }
+ else
render 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: :forbidden
end
end
diff --git a/app/controllers/drafts_controller.rb b/app/controllers/drafts_controller.rb
index 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 delete
end
if sequence_errors.any?
diff --git a/app/controllers/finish_installation_controller.rb b/app/controllers/finish_installation_controller.rb
index 6f4dd95e064..f6d81afe07f 100644
--- a/app/controllers/finish_installation_controller.rb
+++ b/app/controllers/finish_installation_controller.rb
@@ -84,21 +84,19 @@ class FinishInstallationController < ApplicationController
end
def 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.message
end
def seed_admin_users
diff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rb
index 8d7ac528dd9..18075bb6e8b 100644
--- a/app/controllers/groups_controller.rb
+++ b/app/controllers/groups_controller.rb
@@ -423,19 +423,17 @@ class GroupsController < ApplicationController
skip_email ||= params.key?(:notify_users) && !notify
emails.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
+ )
end
render json: success_json.merge!(usernames: uniq_users.map(&:username), emails: emails)
@@ -757,30 +755,28 @@ class GroupsController < ApplicationController
end
hijack 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))
end
end
diff --git a/app/controllers/invites_controller.rb b/app/controllers/invites_controller.rb
index 5df6cf2ff79..fa55cef53da 100644
--- a/app/controllers/invites_controller.rb
+++ b/app/controllers/invites_controller.rb
@@ -90,28 +90,26 @@ class InvitesController < ApplicationController
fail = []
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 })
end
render json: {
@@ -124,62 +122,59 @@ class InvitesController < ApplicationController
end
def 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_entity
end
+ rescue Invite::UserExists => e
+ render_json_error(e.message)
+ rescue ActiveRecord::RecordInvalid => e
+ render_json_error(e.record.errors.full_messages.first)
end
def retrieve
@@ -489,68 +484,66 @@ class InvitesController < ApplicationController
guardian.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_json
end
+ else
+ render json: failed_json.merge(errors: [I18n.t("bulk_invite.error")]),
+ status: :unprocessable_entity
end
end
end
diff --git a/app/controllers/stylesheets_controller.rb b/app/controllers/stylesheets_controller.rb
index a5f9740613c..0f808f1bfcc 100644
--- a/app/controllers/stylesheets_controller.rb
+++ b/app/controllers/stylesheets_controller.rb
@@ -105,9 +105,7 @@ class StylesheetsController < ApplicationController
private
def read_file(location)
- begin
- File.read(location)
- rescue Errno::ENOENT
- end
+ File.read(location)
+ rescue Errno::ENOENT
end
end
diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb
index 748e1dc9736..cd680bfe619 100644
--- a/app/controllers/tags_controller.rb
+++ b/app/controllers/tags_controller.rb
@@ -320,30 +320,28 @@ class TagsController < ::ApplicationController
file = params[:file] || params[:files].first
hijack 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)
end
end
- render json: success_json
- rescue Discourse::InvalidParameters => e
- render json: failed_json.merge(errors: [e.message]), status: :unprocessable_entity
end
+ render json: success_json
+ rescue Discourse::InvalidParameters => e
+ render json: failed_json.merge(errors: [e.message]), status: :unprocessable_entity
end
end
diff --git a/app/controllers/theme_javascripts_controller.rb b/app/controllers/theme_javascripts_controller.rb
index 3fa589d55ac..5434bd06167 100644
--- a/app/controllers/theme_javascripts_controller.rb
+++ b/app/controllers/theme_javascripts_controller.rb
@@ -72,12 +72,10 @@ class ThemeJavascriptsController < ApplicationController
def 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)
end
end
diff --git a/app/controllers/uploads_controller.rb b/app/controllers/uploads_controller.rb
index 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 this
hijack 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 : 422
end
end
@@ -117,26 +115,24 @@ class UploadsController < ApplicationController
request.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_404
end
end
ensure
@@ -392,15 +388,13 @@ class UploadsController < ApplicationController
end
def 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)
end
end
diff --git a/app/controllers/user_avatars_controller.rb b/app/controllers/user_avatars_controller.rb
index c0c4966b4a1..d0dc32c054d 100644
--- a/app/controllers/user_avatars_controller.rb
+++ b/app/controllers/user_avatars_controller.rb
@@ -53,14 +53,12 @@ class UserAvatarsController < ApplicationController
return 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_blank
end
end
diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb
index 338a3f643d0..589abc40af9 100644
--- a/app/controllers/users_controller.rb
+++ b/app/controllers/users_controller.rb
@@ -2248,12 +2248,10 @@ class UsersController < ApplicationController
allowed_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
+ false
end
end
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index c49e29925b0..95c67502878 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -457,32 +457,28 @@ module ApplicationHelper
def 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_url
else
- if dark_color_scheme? && SiteSetting.site_logo_dark_url.present?
- SiteSetting.site_logo_dark_url
- else
- SiteSetting.site_logo_url
- end
+ SiteSetting.site_logo_url
end
end
end
def 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_url
end
end
end
@@ -584,12 +580,10 @@ module ApplicationHelper
Discourse
.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")
+ nil
end
end
@@ -665,14 +659,12 @@ module ApplicationHelper
end
def 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
+ ""
end
def theme_id
diff --git a/app/jobs/base.rb b/app/jobs/base.rb
index 16fa6f1ccfc..abe32acac5c 100644
--- a/app/jobs/base.rb
+++ b/app/jobs/base.rb
@@ -106,11 +106,9 @@ module Jobs
end
def 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 Jobs
interval = 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",
+ )
end
end
end
@@ -299,38 +295,36 @@ module Jobs
exceptions = []
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 => e
exception[: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?
end
Thread.current[Logster::Logger::LOGSTER_ENV] = nil
diff --git a/app/jobs/onceoff/grant_onebox.rb b/app/jobs/onceoff/grant_onebox.rb
index 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 care
end
end
diff --git a/app/jobs/regular/export_user_archive.rb b/app/jobs/regular/export_user_archive.rb
index a5035f0e4b7..ab7f96f7686 100644
--- a/app/jobs/regular/export_user_archive.rb
+++ b/app/jobs/regular/export_user_archive.rb
@@ -187,16 +187,14 @@ module Jobs
end
def 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)
end
end
diff --git a/app/jobs/regular/sync_access_control_for_uploads.rb b/app/jobs/regular/sync_access_control_for_uploads.rb
index 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,
+ },
+ )
end
end
end
diff --git a/app/jobs/scheduled/clean_up_inactive_users.rb b/app/jobs/scheduled/clean_up_inactive_users.rb
index 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 Jobs
User.transaction do
ids.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 e
end
end
end
diff --git a/app/jobs/scheduled/clean_up_unused_staged_users.rb b/app/jobs/scheduled/clean_up_unused_staged_users.rb
index 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,
+ },
+ )
end
end
end
diff --git a/app/jobs/scheduled/process_user_notification_schedules.rb b/app/jobs/scheduled/process_user_notification_schedules.rb
index 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}",
+ )
end
end
end
diff --git a/app/jobs/scheduled/topic_timer_enqueuer.rb b/app/jobs/scheduled/topic_timer_enqueuer.rb
index 13322184e66..ca4d8180def 100644
--- a/app/jobs/scheduled/topic_timer_enqueuer.rb
+++ b/app/jobs/scheduled/topic_timer_enqueuer.rb
@@ -14,14 +14,13 @@ module Jobs
TopicTimer.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}",
+ )
end
end
end
diff --git a/app/models/bookmark.rb b/app/models/bookmark.rb
index dbee454ebd4..f7efb6a7293 100644
--- a/app/models/bookmark.rb
+++ b/app/models/bookmark.rb
@@ -11,14 +11,12 @@ class Bookmark < ActiveRecord::Base
end
def 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 NameError
end
def self.valid_bookmarkable_types
diff --git a/app/models/draft.rb b/app/models/draft.rb
index d3705221bbe..87e604462cd 100644
--- a/app/models/draft.rb
+++ b/app/models/draft.rb
@@ -150,11 +150,9 @@ class Draft < ActiveRecord::Base
end
def parsed_data
- begin
- JSON.parse(data)
- rescue JSON::ParserError
- {}
- end
+ JSON.parse(data)
+ rescue JSON::ParserError
+ {}
end
def topic_id
diff --git a/app/models/global_setting.rb b/app/models/global_setting.rb
index fce1c211714..1d7cb57c04d 100644
--- a/app/models/global_setting.rb
+++ b/app/models/global_setting.rb
@@ -98,13 +98,11 @@ class GlobalSetting
def 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
+ :false
end
) == :true
end
diff --git a/app/models/post.rb b/app/models/post.rb
index 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_fields
end
end
problems
diff --git a/app/models/post_analyzer.rb b/app/models/post_analyzer.rb
index 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
+ next
end
@linked_hosts
diff --git a/app/models/post_mover.rb b/app/models/post_mover.rb
index 161738a3c29..12de911cd16 100644
--- a/app/models/post_mover.rb
+++ b/app/models/post_mover.rb
@@ -722,14 +722,12 @@ class PostMover
def 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? }
end
def update_last_post_stats
diff --git a/app/models/site_setting.rb b/app/models/site_setting.rb
index 62763180c34..29634a0c044 100644
--- a/app/models/site_setting.rb
+++ b/app/models/site_setting.rb
@@ -241,28 +241,28 @@ class SiteSetting < ActiveRecord::Base
current_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("|"),
+ )
end
def self.blocked_attachment_filenames_regex
current_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("|"),
+ )
end
def self.allowed_unicode_username_characters_regex
current_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)
end
end
diff --git a/app/models/theme_field.rb b/app/models/theme_field.rb
index da08fe71957..bb686aa7e4b 100644
--- a/app/models/theme_field.rb
+++ b/app/models/theme_field.rb
@@ -208,14 +208,12 @@ class ThemeField < ActiveRecord::Base
fallback_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::Base
end
def 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,
+ )
end
end
diff --git a/app/models/topic_link.rb b/app/models/topic_link.rb
index 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 deal
end
end
diff --git a/app/models/topic_list.rb b/app/models/topic_list.rb
index cc810d51b85..f6222be384d 100644
--- a/app/models/topic_list.rb
+++ b/app/models/topic_list.rb
@@ -179,12 +179,10 @@ class TopicList
def 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
+ []
end
end
end
diff --git a/app/models/upload.rb b/app/models/upload.rb
index 60c5c2ebd44..83446d5fb6c 100644
--- a/app/models/upload.rb
+++ b/app/models/upload.rb
@@ -559,93 +559,87 @@ class Upload < ActiveRecord::Base
remap_scope = nil
scope.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
+ next
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
- ],
- )
- 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)
+ end
end
+
+ 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
end
end
end
diff --git a/app/models/user.rb b/app/models/user.rb
index 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 going
end
end
diff --git a/app/models/user_action.rb b/app/models/user_action.rb
index 793cc8fc54c..90714e8ce0d 100644
--- a/app/models/user_action.rb
+++ b/app/models/user_action.rb
@@ -274,45 +274,43 @@ class UserAction < ActiveRecord::Base
require_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::Rollback
end
end
diff --git a/app/models/user_avatar.rb b/app/models/user_avatar.rb
index 9f81c4c97a9..2b40ef99272 100644
--- a/app/models/user_avatar.rb
+++ b/app/models/user_avatar.rb
@@ -27,61 +27,59 @@ class UserAvatar < ActiveRecord::Base
def 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)
end
end
- 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!
end
end
@@ -199,14 +197,12 @@ class UserAvatar < ActiveRecord::Base
warnings_reported = 0
ids.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 += 1
end
end
end
diff --git a/app/models/user_export.rb b/app/models/user_export.rb
index 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")}",
+ )
end
end
end
diff --git a/app/models/user_profile.rb b/app/models/user_profile.rb
index 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 }
end
problems
end
diff --git a/app/serializers/post_serializer.rb b/app/serializers/post_serializer.rb
index 011f54523ea..76b4d731e3b 100644
--- a/app/serializers/post_serializer.rb
+++ b/app/serializers/post_serializer.rb
@@ -177,12 +177,10 @@ class PostSerializer < BasicPostSerializer
def 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)
end
end
diff --git a/app/serializers/post_stream_serializer_mixin.rb b/app/serializers/post_stream_serializer_mixin.rb
index f6ef79a25c0..e3f84a6de19 100644
--- a/app/serializers/post_stream_serializer_mixin.rb
+++ b/app/serializers/post_stream_serializer_mixin.rb
@@ -56,18 +56,16 @@ module PostStreamSerializerMixin
def 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_json
end
end
diff --git a/app/services/destroy_task.rb b/app/services/destroy_task.rb
index 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}"
end
end
diff --git a/app/services/email_settings_validator.rb b/app/services/email_settings_validator.rb
index 451adf0e92c..92df9e37b30 100644
--- a/app/services/email_settings_validator.rb
+++ b/app/services/email_settings_validator.rb
@@ -25,25 +25,23 @@ class EmailSettingsValidator
openssl_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 EmailSettingsValidator
openssl_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)
end
def 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.rb
index 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 < ProblemCheck
end
def 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_problem
end
end
diff --git a/app/services/search_indexer.rb b/app/services/search_indexer.rb
index 2e2c70582be..09ec2c2e967 100644
--- a/app/services/search_indexer.rb
+++ b/app/services/search_indexer.rb
@@ -357,15 +357,13 @@ class SearchIndexer
raw_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::InvalidURIError
end
raw_data
diff --git a/app/services/video_conversion/aws_media_convert_adapter.rb b/app/services/video_conversion/aws_media_convert_adapter.rb
index 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 VideoConversion
end
def 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,
+ },
+ )
+ raise
end
def remove_temp_file(s3_store, temp_path)
diff --git a/config/initializers/005-site_settings.rb b/config/initializers/005-site_settings.rb
index 7527f49a449..b23ee0cf39f 100644
--- a/config/initializers/005-site_settings.rb
+++ b/config/initializers/005-site_settings.rb
@@ -16,13 +16,11 @@ end
Rails.application.config.to_prepare do
RailsMultisite::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 database
end
end
diff --git a/config/initializers/014-track-setting-changes.rb b/config/initializers/014-track-setting-changes.rb
index 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}",
+ )
end
end
end
diff --git a/config/initializers/101-lograge.rb b/config/initializers/101-lograge.rb
index 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")}",
+ )
+ {}
end
config.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]
+ end
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")}",
+ )
+ {}
end
config.lograge.formatter = Lograge::Formatters::Logstash.new
diff --git a/db/fixtures/001_refresh.rb b/db/fixtures/001_refresh.rb
index 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
+ nil
end
@refreshed = true
diff --git a/db/migrate/20121204183855_fix_link_post_id.rb b/db/migrate/20121204183855_fix_link_post_id.rb
index 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.id
end
TopicLink.where("id in (?)", to_remove).delete_all
diff --git a/db/migrate/20131210181901_migrate_word_counts.rb b/db/migrate/20131210181901_migrate_word_counts.rb
index 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 > 0
3.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.
end
post_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 > 0
3.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.
end
topic_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.rb
index 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!
end
def down
diff --git a/db/migrate/20180521190040_allow_null_ip_topic_link_click.rb b/db/migrate/20180521190040_allow_null_ip_topic_link_click.rb
index 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!
end
def down
diff --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.rb
index 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!
end
end
diff --git a/db/migrate/20181210122522_remove_not_null_user_associated_account_user.rb b/db/migrate/20181210122522_remove_not_null_user_associated_account_user.rb
index 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!
end
end
diff --git a/db/migrate/20210617202227_change_automatic_on_directory_columns_to_bool.rb b/db/migrate/20210617202227_change_automatic_on_directory_columns_to_bool.rb
index 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 <<~SQL
UPDATE directory_columns SET automatic = (user_field_id IS NULL);
SQL
- ensure
- Migration::SafeMigrate.enable!
- end
+ ensure
+ Migration::SafeMigrate.enable!
end
def down
diff --git a/db/migrate/20211213060445_email_tokens_token_to_nullable.rb b/db/migrate/20211213060445_email_tokens_token_to_nullable.rb
index 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 > 0
ALTER TABLE email_tokens ALTER COLUMN token DROP NOT NULL
SQL
SELECT 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!
end
def down
diff --git a/lib/auth/default_current_user_provider.rb b/lib/auth/default_current_user_provider.rb
index 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::DefaultCurrentUserProvider
return @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_i
end
end
end
diff --git a/lib/autospec/manager.rb b/lib/autospec/manager.rb
index 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 @debug
Thread.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 e
end
end
end
diff --git a/lib/backup_restore/creator.rb b/lib/backup_restore/creator.rb
index ff3fcba943a..0691233d043 100644
--- a/lib/backup_restore/creator.rb
+++ b/lib/backup_restore/creator.rb
@@ -158,16 +158,14 @@ module BackupRestore
end
IO.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 << line
end
+ rescue EOFError
+ # finished reading...
+ ensure
+ pg_dump_running = false
+ logs << ""
end
raise "pg_dump failed" unless $?.success?
diff --git a/lib/backup_restore/database_restorer.rb b/lib/backup_restore/database_restorer.rb
index b076f1ac0b2..92cc38773ab 100644
--- a/lib/backup_restore/database_restorer.rb
+++ b/lib/backup_restore/database_restorer.rb
@@ -76,16 +76,14 @@ module BackupRestore
end
IO.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 = line
end
+ rescue EOFError
+ # finished reading...
+ ensure
+ psql_running = false
end
logs << ""
diff --git a/lib/demon/base.rb b/lib/demon/base.rb
index f61d9e7477f..e22275a987d 100644
--- a/lib/demon/base.rb
+++ b/lib/demon/base.rb
@@ -264,12 +264,10 @@ class Demon::Base
Discourse.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 now
diff --git a/lib/discourse.rb b/lib/discourse.rb
index e5c35535256..681aa204f74 100644
--- a/lib/discourse.rb
+++ b/lib/discourse.rb
@@ -589,12 +589,10 @@ module Discourse
def 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.new
end
end
@@ -1193,11 +1191,9 @@ module Discourse
def self.reset_active_record_cache
ActiveRecord::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
+ nil
end
nil
end
@@ -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
+ nil
end
# 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
+ nil
end,
Thread.new do
# preload discourse version
diff --git a/lib/discourse_dev/post.rb b/lib/discourse_dev/post.rb
index 350696a7d8d..1d965183ff9 100644
--- a/lib/discourse_dev/post.rb
+++ b/lib/discourse_dev/post.rb
@@ -94,20 +94,18 @@ module DiscourseDev
puts "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 e
end
puts "Done!"
diff --git a/lib/discourse_ip_info.rb b/lib/discourse_ip_info.rb
index ab697db919b..0ccbdc5d7bb 100644
--- a/lib/discourse_ip_info.rb
+++ b/lib/discourse_ip_info.rb
@@ -82,15 +82,13 @@ class DiscourseIpInfo
end
def 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.")
+ nil
end
def lookup(ip, locale: :en, resolve_hostname: false)
diff --git a/lib/discourse_updates.rb b/lib/discourse_updates.rb
index 438e8cdfa2d..90c0517e2bd 100644
--- a/lib/discourse_updates.rb
+++ b/lib/discourse_updates.rb
@@ -143,19 +143,17 @@ module DiscourseUpdates
return [] 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
+ false
end
entries.sort_by { |item| Time.zone.parse(item["created_at"]).to_i }.reverse
diff --git a/lib/email/processor.rb b/lib/email/processor.rb
index 30c50c2baef..e47ff2565cd 100644
--- a/lib/email/processor.rb
+++ b/lib/email/processor.rb
@@ -14,24 +14,22 @@ module Email
end
def 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)
end
end
diff --git a/lib/email/receiver.rb b/lib/email/receiver.rb
index 6dc9c004e1b..9b1aa1cbc7a 100644
--- a/lib/email/receiver.rb
+++ b/lib/email/receiver.rb
@@ -124,27 +124,25 @@ module Email
id_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
+ raise
end
end
@@ -249,11 +247,9 @@ module Email
first_exception = nil
destinations.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 ||= e
end
raise first_exception if first_exception
@@ -292,10 +288,8 @@ module Email
next 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.downcase
end
end
@@ -763,28 +757,26 @@ module Email
end
def 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 nil
end
def subject
@@ -1587,46 +1579,44 @@ module Email
next 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 allowed
end
+ rescue ActiveRecord::RecordInvalid, EmailNotAllowed
+ # don't care if user already allowed or the user's email address is not allowed
end
end
end
diff --git a/lib/email/sender.rb b/lib/email/sender.rb
index 5592212a44d..e3ffc872e23 100644
--- a/lib/email/sender.rb
+++ b/lib/email/sender.rb
@@ -330,17 +330,11 @@ module Email
end
def cc_addresses
- @cc_addresses ||=
- begin
- @message.try(:cc) || []
- end
+ @cc_addresses ||= @message.try(:cc) || []
end
def bcc_addresses
- @bcc_addresses ||=
- begin
- @message.try(:bcc) || []
- end
+ @bcc_addresses ||= @message.try(:bcc) || []
end
def self.host_for(base_url)
diff --git a/lib/email/styles.rb b/lib/email/styles.rb
index 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
+ 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
+ i.remove
end
end
@@ -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 it
end
end
diff --git a/lib/external_upload_helpers.rb b/lib/external_upload_helpers.rb
index f4d90f4c699..d65286f17cf 100644
--- a/lib/external_upload_helpers.rb
+++ b/lib/external_upload_helpers.rb
@@ -291,55 +291,50 @@ module ExternalUploadHelpers
external_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)
end
end
diff --git a/lib/final_destination.rb b/lib/final_destination.rb
index 924b7ae5b34..b7f76b1bdc1 100644
--- a/lib/final_destination.rb
+++ b/lib/final_destination.rb
@@ -562,10 +562,8 @@ class FinalDestination
private
def uri(location)
- begin
- URI.parse(location)
- rescue URI::Error
- end
+ URI.parse(location)
+ rescue URI::Error
end
def fetch_canonical_url(body)
diff --git a/lib/freedom_patches/rails_multisite.rb b/lib/freedom_patches/rails_multisite.rb
index a4ae7899997..63886a919fc 100644
--- a/lib/freedom_patches/rails_multisite.rb
+++ b/lib/freedom_patches/rails_multisite.rb
@@ -12,27 +12,25 @@ module RailsMultisite
def self.safe_each_connection
each_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 fails
end
end
end
diff --git a/lib/freedom_patches/translate_accelerator.rb b/lib/freedom_patches/translate_accelerator.rb
index fafa982118a..88a07c6e68e 100644
--- a/lib/freedom_patches/translate_accelerator.rb
+++ b/lib/freedom_patches/translate_accelerator.rb
@@ -147,11 +147,9 @@ module I18n
val =
@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
+ MissingTranslation
end
if val != MissingTranslation
diff --git a/lib/guardian/tag_guardian.rb b/lib/guardian/tag_guardian.rb
index 1d8e13b17f2..78ee36b1d86 100644
--- a/lib/guardian/tag_guardian.rb
+++ b/lib/guardian/tag_guardian.rb
@@ -43,12 +43,10 @@ module TagGuardian
def 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
+ []
end
end
end
diff --git a/lib/guardian/user_guardian.rb b/lib/guardian/user_guardian.rb
index b14e1167b8e..ec8d6301b3f 100644
--- a/lib/guardian/user_guardian.rb
+++ b/lib/guardian/user_guardian.rb
@@ -183,12 +183,10 @@ module UserGuardian
is_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)
end
end
diff --git a/lib/i18n/backend/discourse_i18n.rb b/lib/i18n/backend/discourse_i18n.rb
index f72019e697e..2ab8b520309 100644
--- a/lib/i18n/backend/discourse_i18n.rb
+++ b/lib/i18n/backend/discourse_i18n.rb
@@ -27,12 +27,10 @@ module I18n
end
def 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)
end
def self.sort_locale_files(files)
diff --git a/lib/i18n/locale_file_checker.rb b/lib/i18n/locale_file_checker.rb
index a66eeff7999..9e2edbd52c6 100644
--- a/lib/i18n/locale_file_checker.rb
+++ b/lib/i18n/locale_file_checker.rb
@@ -170,13 +170,11 @@ class LocaleFileChecker
end
def 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_h
end
def add_error(keys, type, details, pluralized:)
diff --git a/lib/import_export/importer.rb b/lib/import_export/importer.rb
index 550a9b66f4c..91a94e11da6 100644
--- a/lib/import_export/importer.rb
+++ b/lib/import_export/importer.rb
@@ -66,11 +66,9 @@ module ImportExport
new_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::RecordNotUnique
end
end
@@ -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}"
end
self
diff --git a/lib/letter_avatar.rb b/lib/letter_avatar.rb
index 1081c886eaf..353ed9e3490 100644
--- a/lib/letter_avatar.rb
+++ b/lib/letter_avatar.rb
@@ -119,17 +119,15 @@ class LetterAvatar
end
def 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 exists
end
end
diff --git a/lib/middleware/anonymous_cache.rb b/lib/middleware/anonymous_cache.rb
index 6d50cc81dca..b24c4707b5b 100644
--- a/lib/middleware/anonymous_cache.rb
+++ b/lib/middleware/anonymous_cache.rb
@@ -118,10 +118,8 @@ module Middleware
alias_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 == :true
end
# rubocop:enable Lint/BooleanSymbol
@@ -137,19 +135,18 @@ module Middleware
# rubocop:disable Lint/BooleanSymbol
def 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")
:true
else
- if @user_agent.downcase.include?("discourse") &&
- !@user_agent.downcase.include?("mobile")
- :true
- else
- :false
- end
+ :false
end
end
+
@is_crawler == :true
end
alias_method :key_is_crawler?, :is_crawler?
diff --git a/lib/middleware/request_tracker.rb b/lib/middleware/request_tracker.rb
index 8c72a394f0d..8fcb78944fe 100644
--- a/lib/middleware/request_tracker.rb
+++ b/lib/middleware/request_tracker.rb
@@ -405,11 +405,9 @@ class Middleware::RequestTracker
limiters.each(&:rollback!)
env["DISCOURSE_ASSET_RATE_LIMITERS"].each do |limiter|
- begin
- limiter.performed!
- rescue RateLimiter::LimitExceeded
- # skip
- end
+ limiter.performed!
+ rescue RateLimiter::LimitExceeded
+ # skip
end
end
@@ -421,14 +419,12 @@ class Middleware::RequestTracker
def 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 writes
end
end
diff --git a/lib/mini_scheduler_long_running_job_logger.rb b/lib/mini_scheduler_long_running_job_logger.rb
index 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 MiniSchedulerLongRunningJobLogger
end
warning_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.hours
end
next 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.rb
index 87a0acae0cc..37ad05bed5f 100644
--- a/lib/onebox/engine/google_maps_onebox.rb
+++ b/lib/onebox/engine/google_maps_onebox.rb
@@ -171,29 +171,25 @@ module Onebox
end
def 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)
+ ensure
begin
- 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
+ nil
end
end
end
diff --git a/lib/onebox/helpers.rb b/lib/onebox/helpers.rb
index de7b77e9d11..d84bc42fe73 100644
--- a/lib/onebox/helpers.rb
+++ b/lib/onebox/helpers.rb
@@ -212,11 +212,9 @@ module Onebox
end
def 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
+ src
end
def self.user_agent
diff --git a/lib/onebox/json_ld.rb b/lib/onebox/json_ld.rb
index 1dbc8faf554..24de0eefb9b 100644
--- a/lib/onebox/json_ld.rb
+++ b/lib/onebox/json_ld.rb
@@ -35,12 +35,10 @@ module Onebox
end
def 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}")
+ {}
end
end
end
diff --git a/lib/plugin.rb b/lib/plugin.rb
index c384d905667..e5b1f508686 100644
--- a/lib/plugin.rb
+++ b/lib/plugin.rb
@@ -2,44 +2,39 @@
module Plugin
def 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 Plugin
Please 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 1
end
+ exit 1
end
end
diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rb
index 98a1f5ec6c9..60fa115c048 100644
--- a/lib/plugin/instance.rb
+++ b/lib/plugin/instance.rb
@@ -677,14 +677,12 @@ class Plugin::Instance
def notify_after_initialize
initializers.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")
end
end
diff --git a/lib/pretty_text.rb b/lib/pretty_text.rb
index 54fe655f738..7cd0428a257 100644
--- a/lib/pretty_text.rb
+++ b/lib/pretty_text.rb
@@ -539,23 +539,21 @@ module PrettyText
doc
.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 it
end
end
diff --git a/lib/s3_helper.rb b/lib/s3_helper.rb
index 36c496b7259..457e016f999 100644
--- a/lib/s3_helper.rb
+++ b/lib/s3_helper.rb
@@ -450,12 +450,10 @@ class S3Helper
end
def 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
+ []
end
def default_s3_options
diff --git a/lib/s3_inventory.rb b/lib/s3_inventory.rb
index ee5371e52fb..43ed9b0e5b0 100644
--- a/lib/s3_inventory.rb
+++ b/lib/s3_inventory.rb
@@ -46,66 +46,62 @@ class S3Inventory
end
DistributedMutex.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}.etag
FROM #{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 = :verified
WHERE 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_etag
WHERE verification_status <> :invalid_etag
@@ -135,34 +131,32 @@ class S3Inventory
WHERE #{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.url
end
end
- 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"
end
end
+
+ set_missing_s3_discourse_stats(missing_count)
ensure
- cleanup!
+ connection.exec("DROP TABLE #{tmp_table_name}") unless connection.nil?
end
+ ensure
+ cleanup!
end
end
diff --git a/lib/scheduler/defer.rb b/lib/scheduler/defer.rb
index 8cf296cace8..847b4a0460c 100644
--- a/lib/scheduler/defer.rb
+++ b/lib/scheduler/defer.rb
@@ -128,21 +128,19 @@ module Scheduler
db ||= RailsMultisite::ConnectionManagement::DEFAULT
RailsMultisite::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 stats
end
+ Discourse.handle_job_exception(ex, message: "Running deferred code '#{desc}'")
+ ensure
+ warning_job&.cancel
end
rescue => ex
Discourse.handle_job_exception(ex, message: "Processing deferred code queue")
diff --git a/lib/scheduler/thread_pool.rb b/lib/scheduler/thread_pool.rb
index 7f9308c01de..7ced614f65d 100644
--- a/lib/scheduler/thread_pool.rb
+++ b/lib/scheduler/thread_pool.rb
@@ -114,14 +114,9 @@ module Scheduler
def 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")
end
end
diff --git a/lib/search/grouped_search_results.rb b/lib/search/grouped_search_results.rb
index 03830d37712..bb52afd96f7 100644
--- a/lib/search/grouped_search_results.rb
+++ b/lib/search/grouped_search_results.rb
@@ -142,15 +142,13 @@ class Search
urls = Set.new
cooked.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::InvalidURIError
end
end
diff --git a/lib/signal_trap_logger.rb b/lib/signal_trap_logger.rb
index fcedd18a48a..5012817b773 100644
--- a/lib/signal_trap_logger.rb
+++ b/lib/signal_trap_logger.rb
@@ -35,14 +35,12 @@ class SignalTrapLogger
@thread =
Thread.new do
loop 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")}",
+ )
end
end
end
diff --git a/lib/site_setting_extension.rb b/lib/site_setting_extension.rb
index d7bbda17785..014f33dc951 100644
--- a/lib/site_setting_extension.rb
+++ b/lib/site_setting_extension.rb
@@ -321,26 +321,24 @@ module SiteSettingExtension
end
def 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}",
+ )
+ nil
end
def all_settings(
@@ -679,12 +677,10 @@ module SiteSettingExtension
end
def 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)
end
def process_id
@@ -1361,9 +1357,10 @@ module SiteSettingExtension
def 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_h
end
def uploads
diff --git a/lib/socket_server.rb b/lib/socket_server.rb
index 4c802d8b0d6..c19d9ec2a02 100644
--- a/lib/socket_server.rb
+++ b/lib/socket_server.rb
@@ -26,13 +26,11 @@ class SocketServer
def new_accept_thread
server = @server
Thread.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}")
end
end
diff --git a/lib/stylesheet/manager/builder.rb b/lib/stylesheet/manager/builder.rb
index 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 recompile
def 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_digest
end
end
diff --git a/lib/stylesheet/watcher.rb b/lib/stylesheet/watcher.rb
index 9dbc7da72c9..3ba1c14c434 100644
--- a/lib/stylesheet/watcher.rb
+++ b/lib/stylesheet/watcher.rb
@@ -35,12 +35,10 @@ module Stylesheet
def start
Thread.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}"
+ start
end
listener_opts = { ignore: [/node_modules/], only: /\.s?css\z/ }
diff --git a/lib/svg_sprite.rb b/lib/svg_sprite.rb
index a775ccfd085..eea0e03daf3 100644
--- a/lib/svg_sprite.rb
+++ b/lib/svg_sprite.rb
@@ -378,16 +378,11 @@ module SvgSprite
theme_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_h
diff --git a/lib/tasks/assets.rake b/lib/tasks/assets.rake
index 67bec8c3e5d..4cda3f1aefc 100644
--- a/lib/tasks/assets.rake
+++ b/lib/tasks/assets.rake
@@ -56,16 +56,14 @@ task "assets:precompile:css" => "environment" do
end
task "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"
end
def assets_path
diff --git a/lib/tasks/db.rake b/lib/tasks/db.rake
index 80121b37dd0..0280f72e405 100644
--- a/lib/tasks/db.rake
+++ b/lib/tasks/db.rake
@@ -2,16 +2,14 @@
# we should set the locale before the migration
task "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 = :en
end
module 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 e
end
execute_db_migration
@@ -465,11 +461,9 @@ task "db:validate_indexes", [:arg] => %w[db:ensure_post_migrations environment]
if fix_indexes
puts "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}"
end
end
else
@@ -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 indexes
table_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 key
end
end
rescue StandardError
@@ -587,14 +577,12 @@ end
desc "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)
end
desc "Grow notification id column to a big int in case of overflow"
diff --git a/lib/tasks/emails.rake b/lib/tasks/emails.rake
index cbf9b73106a..e0929356fc8 100644
--- a/lib/tasks/emails.rake
+++ b/lib/tasks/emails.rake
@@ -1,58 +1,54 @@
# frozen_string_literal: true
def 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 "."
end
desc "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_mails
end
-
- puts "Done"
- rescue Net::POPAuthenticationError
- puts "AUTH EXCEPTION: please make sure your credentials are correct."
- exit(10)
- ensure
- RateLimiter.enable
end
+
+ puts "Done"
+rescue Net::POPAuthenticationError
+ puts "AUTH EXCEPTION: please make sure your credentials are correct."
+ exit(10)
+ensure
+ RateLimiter.enable
end
desc "Check if SMTP connection is successful and send test message"
diff --git a/lib/tasks/import.rake b/lib/tasks/import.rake
index e7abf431acd..4758ce59c3b 100644
--- a/lib/tasks/import.rake
+++ b/lib/tasks/import.rake
@@ -593,32 +593,30 @@ task "import:remap_old_phpbb_permalinks" => :environment do
Post
.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
+ nil
end
+ 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 += 1
end
+ rescue StandardError
+ # skip
end
log "Done! #{i} posts remapped."
diff --git a/lib/tasks/posts.rake b/lib/tasks/posts.rake
index 75de514490d..bf33b8df698 100644
--- a/lib/tasks/posts.rake
+++ b/lib/tasks/posts.rake
@@ -334,12 +334,10 @@ task "posts:delete_all_likes" => :environment do
total = post_actions.count
post_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
+ # skip
end
UserStat.update_all(likes_given: 0, likes_received: 0) # clear user likes stats
@@ -707,19 +705,17 @@ def recover_uploads_from_index(path)
end
File.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)"
next
end
+ rescue Discourse::InvalidAccess
+ puts "Skipping #{url} in #{post.full_url} unable to create upload (bad format)"
+ next
end
end
if changed
diff --git a/lib/tasks/themes.rake b/lib/tasks/themes.rake
index 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"
end
true
diff --git a/lib/tasks/uploads.rake b/lib/tasks/uploads.rake
index 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 "."
end
puts "", "Done!"
@@ -72,16 +70,14 @@ task "uploads:backfill_shas" => :environment do
Upload
.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}"
end
end
puts "", "Done"
@@ -102,14 +98,12 @@ end
def migrate_to_s3_all_sites
RailsMultisite::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"]
end
end
end
@@ -544,11 +538,9 @@ def sync_access_control(async: true, concurrency: 10)
.map do |upload|
Concurrent::Future.execute(executor:) do
RailsMultisite::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}"
end
end
end
diff --git a/lib/tasks/users.rake b/lib/tasks/users.rake
index 0b438d19b9a..d1447a9ccad 100644
--- a/lib/tasks/users.rake
+++ b/lib/tasks/users.rake
@@ -178,12 +178,10 @@ task "users:anonymize_all" => :environment do
system_user = Discourse.system_user
non_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
+ # skip
end
puts "", "#{total} users anonymized.", ""
diff --git a/lib/theme_settings_manager/string.rb b/lib/theme_settings_manager/string.rb
index 57650c8b283..db9770c14fb 100644
--- a/lib/theme_settings_manager/string.rb
+++ b/lib/theme_settings_manager/string.rb
@@ -6,10 +6,8 @@ class ThemeSettingsManager::String < ThemeSettingsManager
end
def json_schema
- begin
- JSON.parse(@opts[:json_schema])
- rescue StandardError
- false
- end
+ JSON.parse(@opts[:json_schema])
+ rescue StandardError
+ false
end
end
diff --git a/lib/topic_query/private_message_lists.rb b/lib/topic_query/private_message_lists.rb
index fe657a4a965..9c06ba82851 100644
--- a/lib/topic_query/private_message_lists.rb
+++ b/lib/topic_query/private_message_lists.rb
@@ -236,9 +236,7 @@ class TopicQuery
def 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).first
end
def user_first_unread_pm_at(user)
diff --git a/lib/topic_view.rb b/lib/topic_view.rb
index ad9ce02d46e..93e30c6e02d 100644
--- a/lib/topic_view.rb
+++ b/lib/topic_view.rb
@@ -245,15 +245,13 @@ class TopicView
return [] 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
+ end
return [] unless @post_user_badges
@@ -290,12 +288,10 @@ class TopicView
return 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))
end
end
@@ -310,10 +306,8 @@ class TopicView
def 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 + 1
end
end
@@ -572,11 +566,10 @@ class TopicView
def post_counts_by_user
@post_counts_by_user ||=
- begin
- if is_mega_topic?
- {}
- else
- sql = <<~SQL
+ if is_mega_topic?
+ {}
+ else
+ sql = <<~SQL
SELECT user_id, count(*) AS count_all
FROM posts
WHERE topic_id = :topic_id
@@ -589,14 +582,13 @@ class TopicView
LIMIT #{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),
+ )
+ ]
end
end
@@ -607,22 +599,20 @@ class TopicView
def 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 = <<~SQL
SELECT COUNT(DISTINCT user_id)
FROM posts
WHERE id IN (:post_ids)
AND user_id IS NOT NULL
SQL
- 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_i
end
+ else
+ participants.size
end
end
@@ -639,10 +629,7 @@ class TopicView
end
def topic_allowed_group_ids
- @topic_allowed_group_ids ||=
- begin
- @topic.allowed_groups.map(&:id)
- end
+ @topic_allowed_group_ids ||= @topic.allowed_groups.map(&:id)
end
def group_allowed_user_ids
@@ -654,24 +641,22 @@ class TopicView
def 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.new
end
end
@@ -845,12 +830,10 @@ class TopicView
def 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_ids
end
end
diff --git a/lib/upload_recovery.rb b/lib/upload_recovery.rb
index 7f2c52d6e60..6261d9ee9e3 100644
--- a/lib/upload_recovery.rb
+++ b/lib/upload_recovery.rb
@@ -11,43 +11,41 @@ class UploadRecovery
end
def 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)
end
end
end
- 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}"
end
private
@@ -95,11 +93,9 @@ class UploadRecovery
def 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.rb
index 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"))
end
def check_allowed_types(record, field)
diff --git a/lib/validators/regexp_list_validator.rb b/lib/validators/regexp_list_validator.rb
index 23ddfc39bf4..c1b18460108 100644
--- a/lib/validators/regexp_list_validator.rb
+++ b/lib/validators/regexp_list_validator.rb
@@ -8,13 +8,11 @@ class RegexpListValidator
value
.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
+ false
end
end
diff --git a/migrations/lib/converters/base/worker.rb b/migrations/lib/converters/base/worker.rb
index 41c2560624d..a424b5dacfa 100644
--- a/migrations/lib/converters/base/worker.rb
+++ b/migrations/lib/converters/base/worker.rb
@@ -53,21 +53,19 @@ module Migrations
fork_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.cleanup
end
end
diff --git a/migrations/lib/uploader/tasks/uploader.rb b/migrations/lib/uploader/tasks/uploader.rb
index a5153e5a487..f1edf655f4d 100644
--- a/migrations/lib/uploader/tasks/uploader.rb
+++ b/migrations/lib/uploader/tasks/uploader.rb
@@ -153,17 +153,15 @@ module Migrations
with_retries do
upload =
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
+ nil
end
if (upload_okay = upload.present? && upload.persisted? && upload.errors.blank?)
diff --git a/migrations/migrations.rb b/migrations/migrations.rb
index e45bd5eb681..9401e3c3350 100644
--- a/migrations/migrations.rb
+++ b/migrations/migrations.rb
@@ -25,13 +25,11 @@ module Migrations
rails_root = File.expand_path("..", __dir__)
# rubocop:disable Discourse/NoChdir
Dir.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
+ raise
end
# rubocop:enable Discourse/NoChdir
diff --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.rb
index 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!
end
def down
diff --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.rb
index 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 DiscourseAi
RateLimiter.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)
end
end
end
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/translation/translation_controller.rb
index 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 DiscourseAi
end
def 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"))
end
def 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.rb
index 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 Jobs
private
def 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")}",
+ )
end
end
end
diff --git a/plugins/discourse-ai/app/jobs/regular/generate_inferred_concepts.rb b/plugins/discourse-ai/app/jobs/regular/generate_inferred_concepts.rb
index 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 Jobs
manager = DiscourseAi::InferredConcepts::Manager.new
items.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")}",
+ )
end
end
diff --git a/plugins/discourse-ai/app/jobs/scheduled/categories_locale_detection_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/categories_locale_detection_backfill.rb
index 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 Jobs
return 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")}",
+ )
end
DiscourseAi::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.rb
index 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 Jobs
return 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")}",
+ )
end
DiscourseAi::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.rb
index 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 Jobs
return 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")}",
+ )
end
DiscourseAi::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.rb
index 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 Jobs
return 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")}",
+ )
end
DiscourseAi::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.rb
index 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::Base
end
def 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",
+ },
+ },
+ ]
end
end
diff --git a/plugins/discourse-ai/db/migrate/20240726164937_fix_ai_summaries_sequence.rb b/plugins/discourse-ai/db/migrate/20240726164937_fix_ai_summaries_sequence.rb
index 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 <<-SQL
SELECT
SETVAL (
'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 error
end
def down
diff --git a/plugins/discourse-ai/discourse_automation/llm_report.rb b/plugins/discourse-ai/discourse_automation/llm_report.rb
index 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: :boolean
script 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.backtrace
end
end
end
diff --git a/plugins/discourse-ai/evals/lib/llm_repository.rb b/plugins/discourse-ai/evals/lib/llm_repository.rb
index 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 DiscourseAi
def all_available_models
configs.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?
+ nil
end
end
diff --git a/plugins/discourse-ai/lib/agents/artifact_update_strategies/diff.rb b/plugins/discourse-ai/lib/agents/artifact_update_strategies/diff.rb
index 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 DiscourseAi
content = 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]}")
end
updated_content[section == :javascript ? :js : section] = content
end
diff --git a/plugins/discourse-ai/lib/agents/tool_runner.rb b/plugins/discourse-ai/lib/agents/tool_runner.rb
index 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 DiscourseAi
t =
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 }
+ break
end
- 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"
end
rval = 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.rb
index 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 DiscourseAi
end
def llm_user
- @llm_user ||=
- begin
- post&.user || @bot_user
- end
+ @llm_user ||= post&.user || @bot_user
end
def post
diff --git a/plugins/discourse-ai/lib/agents/tools/create_image.rb b/plugins/discourse-ai/lib/agents/tools/create_image.rb
index 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 DiscourseAi
errors = []
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 upload
else
- # 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.message
end
if uploads.empty?
diff --git a/plugins/discourse-ai/lib/agents/tools/image.rb b/plugins/discourse-ai/lib/agents/tools/image.rb
index 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 DiscourseAi
errors = []
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
+ }
end
end
- rescue => e
- Rails.logger.warn("Failed to generate image for prompt #{prompt}: #{e}")
- errors << e.message
end
+ rescue => e
+ Rails.logger.warn("Failed to generate image for prompt #{prompt}: #{e}")
+ errors << e.message
end
if 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.rb
index 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 DiscourseAi
def 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")
end
end
@@ -42,39 +40,37 @@ module DiscourseAi
tool_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.close
end
end
diff --git a/plugins/discourse-ai/lib/completions/cancel_manager.rb b/plugins/discourse-ai/lib/completions/cancel_manager.rb
index 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.call
end
- ensure
- @mutex.synchronize { @monitor_thread = nil }
+
+ @mutex.synchronize { cancel! if should_cancel }
+
+ break if cancelled?
end
+ ensure
+ @mutex.synchronize { @monitor_thread = nil }
end
end
end
@@ -97,11 +95,9 @@ module DiscourseAi
end
end
@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 cancelled
end
end
end
diff --git a/plugins/discourse-ai/lib/completions/endpoints/base.rb b/plugins/discourse-ai/lib/completions/endpoints/base.rb
index 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 DiscourseAi
return response_data
end
- 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) }
end
end
+
if xml_stripper
stripped = xml_stripper.finish
if stripped.present?
@@ -447,11 +446,9 @@ module DiscourseAi
private
def 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
+ payload
end
def track_failures(call_status)
diff --git a/plugins/discourse-ai/lib/utils/dns_srv.rb b/plugins/discourse-ai/lib/utils/dns_srv.rb
index 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 DiscourseAi
end
def 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
+ false
end
def 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.rb
index 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::PdfToImages
end
def 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_dir
end
end
diff --git a/plugins/discourse-ai/spec/lib/completions/cancel_manager_spec.rb b/plugins/discourse-ai/spec/lib/completions/cancel_manager_spec.rb
index 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 do
thread =
Thread.new do
loop 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
+ break
end
end
diff --git a/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb
index 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" do
end
it "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)
end
it "includes agent in selector when allow_personal_messages is enabled" do
diff --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.rb
index 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: "")
end
end
end
diff --git a/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb b/plugins/discourse-calendar/app/controllers/discourse_post_event/events_controller.rb
index 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 DiscoursePostEvent
raise 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
+ else
render json:
failed_json.merge(
errors: [I18n.t("discourse_post_event.errors.bulk_invite.error")],
),
status: :unprocessable_entity
end
+ rescue StandardError
+ render json:
+ failed_json.merge(
+ errors: [I18n.t("discourse_post_event.errors.bulk_invite.error")],
+ ),
+ status: :unprocessable_entity
end
end
diff --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.rb
index 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 do
context "when the user requesting the upload is admin" do
it "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!)
end
end
end
@@ -135,19 +131,17 @@ describe Jobs::ExportCsvFile do
before { 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!)
end
end
end
diff --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.rb
index 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 < ApplicationController
end
def 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
+ else
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
- else
- render json: { errors: [err.message] }, status: :unprocessable_entity
- end
end
end
@@ -121,54 +119,50 @@ class DiscourseChatIntegration::ChatController < ApplicationController
end
def 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_entity
end
def 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_entity
end
def destroy_channel
@@ -180,30 +174,26 @@ class DiscourseChatIntegration::ChatController < ApplicationController
end
def 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_entity
end
def 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_entity
end
def destroy_rule
diff --git a/plugins/discourse-data-explorer/plugin.rb b/plugins/discourse-data-explorer/plugin.rb
index 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}"
end
end
end
diff --git a/plugins/discourse-patreon/app/controllers/patreon/patreon_admin_controller.rb b/plugins/discourse-patreon/app/controllers/patreon/patreon_admin_controller.rb
index 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::AdminController
end
def is_number?(string)
- begin
- true if Float(string)
- rescue StandardError
- false
- end
+ true if Float(string)
+ rescue StandardError
+ false
end
def edit
@@ -65,12 +63,10 @@ class Patreon::PatreonAdminController < Admin::AdminController
end
def 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_error
end
def update_data
diff --git a/plugins/discourse-post-voting/extensions/topic_extension.rb b/plugins/discourse-post-voting/extensions/topic_extension.rb
index 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 PostVoting
def 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)
end
def answer_count
@@ -36,12 +34,7 @@ module PostVoting
def 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)
end
def last_commented_on
diff --git a/plugins/discourse-post-voting/plugin.rb b/plugins/discourse-post-voting/plugin.rb
index d56c56a8391..bd6eaf9951f 100644
--- a/plugins/discourse-post-voting/plugin.rb
+++ b/plugins/discourse-post-voting/plugin.rb
@@ -78,20 +78,19 @@ after_initialize do
add_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)
end
add_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)
end
TopicView.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.rb
index 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::PostExtension
end
def 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) }
end
end
diff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/coupons_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/coupons_controller.rb
index 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 DiscourseSubscriptions
requires_plugin PLUGIN_NAME
def 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.message
end
def create
diff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/plans_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/plans_controller.rb
index 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 DiscourseSubscriptions
requires_plugin PLUGIN_NAME
def 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.message
end
def 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.message
end
def 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.message
end
def 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.message
end
private
diff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/products_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/products_controller.rb
index 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 DiscourseSubscriptions
requires_plugin PLUGIN_NAME
def 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 = nil
end
+
+ render_json_dump products
+ rescue ::Stripe::InvalidRequestError => e
+ render_json_error e.message
end
def 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.message
end
def 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.message
end
def 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.message
end
def 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.message
end
private
diff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/subscriptions_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin/subscriptions_controller.rb
index 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 DiscourseSubscriptions
PAGE_LIMIT = 10
def 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] == false
end
- 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 = nil
end
+
+ render_json_dump subscriptions
+ rescue ::Stripe::InvalidRequestError => e
+ render_json_error e.message
end
def destroy
diff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/admin_controller.rb
index 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 DiscourseSubscriptions
end
def 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.message
end
end
end
diff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/subscribe_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/subscribe_controller.rb
index 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 DiscourseSubscriptions
requires_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.message
end
def contributors
@@ -264,16 +262,14 @@ module DiscourseSubscriptions
end
def 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.message
end
def metadata_user
diff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/payments_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/payments_controller.rb
index 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 DiscourseSubscriptions
requires_login
def 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_invoices
end
+ 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.message
end
private
diff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/subscriptions_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/user/subscriptions_controller.rb
index 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 DiscourseSubscriptions
requires_login
def 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))
+ end
end
+
+ render_json_dump subscriptions
+ rescue ::Stripe::InvalidRequestError => e
+ render_json_error e.message
end
def 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.message
end
def update
diff --git a/plugins/discourse-subscriptions/app/serializers/discourse_subscriptions/payment_serializer.rb b/plugins/discourse-subscriptions/app/serializers/discourse_subscriptions/payment_serializer.rb
index 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 DiscourseSubscriptions
private
def user
- begin
- User.find(object.user_id)
- rescue StandardError
- nil
- end
+ User.find(object.user_id)
+ rescue StandardError
+ nil
end
def currency_unit
diff --git a/plugins/discourse-subscriptions/app/services/discourse_subscriptions/campaign.rb b/plugins/discourse-subscriptions/app/services/discourse_subscriptions/campaign.rb
index 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 DiscourseSubscriptions
end
def 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
+ e
end
protected
diff --git a/plugins/discourse-subscriptions/plugin.rb b/plugins/discourse-subscriptions/plugin.rb
index fb8aae8f5b0..5dce15af784 100644
--- a/plugins/discourse-subscriptions/plugin.rb
+++ b/plugins/discourse-subscriptions/plugin.rb
@@ -78,14 +78,12 @@ after_initialize do
Discourse::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
+ false
end
end
diff --git a/plugins/discourse-templates/lib/tasks/discourse-templates.rake b/plugins/discourse-templates/lib/tasks/discourse-templates.rake
index 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 @@ end
def purge_old_data
puts "Removing canned replies data"
- begin
- ActiveRecord::Base.transaction do
- DB.exec <<~SQL
+ ActiveRecord::Base.transaction do
+ DB.exec <<~SQL
DELETE 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!"
end
end
diff --git a/script/biggest_objects.rb b/script/biggest_objects.rb
index 220fff3c00d..7585b3e666f 100644
--- a/script/biggest_objects.rb
+++ b/script/biggest_objects.rb
@@ -20,11 +20,9 @@ ObjectSpace.trace_object_allocations do
RailsMultisite::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
+ nil
end
end
end
diff --git a/script/boot_mem.rb b/script/boot_mem.rb
index 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
+ nil
end
end
.pretty_print
diff --git a/script/bulk_import/base.rb b/script/bulk_import/base.rb
index b368f821782..b953f26335f 100644
--- a/script/bulk_import/base.rb
+++ b/script/bulk_import/base.rb
@@ -2189,24 +2189,20 @@ class BulkImport::Base
begin
@raw_connection.copy_data(sql, @encoder) do
rows.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")
end
end
rescue => e
diff --git a/script/bulk_import/phpbb_postgresql.rb b/script/bulk_import/phpbb_postgresql.rb
index 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::Base
protected
def 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"
+ text
end
def add_default_smilies
diff --git a/script/bulk_import/uploads_importer.rb b/script/bulk_import/uploads_importer.rb
index 4b8eaa8d929..4dca236128a 100644
--- a/script/bulk_import/uploads_importer.rb
+++ b/script/bulk_import/uploads_importer.rb
@@ -217,17 +217,15 @@ module BulkImport
error_message = nil
upload =
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
+ nil
end
if (upload_okay = upload.present? && upload.persisted? && upload.errors.blank?)
diff --git a/script/cache_critical_dns b/script/cache_critical_dns
index 2e38583ee4b..6abab249d0a 100755
--- a/script/cache_critical_dns
+++ b/script/cache_critical_dns
@@ -186,12 +186,12 @@ class SRVName
targets = 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)
end
rescue Resolv::ResolvError, Resolv::ResolvTimeout
- end
+
end
end
end
diff --git a/script/db_timestamps_mover.rb b/script/db_timestamps_mover.rb
index fc92d54b19b..417e8954271 100644
--- a/script/db_timestamps_mover.rb
+++ b/script/db_timestamps_mover.rb
@@ -117,19 +117,15 @@ class TimestampsUpdater
end
def is_i?(string)
- begin
- true if Integer(string)
- rescue StandardError
- false
- end
+ true if Integer(string)
+rescue StandardError
+ false
end
def is_date?(string)
- begin
- true if Date.parse(string)
- rescue StandardError
- false
- end
+ true if Date.parse(string)
+rescue StandardError
+ false
end
def create_updater
diff --git a/script/discourse b/script/discourse
index 1e1c21a2368..e6189cc7d7d 100755
--- a/script/discourse
+++ b/script/discourse
@@ -366,7 +366,7 @@ class DiscourseCLI < Thor
end
def do_remap(from, to)
- begin
+
remap_options = {
verbose: true,
skip_max_length_violations: options[:skip_max_length_violations],
@@ -390,7 +390,7 @@ class DiscourseCLI < Thor
puts "Error: #{ex}"
puts "The remap has only been partially applied due to the error above. Please re-run the script again."
exit(1)
- end
+
end
end
diff --git a/script/import_scripts/answerhub.rb b/script/import_scripts/answerhub.rb
index a95d0c474d1..488c5d4e355 100644
--- a/script/import_scripts/answerhub.rb
+++ b/script/import_scripts/answerhub.rb
@@ -232,20 +232,18 @@ class ImportScripts::AnswerHub < ImportScripts::Base
created_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::Base
avatars = @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",
+ ).read
end
+ 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"]}"
end
end
diff --git a/script/import_scripts/base.rb b/script/import_scripts/base.rb
index c43cf9c4c0f..7656168cd24 100644
--- a/script/import_scripts/base.rb
+++ b/script/import_scripts/base.rb
@@ -217,25 +217,23 @@ class ImportScripts::Base
return 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}"
+ true
end
+ ensure
+ connection.exec("DROP TABLE import_ids") unless connection.nil?
end
end
diff --git a/script/import_scripts/drupal.rb b/script/import_scripts/drupal.rb
index 42b165c6880..5c0d2e222e6 100644
--- a/script/import_scripts/drupal.rb
+++ b/script/import_scripts/drupal.rb
@@ -408,17 +408,15 @@ class ImportScripts::Drupal < ImportScripts::Base
puts "", "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}"
end
end
@@ -471,35 +469,33 @@ class ImportScripts::Drupal < ImportScripts::Base
max = Post.count
Post.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.save
end
+ rescue StandardError
+ puts "", "Failed rewrite on post: #{post.id}"
+ ensure
+ print_status(current += 1, max)
end
end
@@ -508,14 +504,12 @@ class ImportScripts::Drupal < ImportScripts::Base
current = 0
max = User.count
User.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)
end
end
diff --git a/script/import_scripts/google_groups.rb b/script/import_scripts/google_groups.rb
index d6a095f5091..90ccc5f241e 100755
--- a/script/import_scripts/google_groups.rb
+++ b/script/import_scripts/google_groups.rb
@@ -39,33 +39,27 @@ MAX_GET_RETRIES = 5
MAX_FIND_RETRIES = 3
def 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_RETRIES
end
def 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_RETRIES
end
def 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_RETRIES
end
def base_url
diff --git a/script/import_scripts/jforum.rb b/script/import_scripts/jforum.rb
index fc407a425b8..c66e80b9db2 100644
--- a/script/import_scripts/jforum.rb
+++ b/script/import_scripts/jforum.rb
@@ -87,10 +87,7 @@ class ImportScripts::JForum < ImportScripts::Base
end
def user_fields
- @user_fields ||=
- begin
- UserField.all.index_by(&:name)
- end
+ @user_fields ||= UserField.all.index_by(&:name)
end
def user_custom_fields(row)
diff --git a/script/import_scripts/lithium.rb b/script/import_scripts/lithium.rb
index 2ece7668a63..b44bf6bc704 100644
--- a/script/import_scripts/lithium.rb
+++ b/script/import_scripts/lithium.rb
@@ -924,31 +924,29 @@ SQL
Post
.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.save
end
+ rescue PrettyText::JavaScriptError
+ puts "GOT A JS error on post: #{post.id}"
+ nil
+ ensure
+ print_status(current += 1, max)
end
SiteSetting.authorized_extensions = default_extensions
diff --git a/script/import_scripts/mbox/importer.rb b/script/import_scripts/mbox/importer.rb
index 6f8e60eb4fe..69edf2531ee 100644
--- a/script/import_scripts/mbox/importer.rb
+++ b/script/import_scripts/mbox/importer.rb
@@ -97,18 +97,16 @@ module ImportScripts::Mbox
next 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")
end
end
end
diff --git a/script/import_scripts/mbox/support/indexer.rb b/script/import_scripts/mbox/support/indexer.rb
index 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::Mbox
def 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_name
end
end
+ 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.inspect
end
end
diff --git a/script/import_scripts/modx.rb b/script/import_scripts/modx.rb
index 2beb481a7d9..de66bb4fd7a 100644
--- a/script/import_scripts/modx.rb
+++ b/script/import_scripts/modx.rb
@@ -490,17 +490,15 @@ FROM #{TABLE_PREFIX}discuss_users
max = Post.count
Post.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.save
end
+ rescue PrettyText::JavaScriptError
+ nil
+ ensure
+ print_status(current += 1, max)
end
end
diff --git a/script/import_scripts/mylittleforum.rb b/script/import_scripts/mylittleforum.rb
index fd797fef07d..6855bfc9104 100644
--- a/script/import_scripts/mylittleforum.rb
+++ b/script/import_scripts/mylittleforum.rb
@@ -826,13 +826,9 @@ class ImportScripts::MylittleforumSQL < ImportScripts::Base
end
def 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}")
end
def 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}")
end
end
diff --git a/script/import_scripts/nodebb/nodebb.rb b/script/import_scripts/nodebb/nodebb.rb
index 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::Base
start_time = Time.now
Post.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.save
end
+ ensure
+ print_status(current += 1, max, start_time)
end
end
diff --git a/script/import_scripts/phpbb3/database/database_3_1.rb b/script/import_scripts/phpbb3/database/database_3_1.rb
index 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::PhpBB3
def 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
+ ""
end
end
end
diff --git a/script/import_scripts/phpbb3/importer.rb b/script/import_scripts/phpbb3/importer.rb
index a4f64f82c46..1b42af3b0ff 100644
--- a/script/import_scripts/phpbb3/importer.rb
+++ b/script/import_scripts/phpbb3/importer.rb
@@ -83,12 +83,10 @@ module ImportScripts::PhpBB3
break if rows.size < 1
create_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)
end
end
end
@@ -104,12 +102,10 @@ module ImportScripts::PhpBB3
break if rows.size < 1
create_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)
end
end
end
@@ -119,34 +115,32 @@ module ImportScripts::PhpBB3
rows = @database.fetch_groups
create_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)
end
end
@@ -210,12 +204,10 @@ module ImportScripts::PhpBB3
break if rows.size < 1
create_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)
end
end
end
@@ -231,12 +223,10 @@ module ImportScripts::PhpBB3
break if rows.size < 1
create_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)
end
end
end
@@ -252,11 +242,9 @@ module ImportScripts::PhpBB3
break if rows.size < 1
create_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)
end
end
end
diff --git a/script/import_scripts/phpbb3/importers/user_importer.rb b/script/import_scripts/phpbb3/importers/user_importer.rb
index 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::PhpBB3
end
def user_fields
- @user_fields ||=
- begin
- UserField.all.index_by(&:name)
- end
+ @user_fields ||= UserField.all.index_by(&:name)
end
def 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]],
+ }
end
end
diff --git a/script/import_scripts/phpbb3/support/text_processor.rb b/script/import_scripts/phpbb3/support/text_processor.rb
index 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::PhpBB3
end
def process_post(raw, attachments)
- begin
- process_raw_text(raw, attachments)
- rescue StandardError
- raw
- end
+ process_raw_text(raw, attachments)
+ rescue StandardError
+ raw
end
def process_private_msg(raw, attachments)
- begin
- process_raw_text(raw, attachments)
- rescue StandardError
- raw
- end
+ process_raw_text(raw, attachments)
+ rescue StandardError
+ raw
end
protected
@@ -100,12 +96,10 @@ module ImportScripts::PhpBB3
end
def 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"
+ text
end
def process_smilies(text)
diff --git a/script/import_scripts/question2answer.rb b/script/import_scripts/question2answer.rb
index 8a0170a9d71..f8b84477598 100644
--- a/script/import_scripts/question2answer.rb
+++ b/script/import_scripts/question2answer.rb
@@ -284,16 +284,14 @@ class ImportScripts::Question2Answer < ImportScripts::Base
puts "", "importing best answers..."
ans = mysql_query("select postid, selchildid from qa_posts where selchildid is not null").to_a
ans.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}"
end
end
@@ -322,17 +320,15 @@ class ImportScripts::Question2Answer < ImportScripts::Base
max = Post.count
Post.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.save
end
+ rescue PrettyText::JavaScriptError
+ nil
+ ensure
+ print_status(current += 1, max)
end
end
diff --git a/script/import_scripts/smf2.rb b/script/import_scripts/smf2.rb
index 93d324de916..a3081a96512 100644
--- a/script/import_scripts/smf2.rb
+++ b/script/import_scripts/smf2.rb
@@ -260,14 +260,12 @@ class ImportScripts::Smf2 < ImportScripts::Base
ORDER BY id_attach ASC
SQL
attachments.map! do |a|
- begin
- import_attachment(post, a)
- rescue StandardError
- (
- puts $!
- nil
- )
- end
+ import_attachment(post, a)
+ rescue StandardError
+ (
+ puts $!
+ nil
+ )
end
begin
post[:raw] = convert_message_body(message[:body], attachments, ignore_quotes: ignore_quotes)
diff --git a/script/import_scripts/vbulletin.rb b/script/import_scripts/vbulletin.rb
index e49f5f0e9ac..af317e53fe4 100644
--- a/script/import_scripts/vbulletin.rb
+++ b/script/import_scripts/vbulletin.rb
@@ -186,24 +186,22 @@ class ImportScripts::VBulletin < ImportScripts::Base
puts "", "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 <<~SQL
INSERT 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")
end
Group.reset_all_counters!
@@ -738,18 +736,16 @@ class ImportScripts::VBulletin < ImportScripts::Base
max = Post.count
Post.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.save
end
+ rescue PrettyText::JavaScriptError
+ nil
+ ensure
+ print_status(current += 1, max)
end
end
diff --git a/script/import_scripts/vbulletin3.rb b/script/import_scripts/vbulletin3.rb
index 074efce8fb6..c2ab07eedf2 100644
--- a/script/import_scripts/vbulletin3.rb
+++ b/script/import_scripts/vbulletin3.rb
@@ -364,26 +364,24 @@ EOM
puts "", "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 <<~SQL
INSERT 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")
end
end
@@ -1337,18 +1335,16 @@ LEFT OUTER JOIN #{TABLE_PREFIX}avatar a ON a.avatarid = u.avatarid
start = Time.now
Post.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.save
end
+ rescue PrettyText::JavaScriptError
+ nil
+ ensure
+ print_status(current += 1, max, start)
end
end
diff --git a/script/import_scripts/vbulletin5.rb b/script/import_scripts/vbulletin5.rb
index 147f20d0bb1..e0b35acc09b 100644
--- a/script/import_scripts/vbulletin5.rb
+++ b/script/import_scripts/vbulletin5.rb
@@ -477,17 +477,15 @@ class ImportScripts::VBulletin < ImportScripts::Base
max = Post.count
Post.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.save
end
+ rescue PrettyText::JavaScriptError
+ nil
+ ensure
+ print_status(current += 1, max)
end
end
diff --git a/script/import_scripts/zendesk_api.rb b/script/import_scripts/zendesk_api.rb
index 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::Base
retry_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 += 1
end
end
diff --git a/script/local_minio_s3.rb b/script/local_minio_s3.rb
index 18bd52f7c13..f2b5de3e2e9 100755
--- a/script/local_minio_s3.rb
+++ b/script/local_minio_s3.rb
@@ -5,17 +5,15 @@ require "minio_runner"
class ExecuteLocalMinioS3
def 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
+ raise
end
def start_minio
diff --git a/script/memory-analysis b/script/memory-analysis
index 84e47676aa3..8159e4fe054 100755
--- a/script/memory-analysis
+++ b/script/memory-analysis
@@ -91,11 +91,10 @@ class Stats
def thread_class
@thread_class ||=
- begin
- @classes.find do |addr, n|
+ @classes.find do |addr, n|
n == "Thread"
end.first
- end
+
end
def detect_threads(line)
diff --git a/script/mwrap_sidekiq b/script/mwrap_sidekiq
index 8c2a73a5b7b..581385077da 100755
--- a/script/mwrap_sidekiq
+++ b/script/mwrap_sidekiq
@@ -84,7 +84,7 @@ def mwrap_log
end
Thread.new do
- begin
+
puts "Starting Logging Thread"
path = "/tmp/mwrap_#{Process.pid}"
`mkdir -p #{path}`
@@ -99,7 +99,7 @@ Thread.new do
rescue => e
STDERR.puts "ERROR crashed logger #{e}"
STDERR.puts e.backtrace
- end
+
end
Thread.new do
diff --git a/script/profile_db_generator.rb b/script/profile_db_generator.rb
index 7631754cecc..e3a46439880 100644
--- a/script/profile_db_generator.rb
+++ b/script/profile_db_generator.rb
@@ -22,9 +22,7 @@ def unbundled_require(gem)
spec.activate
end
- begin
- require gem
- end
+ require gem
end
def sentence
diff --git a/script/require_profiler.rb b/script/require_profiler.rb
index b8f3437efb6..328a7e1767a 100644
--- a/script/require_profiler.rb
+++ b/script/require_profiler.rb
@@ -127,11 +127,9 @@ end
RequireProfiler.profile do
Bundler.definition.dependencies.each do |dep|
- begin
- require dep.name
- rescue Exception
- # don't care
- end
+ require dep.name
+ rescue Exception
+ # don't care
end
end
diff --git a/script/test_mem.rb b/script/test_mem.rb
index 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
+ nil
end
# router warm up
diff --git a/spec/jobs/about_stats_spec.rb b/spec/jobs/about_stats_spec.rb
index 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 do
it "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)
end
end
diff --git a/spec/jobs/bookmark_reminder_notifications_spec.rb b/spec/jobs/bookmark_reminder_notifications_spec.rb
index 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 do
context "when the number of notifications exceed max_reminder_notifications_per_run" do
it "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)
end
end
diff --git a/spec/jobs/clean_up_uploads_spec.rb b/spec/jobs/clean_up_uploads_spec.rb
index 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 do
end
it "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_provider
end
it "does not clean up selectable avatars" do
diff --git a/spec/lib/discourse_event_spec.rb b/spec/lib/discourse_event_spec.rb
index b476011a535..9c55dc1b33a 100644
--- a/spec/lib/discourse_event_spec.rb
+++ b/spec/lib/discourse_event_spec.rb
@@ -3,13 +3,11 @@
RSpec.describe DiscourseEvent do
describe "#events" do
it "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)
end
describe "key value" do
@@ -99,17 +97,15 @@ RSpec.describe DiscourseEvent do
end
it "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)
end
end
diff --git a/spec/lib/distributed_mutex_spec.rb b/spec/lib/distributed_mutex_spec.rb
index f75a0b75f17..b1ba62cf505 100644
--- a/spec/lib/distributed_mutex_spec.rb
+++ b/spec/lib/distributed_mutex_spec.rb
@@ -93,22 +93,20 @@ RSpec.describe DistributedMutex do
3.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 = false
end
- rescue Redis::ConnectionError
end
+ rescue Redis::ConnectionError
end
end
end
diff --git a/spec/lib/file_helper_spec.rb b/spec/lib/file_helper_spec.rb
index 7957521ac4a..e5b74e125e4 100644
--- a/spec/lib/file_helper_spec.rb
+++ b/spec/lib/file_helper_spec.rb
@@ -17,17 +17,15 @@ RSpec.describe FileHelper do
stub_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")
+ raise
end.to raise_error(OpenURI::HTTPError, "404 Error")
end
@@ -73,45 +71,39 @@ RSpec.describe FileHelper do
stub_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")
+ raise
end.to raise_error(OpenURI::HTTPError)
end
it "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&.unlink
end
it "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&.unlink
end
describe "when max_file_size is exceeded" do
@@ -127,20 +119,18 @@ RSpec.describe FileHelper do
end
it "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&.unlink
end
end
@@ -148,16 +138,14 @@ RSpec.describe FileHelper do
let(: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&.unlink
end
end
end
diff --git a/spec/lib/file_store/local_store_spec.rb b/spec/lib/file_store/local_store_spec.rb
index 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 do
end
it "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) }
end
end
describe "#remove_optimized_image" do
it "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) }
end
end
diff --git a/spec/lib/guardian_spec.rb b/spec/lib/guardian_spec.rb
index c4299edc742..343ba1ab098 100644
--- a/spec/lib/guardian_spec.rb
+++ b/spec/lib/guardian_spec.rb
@@ -1869,12 +1869,10 @@ RSpec.describe Guardian do
end
it "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)
end
end
@@ -1925,12 +1923,10 @@ RSpec.describe Guardian do
end
it "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)
end
end
diff --git a/spec/lib/migration/column_dropper_spec.rb b/spec/lib/migration/column_dropper_spec.rb
index 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 do
end
it "should prevent updates to the readonly column" do
- begin
- DB.exec <<~SQL
+ DB.exec <<~SQL
UPDATE #{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) }
end
it "should allow updates to the other columns" do
diff --git a/spec/lib/migration/safe_migrate_spec.rb b/spec/lib/migration/safe_migrate_spec.rb
index 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 do
error = nil
capture_stdout do
- begin
- migrate_up(path)
- rescue StandardError => e
- error = e
- end
+ migrate_up(path)
+ rescue StandardError => e
+ error = e
end
expect(error.cause.cause.message).to include(
@@ -99,11 +97,9 @@ RSpec.describe Migration::SafeMigrate do
error = nil
capture_stdout do
- begin
- migrate_up(path)
- rescue StandardError => e
- error = e
- end
+ migrate_up(path)
+ rescue StandardError => e
+ error = e
end
expect(error.cause.cause.message).to include(
diff --git a/spec/lib/migration/table_dropper_spec.rb b/spec/lib/migration/table_dropper_spec.rb
index 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 do
end
it "should prevent insertions to the table" do
- begin
- DB.exec <<~SQL
+ DB.exec <<~SQL
INSERT 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) }
end
end
end
diff --git a/spec/lib/post_destroyer_spec.rb b/spec/lib/post_destroyer_spec.rb
index 3fcd3c7229a..fabe31a8d3e 100644
--- a/spec/lib/post_destroyer_spec.rb
+++ b/spec/lib/post_destroyer_spec.rb
@@ -420,55 +420,53 @@ RSpec.describe PostDestroyer do
describe "basic destroying" do
it "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 += 1
end
+
+ 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)
end
it "maintains history when a user destroys a hidden post" do
diff --git a/spec/lib/pretty_text_spec.rb b/spec/lib/pretty_text_spec.rb
index f410a7d50bc..44a95670406 100644
--- a/spec/lib/pretty_text_spec.rb
+++ b/spec/lib/pretty_text_spec.rb
@@ -704,14 +704,12 @@ RSpec.describe PrettyText do
end
it "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.flushdb
end
it "strips out unicode bidirectional (bidi) override characters and replaces with a highlighted span" do
diff --git a/spec/lib/search_spec.rb b/spec/lib/search_spec.rb
index 6191893f50e..f55a99f04f6 100644
--- a/spec/lib/search_spec.rb
+++ b/spec/lib/search_spec.rb
@@ -2130,25 +2130,23 @@ RSpec.describe Search do
end
it "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!
end
end
end
diff --git a/spec/lib/upload_creator_spec.rb b/spec/lib/upload_creator_spec.rb
index 259a9452669..d4b8dccf8cc 100644
--- a/spec/lib/upload_creator_spec.rb
+++ b/spec/lib/upload_creator_spec.rb
@@ -647,16 +647,14 @@ RSpec.describe UploadCreator do
end
it "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.unlink
end
end
diff --git a/spec/lib/url_helper_spec.rb b/spec/lib/url_helper_spec.rb
index c4b5fdadd12..2d29593db6d 100644
--- a/spec/lib/url_helper_spec.rb
+++ b/spec/lib/url_helper_spec.rb
@@ -42,18 +42,16 @@ RSpec.describe UrlHelper do
describe "#absolute" do
it "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 = nil
end
it "does not change non-relative url" do
diff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rb
index e23bd4fbd84..df97287108a 100644
--- a/spec/models/group_spec.rb
+++ b/spec/models/group_spec.rb
@@ -447,33 +447,29 @@ RSpec.describe Group do
end
it "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"))
end
it "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"))
end
it "does not use the localized name if name has already been taken when switching to a the english locale" do
diff --git a/spec/models/post_mover_spec.rb b/spec/models/post_mover_spec.rb
index a57887de033..be6fe40516f 100644
--- a/spec/models/post_mover_spec.rb
+++ b/spec/models/post_mover_spec.rb
@@ -3354,65 +3354,57 @@ RSpec.describe PostMover do
end
it "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"
end
it "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"
end
it "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"
end
it "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"
end
end
end
diff --git a/spec/models/topic_user_spec.rb b/spec/models/topic_user_spec.rb
index c69901be854..5950d2fda81 100644
--- a/spec/models/topic_user_spec.rb
+++ b/spec/models/topic_user_spec.rb
@@ -571,31 +571,29 @@ RSpec.describe TopicUser do
end
it "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)
end
end
diff --git a/spec/models/upload_spec.rb b/spec/models/upload_spec.rb
index e0f65414cc6..80d45fd8c6e 100644
--- a/spec/models/upload_spec.rb
+++ b/spec/models/upload_spec.rb
@@ -333,14 +333,12 @@ RSpec.describe Upload do
end
it "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_host
end
it "should return the right upload when using the full URL" do
@@ -393,17 +391,15 @@ RSpec.describe Upload do
end
it "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_host
end
end
end
@@ -436,16 +432,14 @@ RSpec.describe Upload do
end
it "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_host
end
it "works with full URLs" do
diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb
index a06a69474d0..3ba9976837b 100644
--- a/spec/rails_helper.rb
+++ b/spec/rails_helper.rb
@@ -45,16 +45,14 @@ class RspecErrorTracker
end
def 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 e
end
end
diff --git a/spec/requests/admin/backups_controller_spec.rb b/spec/requests/admin/backups_controller_spec.rb
index 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 do
context "with json format" do
it "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)
end
end
end
@@ -206,29 +204,25 @@ RSpec.describe Admin::BackupsController do
before { 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/)
end
it "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"))
end
it "returns 404 when the backup does not exist" do
@@ -248,20 +242,16 @@ RSpec.describe Admin::BackupsController do
shared_examples "backup inaccessible" do
it "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/)
end
end
@@ -283,18 +273,16 @@ RSpec.describe Admin::BackupsController do
before { 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)
end
it "doesn't remove the backup if not found" do
@@ -322,19 +310,17 @@ RSpec.describe Admin::BackupsController do
shared_examples "backup deletion not allowed" do
it "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)
end
end
diff --git a/spec/requests/api/site_spec.rb b/spec/requests/api/site_spec.rb
index 2e1500fe9a1..41c04f6ad17 100644
--- a/spec/requests/api/site_spec.rb
+++ b/spec/requests/api/site_spec.rb
@@ -21,19 +21,17 @@ RSpec.describe "site" do
produces "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_fields
end
end
end
diff --git a/spec/requests/static_controller_spec.rb b/spec/requests/static_controller_spec.rb
index d80eea5fe76..c7491c885bb 100644
--- a/spec/requests/static_controller_spec.rb
+++ b/spec/requests/static_controller_spec.rb
@@ -69,37 +69,33 @@ RSpec.describe StaticController do
let(: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)
end
it "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)
end
context "with fallback_assets_path" do
diff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rb
index 0a8901cc215..291cca31e8f 100644
--- a/spec/requests/topics_controller_spec.rb
+++ b/spec/requests/topics_controller_spec.rb
@@ -393,28 +393,26 @@ RSpec.describe TopicsController do
end
it "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)
end
end
diff --git a/spec/support/dom_matcher.rb b/spec/support/dom_matcher.rb
index 08a874f6b6f..ad64bbdc934 100644
--- a/spec/support/dom_matcher.rb
+++ b/spec/support/dom_matcher.rb
@@ -3,11 +3,9 @@ include Rails::Dom::Testing::Assertions::DomAssertions
RSpec::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
+ false
end
failure_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.rb
index b8108eaa463..cd25775f999 100644
--- a/spec/system/page_objects/cdp.rb
+++ b/spec/system/page_objects/cdp.rb
@@ -71,91 +71,85 @@ module PageObjects
def with_network_disconnected
page.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,
+ },
+ )
end
end
def with_slow_download
page.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,
+ },
+ )
end
end
def with_slow_upload
page.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,
+ },
+ )
end
end
end
diff --git a/spec/system/user_page/user_preferences_account_spec.rb b/spec/system/user_page/user_preferences_account_spec.rb
index 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" do
end
it "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?
+ true
end
- .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!
end
end
end