From ed570050c62115cfbcca8cfcd0de891b729f3e5c Mon Sep 17 00:00:00 2001 From: Nick Schonning Date: Mon, 6 Feb 2023 21:44:36 -0500 Subject: Autofix Rails/EagerEvaluationLogMessage (#23429) * Autofix Rails/EagerEvaluationLogMessage * Update spec for debug block syntax --- app/lib/activitypub/activity/create.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'app/lib/activitypub/activity/create.rb') diff --git a/app/lib/activitypub/activity/create.rb b/app/lib/activitypub/activity/create.rb index b15e66ca2..cfad62a6b 100644 --- a/app/lib/activitypub/activity/create.rb +++ b/app/lib/activitypub/activity/create.rb @@ -285,7 +285,7 @@ class ActivityPub::Activity::Create < ActivityPub::Activity media_attachments rescue Addressable::URI::InvalidURIError => e - Rails.logger.debug "Invalid URL in attachment: #{e}" + Rails.logger.debug { "Invalid URL in attachment: #{e}" } media_attachments end -- cgit From 0c9eac80d887cdf7f1efa582b21006248d2f83eb Mon Sep 17 00:00:00 2001 From: Claire Date: Fri, 10 Feb 2023 22:16:37 +0100 Subject: Fix unbounded recursion in post discovery (#23506) * Add a limit to how many posts can get fetched as a result of a single request * Add tests * Always pass `request_id` when processing `Announce` activities --------- Co-authored-by: nametoolong --- app/lib/activitypub/activity.rb | 7 +- app/lib/activitypub/activity/create.rb | 6 +- .../activitypub/fetch_remote_status_service.rb | 13 ++- app/services/activitypub/fetch_replies_service.rb | 4 +- app/services/fetch_remote_status_service.rb | 4 +- app/services/resolve_url_service.rb | 2 +- app/workers/activitypub/fetch_replies_worker.rb | 4 +- app/workers/fetch_reply_worker.rb | 4 +- app/workers/thread_resolve_worker.rb | 4 +- spec/lib/activitypub/activity/add_spec.rb | 4 +- .../fetch_remote_status_service_spec.rb | 94 ++++++++++++++++++++++ spec/services/fetch_remote_status_service_spec.rb | 2 +- 12 files changed, 126 insertions(+), 22 deletions(-) (limited to 'app/lib/activitypub/activity/create.rb') diff --git a/app/lib/activitypub/activity.rb b/app/lib/activitypub/activity.rb index f4c67cccd..900428e92 100644 --- a/app/lib/activitypub/activity.rb +++ b/app/lib/activitypub/activity.rb @@ -106,7 +106,8 @@ class ActivityPub::Activity actor_id = value_or_id(first_of_value(@object['attributedTo'])) if actor_id == @account.uri - return ActivityPub::Activity.factory({ 'type' => 'Create', 'actor' => actor_id, 'object' => @object }, @account).perform + virtual_object = { 'type' => 'Create', 'actor' => actor_id, 'object' => @object } + return ActivityPub::Activity.factory(virtual_object, @account, request_id: @options[:request_id]).perform end end @@ -152,9 +153,9 @@ class ActivityPub::Activity def fetch_remote_original_status if object_uri.start_with?('http') return if ActivityPub::TagManager.instance.local_uri?(object_uri) - ActivityPub::FetchRemoteStatusService.new.call(object_uri, id: true, on_behalf_of: @account.followers.local.first) + ActivityPub::FetchRemoteStatusService.new.call(object_uri, id: true, on_behalf_of: @account.followers.local.first, request_id: @options[:request_id]) elsif @object['url'].present? - ::FetchRemoteStatusService.new.call(@object['url']) + ::FetchRemoteStatusService.new.call(@object['url'], request_id: @options[:request_id]) end end diff --git a/app/lib/activitypub/activity/create.rb b/app/lib/activitypub/activity/create.rb index cfad62a6b..487b65223 100644 --- a/app/lib/activitypub/activity/create.rb +++ b/app/lib/activitypub/activity/create.rb @@ -327,18 +327,18 @@ class ActivityPub::Activity::Create < ActivityPub::Activity def resolve_thread(status) return unless status.reply? && status.thread.nil? && Request.valid_url?(in_reply_to_uri) - ThreadResolveWorker.perform_async(status.id, in_reply_to_uri) + ThreadResolveWorker.perform_async(status.id, in_reply_to_uri, { 'request_id' => @options[:request_id]}) end def fetch_replies(status) collection = @object['replies'] return if collection.nil? - replies = ActivityPub::FetchRepliesService.new.call(status, collection, false) + replies = ActivityPub::FetchRepliesService.new.call(status, collection, allow_synchronous_requests: false, request_id: @options[:request_id]) return unless replies.nil? uri = value_or_id(collection) - ActivityPub::FetchRepliesWorker.perform_async(status.id, uri) unless uri.nil? + ActivityPub::FetchRepliesWorker.perform_async(status.id, uri, { 'request_id' => @options[:request_id]}) unless uri.nil? end def conversation_from_uri(uri) diff --git a/app/services/activitypub/fetch_remote_status_service.rb b/app/services/activitypub/fetch_remote_status_service.rb index 21b9242f8..936737bf6 100644 --- a/app/services/activitypub/fetch_remote_status_service.rb +++ b/app/services/activitypub/fetch_remote_status_service.rb @@ -2,10 +2,13 @@ class ActivityPub::FetchRemoteStatusService < BaseService include JsonLdHelper + include Redisable + + DISCOVERIES_PER_REQUEST = 1000 # Should be called when uri has already been checked for locality def call(uri, id: true, prefetched_body: nil, on_behalf_of: nil, expected_actor_uri: nil, request_id: nil) - @request_id = request_id + @request_id = request_id || "#{Time.now.utc.to_i}-status-#{uri}" @json = begin if prefetched_body.nil? fetch_resource(uri, id, on_behalf_of) @@ -42,7 +45,13 @@ class ActivityPub::FetchRemoteStatusService < BaseService # activity as an update rather than create activity_json['type'] = 'Update' if equals_or_includes_any?(activity_json['type'], %w(Create)) && Status.where(uri: object_uri, account_id: actor.id).exists? - ActivityPub::Activity.factory(activity_json, actor, request_id: request_id).perform + with_redis do |redis| + discoveries = redis.incr("status_discovery_per_request:#{@request_id}") + redis.expire("status_discovery_per_request:#{@request_id}", 5.minutes.seconds) + return nil if discoveries > DISCOVERIES_PER_REQUEST + end + + ActivityPub::Activity.factory(activity_json, actor, request_id: @request_id).perform end private diff --git a/app/services/activitypub/fetch_replies_service.rb b/app/services/activitypub/fetch_replies_service.rb index 8cb309e52..18a27e851 100644 --- a/app/services/activitypub/fetch_replies_service.rb +++ b/app/services/activitypub/fetch_replies_service.rb @@ -3,14 +3,14 @@ class ActivityPub::FetchRepliesService < BaseService include JsonLdHelper - def call(parent_status, collection_or_uri, allow_synchronous_requests = true) + def call(parent_status, collection_or_uri, allow_synchronous_requests: true, request_id: nil) @account = parent_status.account @allow_synchronous_requests = allow_synchronous_requests @items = collection_items(collection_or_uri) return if @items.nil? - FetchReplyWorker.push_bulk(filtered_replies) + FetchReplyWorker.push_bulk(filtered_replies) { |reply_uri| [reply_uri, { 'request_id' => request_id}] } @items end diff --git a/app/services/fetch_remote_status_service.rb b/app/services/fetch_remote_status_service.rb index eafde4d4a..08c2d24ba 100644 --- a/app/services/fetch_remote_status_service.rb +++ b/app/services/fetch_remote_status_service.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class FetchRemoteStatusService < BaseService - def call(url, prefetched_body = nil) + def call(url, prefetched_body: nil, request_id: nil) if prefetched_body.nil? resource_url, resource_options = FetchResourceService.new.call(url) else @@ -9,6 +9,6 @@ class FetchRemoteStatusService < BaseService resource_options = { prefetched_body: prefetched_body } end - ActivityPub::FetchRemoteStatusService.new.call(resource_url, **resource_options) unless resource_url.nil? + ActivityPub::FetchRemoteStatusService.new.call(resource_url, **resource_options.merge(request_id: request_id)) unless resource_url.nil? end end diff --git a/app/services/resolve_url_service.rb b/app/services/resolve_url_service.rb index 52f35daf3..d8e795f3b 100644 --- a/app/services/resolve_url_service.rb +++ b/app/services/resolve_url_service.rb @@ -25,7 +25,7 @@ class ResolveURLService < BaseService if equals_or_includes_any?(type, ActivityPub::FetchRemoteActorService::SUPPORTED_TYPES) ActivityPub::FetchRemoteActorService.new.call(resource_url, prefetched_body: body) elsif equals_or_includes_any?(type, ActivityPub::Activity::Create::SUPPORTED_TYPES + ActivityPub::Activity::Create::CONVERTED_TYPES) - status = FetchRemoteStatusService.new.call(resource_url, body) + status = FetchRemoteStatusService.new.call(resource_url, prefetched_body: body) authorize_with @on_behalf_of, status, :show? unless status.nil? status end diff --git a/app/workers/activitypub/fetch_replies_worker.rb b/app/workers/activitypub/fetch_replies_worker.rb index 54d98f228..d72bad745 100644 --- a/app/workers/activitypub/fetch_replies_worker.rb +++ b/app/workers/activitypub/fetch_replies_worker.rb @@ -6,8 +6,8 @@ class ActivityPub::FetchRepliesWorker sidekiq_options queue: 'pull', retry: 3 - def perform(parent_status_id, replies_uri) - ActivityPub::FetchRepliesService.new.call(Status.find(parent_status_id), replies_uri) + def perform(parent_status_id, replies_uri, options = {}) + ActivityPub::FetchRepliesService.new.call(Status.find(parent_status_id), replies_uri, **options.deep_symbolize_keys) rescue ActiveRecord::RecordNotFound true end diff --git a/app/workers/fetch_reply_worker.rb b/app/workers/fetch_reply_worker.rb index f7aa25e81..68a7414be 100644 --- a/app/workers/fetch_reply_worker.rb +++ b/app/workers/fetch_reply_worker.rb @@ -6,7 +6,7 @@ class FetchReplyWorker sidekiq_options queue: 'pull', retry: 3 - def perform(child_url) - FetchRemoteStatusService.new.call(child_url) + def perform(child_url, options = {}) + FetchRemoteStatusService.new.call(child_url, **options.deep_symbolize_keys) end end diff --git a/app/workers/thread_resolve_worker.rb b/app/workers/thread_resolve_worker.rb index 1b77dfdd9..3206c45f6 100644 --- a/app/workers/thread_resolve_worker.rb +++ b/app/workers/thread_resolve_worker.rb @@ -6,9 +6,9 @@ class ThreadResolveWorker sidekiq_options queue: 'pull', retry: 3 - def perform(child_status_id, parent_url) + def perform(child_status_id, parent_url, options = {}) child_status = Status.find(child_status_id) - parent_status = FetchRemoteStatusService.new.call(parent_url) + parent_status = FetchRemoteStatusService.new.call(parent_url, **options.deep_symbolize_keys) return if parent_status.nil? diff --git a/spec/lib/activitypub/activity/add_spec.rb b/spec/lib/activitypub/activity/add_spec.rb index e6408b610..0b08e2924 100644 --- a/spec/lib/activitypub/activity/add_spec.rb +++ b/spec/lib/activitypub/activity/add_spec.rb @@ -48,7 +48,7 @@ RSpec.describe ActivityPub::Activity::Add do end it 'fetches the status and pins it' do - allow(service_stub).to receive(:call) do |uri, id: true, on_behalf_of: nil| + allow(service_stub).to receive(:call) do |uri, id: true, on_behalf_of: nil, request_id: nil| expect(uri).to eq 'https://example.com/unknown' expect(id).to eq true expect(on_behalf_of&.following?(sender)).to eq true @@ -62,7 +62,7 @@ RSpec.describe ActivityPub::Activity::Add do context 'when there is no local follower' do it 'tries to fetch the status' do - allow(service_stub).to receive(:call) do |uri, id: true, on_behalf_of: nil| + allow(service_stub).to receive(:call) do |uri, id: true, on_behalf_of: nil, request_id: nil| expect(uri).to eq 'https://example.com/unknown' expect(id).to eq true expect(on_behalf_of).to eq nil diff --git a/spec/services/activitypub/fetch_remote_status_service_spec.rb b/spec/services/activitypub/fetch_remote_status_service_spec.rb index 7359ca0b4..a81dcad81 100644 --- a/spec/services/activitypub/fetch_remote_status_service_spec.rb +++ b/spec/services/activitypub/fetch_remote_status_service_spec.rb @@ -223,4 +223,98 @@ RSpec.describe ActivityPub::FetchRemoteStatusService, type: :service do end end end + + context 'statuses referencing other statuses' do + before do + stub_const 'ActivityPub::FetchRemoteStatusService::DISCOVERIES_PER_REQUEST', 5 + end + + context 'using inReplyTo' do + let(:object) do + { + '@context': 'https://www.w3.org/ns/activitystreams', + id: "https://foo.bar/@foo/1", + type: 'Note', + content: 'Lorem ipsum', + inReplyTo: 'https://foo.bar/@foo/2', + attributedTo: ActivityPub::TagManager.instance.uri_for(sender), + } + end + + before do + 8.times do |i| + status_json = { + '@context': 'https://www.w3.org/ns/activitystreams', + id: "https://foo.bar/@foo/#{i}", + type: 'Note', + content: 'Lorem ipsum', + inReplyTo: "https://foo.bar/@foo/#{i + 1}", + attributedTo: ActivityPub::TagManager.instance.uri_for(sender), + to: 'as:Public', + }.with_indifferent_access + stub_request(:get, "https://foo.bar/@foo/#{i}").to_return(status: 200, body: status_json.to_json, headers: { 'Content-Type': 'application/activity+json' }) + end + end + + it 'creates at least some statuses' do + expect { subject.call(object[:id], prefetched_body: Oj.dump(object)) }.to change { sender.statuses.count }.by_at_least(2) + end + + it 'creates no more account than the limit allows' do + expect { subject.call(object[:id], prefetched_body: Oj.dump(object)) }.to change { sender.statuses.count }.by_at_most(5) + end + end + + context 'using replies' do + let(:object) do + { + '@context': 'https://www.w3.org/ns/activitystreams', + id: "https://foo.bar/@foo/1", + type: 'Note', + content: 'Lorem ipsum', + replies: { + type: 'Collection', + id: 'https://foo.bar/@foo/1/replies', + first: { + type: 'CollectionPage', + partOf: 'https://foo.bar/@foo/1/replies', + items: ['https://foo.bar/@foo/2'], + }, + }, + attributedTo: ActivityPub::TagManager.instance.uri_for(sender), + } + end + + before do + 8.times do |i| + status_json = { + '@context': 'https://www.w3.org/ns/activitystreams', + id: "https://foo.bar/@foo/#{i}", + type: 'Note', + content: 'Lorem ipsum', + replies: { + type: 'Collection', + id: "https://foo.bar/@foo/#{i}/replies", + first: { + type: 'CollectionPage', + partOf: "https://foo.bar/@foo/#{i}/replies", + items: ["https://foo.bar/@foo/#{i+1}"], + }, + }, + attributedTo: ActivityPub::TagManager.instance.uri_for(sender), + to: 'as:Public', + }.with_indifferent_access + stub_request(:get, "https://foo.bar/@foo/#{i}").to_return(status: 200, body: status_json.to_json, headers: { 'Content-Type': 'application/activity+json' }) + end + end + + it 'creates at least some statuses' do + expect { subject.call(object[:id], prefetched_body: Oj.dump(object)) }.to change { sender.statuses.count }.by_at_least(2) + end + + it 'creates no more account than the limit allows' do + expect { subject.call(object[:id], prefetched_body: Oj.dump(object)) }.to change { sender.statuses.count }.by_at_most(5) + end + end + end end diff --git a/spec/services/fetch_remote_status_service_spec.rb b/spec/services/fetch_remote_status_service_spec.rb index fe5f1aed1..4f6ad6496 100644 --- a/spec/services/fetch_remote_status_service_spec.rb +++ b/spec/services/fetch_remote_status_service_spec.rb @@ -15,7 +15,7 @@ RSpec.describe FetchRemoteStatusService, type: :service do end context 'protocol is :activitypub' do - subject { described_class.new.call(note[:id], prefetched_body) } + subject { described_class.new.call(note[:id], prefetched_body: prefetched_body) } let(:prefetched_body) { Oj.dump(note) } before do -- cgit From 669f6d2c0af969268c76e389ed626bce0cc9f998 Mon Sep 17 00:00:00 2001 From: Nick Schonning Date: Fri, 17 Feb 2023 16:56:20 -0500 Subject: Run rubocop formatting except line length (#23632) --- .rubocop_todo.yml | 277 +-------------------- app/lib/activitypub/activity/create.rb | 4 +- app/models/concerns/expireable.rb | 2 +- app/services/activitypub/fetch_replies_service.rb | 2 +- .../20161006213403_rails_settings_migration.rb | 10 +- ...uses_for_api_v1_accounts_account_id_statuses.rb | 8 +- .../20190306145741_add_lock_version_to_polls.rb | 1 - ...20190807135426_add_comments_to_domain_blocks.rb | 1 - ...200312162302_add_status_ids_to_announcements.rb | 1 - ...00510181721_remove_duplicated_indexes_pghero.rb | 1 - db/migrate/20200628133322_create_account_notes.rb | 1 - ...340_create_account_statuses_cleanup_policies.rb | 1 - ...0729171123_fix_custom_filter_keywords_id_seq.rb | 2 +- lib/paperclip/attachment_extensions.rb | 10 +- lib/tasks/mastodon.rake | 4 +- spec/config/initializers/rack_attack_spec.rb | 10 +- .../controllers/admin/dashboard_controller_spec.rb | 8 +- .../api/v1/accounts/credentials_controller_spec.rb | 2 +- spec/controllers/api/v1/reports_controller_spec.rb | 2 +- .../favourited_by_accounts_controller_spec.rb | 2 +- .../reblogged_by_accounts_controller_spec.rb | 2 +- .../api/v2/filters/statuses_controller_spec.rb | 4 +- spec/controllers/auth/sessions_controller_spec.rb | 6 +- .../authorize_interactions_controller_spec.rb | 1 - .../settings/applications_controller_spec.rb | 2 +- .../confirmations_controller_spec.rb | 1 - .../webauthn_credentials_controller_spec.rb | 2 +- .../well_known/host_meta_controller_spec.rb | 12 +- .../custom_filter_keyword_fabricator.rb | 2 +- spec/fabricators/ip_block_fabricator.rb | 2 +- spec/fabricators/poll_vote_fabricator.rb | 2 +- spec/fabricators/status_edit_fabricator.rb | 2 +- spec/fabricators/system_key_fabricator.rb | 1 - spec/lib/activitypub/activity/create_spec.rb | 1 - spec/lib/extractor_spec.rb | 8 +- spec/lib/fast_ip_map_spec.rb | 2 +- spec/lib/link_details_extractor_spec.rb | 124 ++++----- spec/models/account/field_spec.rb | 4 +- spec/models/account_alias_spec.rb | 1 - .../models/account_statuses_cleanup_policy_spec.rb | 40 ++- spec/models/concerns/account_interactions_spec.rb | 2 +- spec/models/device_spec.rb | 1 - spec/models/encrypted_message_spec.rb | 1 - spec/models/export_spec.rb | 2 +- spec/models/login_activity_spec.rb | 1 - spec/models/one_time_key_spec.rb | 1 - spec/models/system_key_spec.rb | 1 - spec/models/trends/statuses_spec.rb | 2 +- spec/models/user_role_spec.rb | 2 +- spec/routing/api_routing_spec.rb | 72 +++--- spec/routing/well_known_routes_spec.rb | 8 +- spec/serializers/rest/account_serializer_spec.rb | 2 +- .../account_statuses_cleanup_service_spec.rb | 4 +- .../fetch_remote_status_service_spec.rb | 2 +- .../activitypub/process_account_service_spec.rb | 4 +- .../activitypub/process_collection_service_spec.rb | 12 +- .../process_status_update_service_spec.rb | 42 ++-- spec/services/bootstrap_timeline_service_spec.rb | 1 - spec/services/fetch_oembed_service_spec.rb | 1 - spec/services/import_service_spec.rb | 4 +- spec/services/remove_from_follwers_service_spec.rb | 2 +- spec/services/remove_status_service_spec.rb | 68 ++--- spec/services/resolve_account_service_spec.rb | 2 +- spec/services/resolve_url_service_spec.rb | 2 +- spec/services/update_status_service_spec.rb | 2 +- spec/support/stories/profile_stories.rb | 4 +- spec/validators/note_length_validator_spec.rb | 4 +- .../unreserved_username_validator_spec.rb | 6 +- .../activitypub/distribution_worker_spec.rb | 2 +- .../activitypub/move_distribution_worker_spec.rb | 8 +- .../accounts_statuses_cleanup_scheduler_spec.rb | 2 +- 71 files changed, 269 insertions(+), 566 deletions(-) (limited to 'app/lib/activitypub/activity/create.rb') diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index e3a42da5b..e24ce7e32 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,6 +1,6 @@ # This configuration was generated by # `rubocop --auto-gen-config --auto-gen-only-exclude --no-exclude-limit` -# on 2023-02-16 04:55:24 UTC using RuboCop version 1.45.1. +# on 2023-02-16 05:53:07 UTC using RuboCop version 1.45.1. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new @@ -14,53 +14,6 @@ Bundler/OrderedGems: Exclude: - 'Gemfile' -# Offense count: 5 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: with_first_argument, with_fixed_indentation -Layout/ArgumentAlignment: - Exclude: - - 'spec/models/account_statuses_cleanup_policy_spec.rb' - - 'spec/services/activitypub/process_collection_service_spec.rb' - - 'spec/services/activitypub/process_status_update_service_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyleAlignWith. -# SupportedStylesAlignWith: either, start_of_block, start_of_line -Layout/BlockAlignment: - Exclude: - - 'spec/controllers/api/v1/accounts/credentials_controller_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Layout/ClosingParenthesisIndentation: - Exclude: - - 'spec/controllers/auth/sessions_controller_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowForAlignment. -Layout/CommentIndentation: - Exclude: - - 'db/migrate/20180514130000_improve_index_on_statuses_for_api_v1_accounts_account_id_statuses.rb' - -# Offense count: 22 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: leading, trailing -Layout/DotPosition: - Exclude: - - 'lib/paperclip/attachment_extensions.rb' - - 'spec/routing/api_routing_spec.rb' - - 'spec/routing/well_known_routes_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Layout/ElseAlignment: - Exclude: - - 'db/migrate/20161006213403_rails_settings_migration.rb' - # Offense count: 81 # This cop supports safe autocorrection (--autocorrect). Layout/EmptyLineAfterGuardClause: @@ -183,73 +136,6 @@ Layout/EmptyLineAfterMagicComment: - 'spec/controllers/api/v1/accounts/statuses_controller_spec.rb' - 'spec/models/tag_spec.rb' -# Offense count: 3 -# This cop supports safe autocorrection (--autocorrect). -Layout/EmptyLines: - Exclude: - - 'spec/controllers/authorize_interactions_controller_spec.rb' - - 'spec/controllers/settings/two_factor_authentication/confirmations_controller_spec.rb' - - 'spec/lib/activitypub/activity/create_spec.rb' - -# Offense count: 9 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, no_empty_lines -Layout/EmptyLinesAroundBlockBody: - Exclude: - - 'spec/fabricators/system_key_fabricator.rb' - - 'spec/models/account_alias_spec.rb' - - 'spec/models/device_spec.rb' - - 'spec/models/encrypted_message_spec.rb' - - 'spec/models/login_activity_spec.rb' - - 'spec/models/one_time_key_spec.rb' - - 'spec/models/system_key_spec.rb' - - 'spec/services/bootstrap_timeline_service_spec.rb' - - 'spec/services/fetch_oembed_service_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyleAlignWith, Severity. -# SupportedStylesAlignWith: keyword, variable, start_of_line -Layout/EndAlignment: - Exclude: - - 'db/migrate/20161006213403_rails_settings_migration.rb' - -# Offense count: 19 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowForAlignment, AllowBeforeTrailingComments, ForceEqualSignAlignment. -Layout/ExtraSpacing: - Exclude: - - 'spec/config/initializers/rack_attack_spec.rb' - - 'spec/controllers/api/v2/filters/statuses_controller_spec.rb' - - 'spec/fabricators/custom_filter_keyword_fabricator.rb' - - 'spec/fabricators/poll_vote_fabricator.rb' - - 'spec/models/account_statuses_cleanup_policy_spec.rb' - - 'spec/services/activitypub/process_status_update_service_spec.rb' - - 'spec/services/import_service_spec.rb' - - 'spec/services/resolve_account_service_spec.rb' - - 'spec/services/resolve_url_service_spec.rb' - - 'spec/validators/note_length_validator_spec.rb' - - 'spec/validators/unreserved_username_validator_spec.rb' - - 'spec/workers/activitypub/move_distribution_worker_spec.rb' - -# Offense count: 4 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: consistent, consistent_relative_to_receiver, special_for_inner_method_call, special_for_inner_method_call_in_parentheses -Layout/FirstArgumentIndentation: - Exclude: - - 'spec/services/remove_status_service_spec.rb' - -# Offense count: 4 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: special_inside_parentheses, consistent, align_brackets -Layout/FirstArrayElementIndentation: - Exclude: - - 'spec/controllers/admin/dashboard_controller_spec.rb' - - 'spec/workers/activitypub/move_distribution_worker_spec.rb' - # Offense count: 113 # This cop supports safe autocorrection (--autocorrect). # Configuration parameters: AllowMultipleStyles, EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle. @@ -276,49 +162,6 @@ Layout/HashAlignment: - 'spec/models/admin/account_action_spec.rb' - 'spec/models/concerns/account_interactions_spec.rb' -# Offense count: 3 -# This cop supports safe autocorrection (--autocorrect). -Layout/HeredocIndentation: - Exclude: - - 'spec/controllers/well_known/host_meta_controller_spec.rb' - - 'spec/lib/link_details_extractor_spec.rb' - -# Offense count: 5 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: normal, indented_internal_methods -Layout/IndentationConsistency: - Exclude: - - 'spec/controllers/api/v1/statuses/favourited_by_accounts_controller_spec.rb' - - 'spec/controllers/api/v1/statuses/reblogged_by_accounts_controller_spec.rb' - - 'spec/models/trends/statuses_spec.rb' - - 'spec/services/import_service_spec.rb' - -# Offense count: 4 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: Width, AllowedPatterns. -Layout/IndentationWidth: - Exclude: - - 'db/migrate/20161006213403_rails_settings_migration.rb' - - 'spec/controllers/api/v1/accounts/credentials_controller_spec.rb' - - 'spec/services/account_statuses_cleanup_service_spec.rb' - - 'spec/services/import_service_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowDoxygenCommentStyle, AllowGemfileRubyComment. -Layout/LeadingCommentSpace: - Exclude: - - 'lib/paperclip/attachment_extensions.rb' - -# Offense count: 2 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AutoCorrect, EnforcedStyle. -# SupportedStyles: space, no_space -Layout/LineContinuationSpacing: - Exclude: - - 'spec/support/stories/profile_stories.rb' - # Offense count: 577 # This cop supports safe autocorrection (--autocorrect). # Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, AllowedPatterns. @@ -326,124 +169,6 @@ Layout/LineContinuationSpacing: Layout/LineLength: Enabled: false -# Offense count: 4 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: symmetrical, new_line, same_line -Layout/MultilineMethodCallBraceLayout: - Exclude: - - 'spec/models/account_statuses_cleanup_policy_spec.rb' - - 'spec/services/activitypub/process_status_update_service_spec.rb' - -# Offense count: 3 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowForAlignment, EnforcedStyleForExponentOperator. -# SupportedStylesForExponentOperator: space, no_space -Layout/SpaceAroundOperators: - Exclude: - - 'spec/services/activitypub/fetch_remote_status_service_spec.rb' - - 'spec/validators/note_length_validator_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. -# SupportedStyles: space, no_space -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceBeforeBlockBraces: - Exclude: - - 'spec/controllers/api/v1/reports_controller_spec.rb' - -# Offense count: 3 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowForAlignment. -Layout/SpaceBeforeFirstArg: - Exclude: - - 'spec/fabricators/custom_filter_keyword_fabricator.rb' - - 'spec/fabricators/poll_vote_fabricator.rb' - - 'spec/models/concerns/account_interactions_spec.rb' - -# Offense count: 24 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBrackets. -# SupportedStyles: space, no_space, compact -# SupportedStylesForEmptyBrackets: space, no_space -Layout/SpaceInsideArrayLiteralBrackets: - Exclude: - - 'db/migrate/20161006213403_rails_settings_migration.rb' - - 'spec/controllers/settings/applications_controller_spec.rb' - - 'spec/lib/extractor_spec.rb' - - 'spec/models/export_spec.rb' - - 'spec/services/activitypub/process_account_service_spec.rb' - - 'spec/workers/scheduler/accounts_statuses_cleanup_scheduler_spec.rb' - -# Offense count: 4 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. -# SupportedStyles: space, no_space -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceInsideBlockBraces: - Exclude: - - 'spec/lib/fast_ip_map_spec.rb' - - 'spec/models/user_role_spec.rb' - - 'spec/serializers/rest/account_serializer_spec.rb' - - 'spec/workers/activitypub/distribution_worker_spec.rb' - -# Offense count: 6 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. -# SupportedStyles: space, no_space, compact -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceInsideHashLiteralBraces: - Exclude: - - 'app/lib/activitypub/activity/create.rb' - - 'app/services/activitypub/fetch_replies_service.rb' - - 'spec/services/activitypub/process_collection_service_spec.rb' - - 'spec/services/update_status_service_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: space, compact, no_space -Layout/SpaceInsideParens: - Exclude: - - 'spec/validators/unreserved_username_validator_spec.rb' - -# Offense count: 4 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: space, no_space -Layout/SpaceInsideStringInterpolation: - Exclude: - - 'spec/controllers/auth/sessions_controller_spec.rb' - - 'spec/controllers/settings/two_factor_authentication/webauthn_credentials_controller_spec.rb' - - 'spec/services/activitypub/process_account_service_spec.rb' - -# Offense count: 8 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: final_newline, final_blank_line -Layout/TrailingEmptyLines: - Exclude: - - 'db/migrate/20190306145741_add_lock_version_to_polls.rb' - - 'db/migrate/20190807135426_add_comments_to_domain_blocks.rb' - - 'db/migrate/20200312162302_add_status_ids_to_announcements.rb' - - 'db/migrate/20200510181721_remove_duplicated_indexes_pghero.rb' - - 'db/migrate/20200628133322_create_account_notes.rb' - - 'db/migrate/20210722120340_create_account_statuses_cleanup_policies.rb' - - 'spec/fabricators/ip_block_fabricator.rb' - - 'spec/fabricators/status_edit_fabricator.rb' - -# Offense count: 7 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowInHeredoc. -Layout/TrailingWhitespace: - Exclude: - - 'app/models/concerns/expireable.rb' - - 'db/post_migrate/20220729171123_fix_custom_filter_keywords_id_seq.rb' - - 'lib/tasks/mastodon.rake' - - 'spec/models/account/field_spec.rb' - - 'spec/services/remove_from_follwers_service_spec.rb' - # Offense count: 14 # Configuration parameters: AllowedMethods, AllowedPatterns. Lint/AmbiguousBlockAssociation: diff --git a/app/lib/activitypub/activity/create.rb b/app/lib/activitypub/activity/create.rb index 487b65223..f82112c02 100644 --- a/app/lib/activitypub/activity/create.rb +++ b/app/lib/activitypub/activity/create.rb @@ -327,7 +327,7 @@ class ActivityPub::Activity::Create < ActivityPub::Activity def resolve_thread(status) return unless status.reply? && status.thread.nil? && Request.valid_url?(in_reply_to_uri) - ThreadResolveWorker.perform_async(status.id, in_reply_to_uri, { 'request_id' => @options[:request_id]}) + ThreadResolveWorker.perform_async(status.id, in_reply_to_uri, { 'request_id' => @options[:request_id] }) end def fetch_replies(status) @@ -338,7 +338,7 @@ class ActivityPub::Activity::Create < ActivityPub::Activity return unless replies.nil? uri = value_or_id(collection) - ActivityPub::FetchRepliesWorker.perform_async(status.id, uri, { 'request_id' => @options[:request_id]}) unless uri.nil? + ActivityPub::FetchRepliesWorker.perform_async(status.id, uri, { 'request_id' => @options[:request_id] }) unless uri.nil? end def conversation_from_uri(uri) diff --git a/app/models/concerns/expireable.rb b/app/models/concerns/expireable.rb index 4d902abcb..c64fc7d80 100644 --- a/app/models/concerns/expireable.rb +++ b/app/models/concerns/expireable.rb @@ -17,7 +17,7 @@ module Expireable end def expires_in=(interval) - self.expires_at = interval.present? ? interval.to_i.seconds.from_now : nil + self.expires_at = interval.present? ? interval.to_i.seconds.from_now : nil @expires_in = interval end diff --git a/app/services/activitypub/fetch_replies_service.rb b/app/services/activitypub/fetch_replies_service.rb index 18a27e851..4128df9ca 100644 --- a/app/services/activitypub/fetch_replies_service.rb +++ b/app/services/activitypub/fetch_replies_service.rb @@ -10,7 +10,7 @@ class ActivityPub::FetchRepliesService < BaseService @items = collection_items(collection_or_uri) return if @items.nil? - FetchReplyWorker.push_bulk(filtered_replies) { |reply_uri| [reply_uri, { 'request_id' => request_id}] } + FetchReplyWorker.push_bulk(filtered_replies) { |reply_uri| [reply_uri, { 'request_id' => request_id }] } @items end diff --git a/db/migrate/20161006213403_rails_settings_migration.rb b/db/migrate/20161006213403_rails_settings_migration.rb index 9d565cb5c..02932610c 100644 --- a/db/migrate/20161006213403_rails_settings_migration.rb +++ b/db/migrate/20161006213403_rails_settings_migration.rb @@ -1,8 +1,8 @@ MIGRATION_BASE_CLASS = if ActiveRecord::VERSION::MAJOR >= 5 - ActiveRecord::Migration[5.0] -else - ActiveRecord::Migration[4.2] -end + ActiveRecord::Migration[5.0] + else + ActiveRecord::Migration[4.2] + end class RailsSettingsMigration < MIGRATION_BASE_CLASS def self.up @@ -12,7 +12,7 @@ class RailsSettingsMigration < MIGRATION_BASE_CLASS t.references :target, null: false, polymorphic: true, index: { name: 'index_settings_on_target_type_and_target_id' } t.timestamps null: true end - add_index :settings, [ :target_type, :target_id, :var ], unique: true + add_index :settings, [:target_type, :target_id, :var], unique: true end def self.down diff --git a/db/migrate/20180514130000_improve_index_on_statuses_for_api_v1_accounts_account_id_statuses.rb b/db/migrate/20180514130000_improve_index_on_statuses_for_api_v1_accounts_account_id_statuses.rb index b29e62803..a3f883fcb 100644 --- a/db/migrate/20180514130000_improve_index_on_statuses_for_api_v1_accounts_account_id_statuses.rb +++ b/db/migrate/20180514130000_improve_index_on_statuses_for_api_v1_accounts_account_id_statuses.rb @@ -4,9 +4,9 @@ class ImproveIndexOnStatusesForApiV1AccountsAccountIdStatuses < ActiveRecord::Mi disable_ddl_transaction! def change - # These changes ware reverted by migration 20180514140000. - # add_index :statuses, [:account_id, :id, :visibility], where: 'visibility IN (0, 1, 2)', algorithm: :concurrently - # add_index :statuses, [:account_id, :id], where: 'visibility = 3', algorithm: :concurrently - # remove_index :statuses, column: [:account_id, :id, :visibility, :updated_at], order: { id: :desc }, algorithm: :concurrently, name: :index_statuses_20180106 + # These changes ware reverted by migration 20180514140000. + # add_index :statuses, [:account_id, :id, :visibility], where: 'visibility IN (0, 1, 2)', algorithm: :concurrently + # add_index :statuses, [:account_id, :id], where: 'visibility = 3', algorithm: :concurrently + # remove_index :statuses, column: [:account_id, :id, :visibility, :updated_at], order: { id: :desc }, algorithm: :concurrently, name: :index_statuses_20180106 end end diff --git a/db/migrate/20190306145741_add_lock_version_to_polls.rb b/db/migrate/20190306145741_add_lock_version_to_polls.rb index 5bb8cd3b4..c9fa471ad 100644 --- a/db/migrate/20190306145741_add_lock_version_to_polls.rb +++ b/db/migrate/20190306145741_add_lock_version_to_polls.rb @@ -21,4 +21,3 @@ class AddLockVersionToPolls < ActiveRecord::Migration[5.2] remove_column :polls, :lock_version end end - diff --git a/db/migrate/20190807135426_add_comments_to_domain_blocks.rb b/db/migrate/20190807135426_add_comments_to_domain_blocks.rb index b660a71ad..79b9f0212 100644 --- a/db/migrate/20190807135426_add_comments_to_domain_blocks.rb +++ b/db/migrate/20190807135426_add_comments_to_domain_blocks.rb @@ -4,4 +4,3 @@ class AddCommentsToDomainBlocks < ActiveRecord::Migration[5.2] add_column :domain_blocks, :public_comment, :text end end - diff --git a/db/migrate/20200312162302_add_status_ids_to_announcements.rb b/db/migrate/20200312162302_add_status_ids_to_announcements.rb index 42aa6513d..704d3773e 100644 --- a/db/migrate/20200312162302_add_status_ids_to_announcements.rb +++ b/db/migrate/20200312162302_add_status_ids_to_announcements.rb @@ -3,4 +3,3 @@ class AddStatusIdsToAnnouncements < ActiveRecord::Migration[5.2] add_column :announcements, :status_ids, :bigint, array: true end end - diff --git a/db/migrate/20200510181721_remove_duplicated_indexes_pghero.rb b/db/migrate/20200510181721_remove_duplicated_indexes_pghero.rb index 1d6ba1fe9..59bb1b9e2 100644 --- a/db/migrate/20200510181721_remove_duplicated_indexes_pghero.rb +++ b/db/migrate/20200510181721_remove_duplicated_indexes_pghero.rb @@ -19,4 +19,3 @@ class RemoveDuplicatedIndexesPghero < ActiveRecord::Migration[5.2] add_index :markers, :user_id, name: :index_markers_on_user_id unless index_exists?(:markers, :user_id, name: :index_markers_on_user_id) end end - diff --git a/db/migrate/20200628133322_create_account_notes.rb b/db/migrate/20200628133322_create_account_notes.rb index 664727e60..022e0ff3a 100644 --- a/db/migrate/20200628133322_create_account_notes.rb +++ b/db/migrate/20200628133322_create_account_notes.rb @@ -10,4 +10,3 @@ class CreateAccountNotes < ActiveRecord::Migration[5.2] end end end - diff --git a/db/migrate/20210722120340_create_account_statuses_cleanup_policies.rb b/db/migrate/20210722120340_create_account_statuses_cleanup_policies.rb index 28cfb6ef5..db168676a 100644 --- a/db/migrate/20210722120340_create_account_statuses_cleanup_policies.rb +++ b/db/migrate/20210722120340_create_account_statuses_cleanup_policies.rb @@ -17,4 +17,3 @@ class CreateAccountStatusesCleanupPolicies < ActiveRecord::Migration[6.1] end end end - diff --git a/db/post_migrate/20220729171123_fix_custom_filter_keywords_id_seq.rb b/db/post_migrate/20220729171123_fix_custom_filter_keywords_id_seq.rb index 7ed34a3ef..eb437c86c 100644 --- a/db/post_migrate/20220729171123_fix_custom_filter_keywords_id_seq.rb +++ b/db/post_migrate/20220729171123_fix_custom_filter_keywords_id_seq.rb @@ -5,7 +5,7 @@ class FixCustomFilterKeywordsIdSeq < ActiveRecord::Migration[6.1] def up # 20220613110711 manually inserts items with set `id` in the database, but - # we also need to bump the sequence number, otherwise + # we also need to bump the sequence number, otherwise safety_assured do execute <<-SQL.squish BEGIN; diff --git a/lib/paperclip/attachment_extensions.rb b/lib/paperclip/attachment_extensions.rb index d66a17623..7f82138aa 100644 --- a/lib/paperclip/attachment_extensions.rb +++ b/lib/paperclip/attachment_extensions.rb @@ -8,7 +8,7 @@ module Paperclip # monkey-patch to avoid unlinking too avoid unlinking source file too early # see https://github.com/kreeti/kt-paperclip/issues/64 - def post_process_style(name, style) #:nodoc: + def post_process_style(name, style) # :nodoc: raise "Style #{name} has no processors defined." if style.processors.blank? intermediate_files = [] @@ -16,16 +16,16 @@ module Paperclip # if we're processing the original, close + unlink the source tempfile intermediate_files << original if name == :original - @queued_for_write[name] = style.processors. - inject(original) do |file, processor| + @queued_for_write[name] = style.processors + .inject(original) do |file, processor| file = Paperclip.processor(processor).make(file, style.processor_options, self) intermediate_files << file unless file == original file end unadapted_file = @queued_for_write[name] - @queued_for_write[name] = Paperclip.io_adapters. - for(@queued_for_write[name], @options[:adapter_options]) + @queued_for_write[name] = Paperclip.io_adapters + .for(@queued_for_write[name], @options[:adapter_options]) unadapted_file.close if unadapted_file.respond_to?(:close) @queued_for_write[name] rescue Paperclip::Errors::NotIdentifiedByImageMagickError => e diff --git a/lib/tasks/mastodon.rake b/lib/tasks/mastodon.rake index 1184e5273..477daa01b 100644 --- a/lib/tasks/mastodon.rake +++ b/lib/tasks/mastodon.rake @@ -286,13 +286,13 @@ namespace :mastodon do q.required true q.modify :strip end - + linksharing_access_key = prompt.ask('Storj Linksharing access key (uplink share --register --public --readonly=true --disallow-lists --not-after=none sj://bucket):') do |q| q.required true q.modify :strip end env['S3_ALIAS_HOST'] = "link.storjshare.io/raw/#{linksharing_access_key}/#{env['S3_BUCKET']}" - + when 'Google Cloud Storage' env['S3_ENABLED'] = 'true' env['S3_PROTOCOL'] = 'https' diff --git a/spec/config/initializers/rack_attack_spec.rb b/spec/config/initializers/rack_attack_spec.rb index 581021cb9..03695f5fd 100644 --- a/spec/config/initializers/rack_attack_spec.rb +++ b/spec/config/initializers/rack_attack_spec.rb @@ -35,12 +35,12 @@ describe Rack::Attack do let(:request) { ->() { post path, {}, 'REMOTE_ADDR' => remote_ip } } context 'for exact path' do - let(:path) { '/auth' } + let(:path) { '/auth' } it_behaves_like 'throttled endpoint' end context 'for path with format' do - let(:path) { '/auth.html' } + let(:path) { '/auth.html' } it_behaves_like 'throttled endpoint' end end @@ -50,7 +50,7 @@ describe Rack::Attack do let(:request) { ->() { post path, {}, 'REMOTE_ADDR' => remote_ip } } context 'for exact path' do - let(:path) { '/api/v1/accounts' } + let(:path) { '/api/v1/accounts' } it_behaves_like 'throttled endpoint' end @@ -70,12 +70,12 @@ describe Rack::Attack do let(:request) { ->() { post path, {}, 'REMOTE_ADDR' => remote_ip } } context 'for exact path' do - let(:path) { '/auth/sign_in' } + let(:path) { '/auth/sign_in' } it_behaves_like 'throttled endpoint' end context 'for path with format' do - let(:path) { '/auth/sign_in.html' } + let(:path) { '/auth/sign_in.html' } it_behaves_like 'throttled endpoint' end end diff --git a/spec/controllers/admin/dashboard_controller_spec.rb b/spec/controllers/admin/dashboard_controller_spec.rb index 6231a09a2..ab3738fcd 100644 --- a/spec/controllers/admin/dashboard_controller_spec.rb +++ b/spec/controllers/admin/dashboard_controller_spec.rb @@ -8,10 +8,10 @@ describe Admin::DashboardController, type: :controller do describe 'GET #index' do before do allow(Admin::SystemCheck).to receive(:perform).and_return([ - Admin::SystemCheck::Message.new(:database_schema_check), - Admin::SystemCheck::Message.new(:rules_check, nil, admin_rules_path), - Admin::SystemCheck::Message.new(:sidekiq_process_check, 'foo, bar'), - ]) + Admin::SystemCheck::Message.new(:database_schema_check), + Admin::SystemCheck::Message.new(:rules_check, nil, admin_rules_path), + Admin::SystemCheck::Message.new(:sidekiq_process_check, 'foo, bar'), + ]) sign_in Fabricate(:user, role: UserRole.find_by(name: 'Admin')) end diff --git a/spec/controllers/api/v1/accounts/credentials_controller_spec.rb b/spec/controllers/api/v1/accounts/credentials_controller_spec.rb index b2557d957..89cc8acad 100644 --- a/spec/controllers/api/v1/accounts/credentials_controller_spec.rb +++ b/spec/controllers/api/v1/accounts/credentials_controller_spec.rb @@ -70,7 +70,7 @@ describe Api::V1::Accounts::CredentialsController do it 'returns http success' do expect(response).to have_http_status(200) end - end + end describe 'with invalid data' do before do diff --git a/spec/controllers/api/v1/reports_controller_spec.rb b/spec/controllers/api/v1/reports_controller_spec.rb index dbc64e704..78a72b95b 100644 --- a/spec/controllers/api/v1/reports_controller_spec.rb +++ b/spec/controllers/api/v1/reports_controller_spec.rb @@ -20,7 +20,7 @@ RSpec.describe Api::V1::ReportsController, type: :controller do let(:target_account) { status.account } let(:category) { nil } let(:forward) { nil } - let(:rule_ids){ nil } + let(:rule_ids) { nil } before do allow(AdminMailer).to receive(:new_report).and_return(double('email', deliver_later: nil)) diff --git a/spec/controllers/api/v1/statuses/favourited_by_accounts_controller_spec.rb b/spec/controllers/api/v1/statuses/favourited_by_accounts_controller_spec.rb index 7cc77f430..4dcaba6bd 100644 --- a/spec/controllers/api/v1/statuses/favourited_by_accounts_controller_spec.rb +++ b/spec/controllers/api/v1/statuses/favourited_by_accounts_controller_spec.rb @@ -31,7 +31,7 @@ RSpec.describe Api::V1::Statuses::FavouritedByAccountsController, type: :control it 'returns accounts who favorited the status' do get :index, params: { status_id: status.id, limit: 2 } expect(body_as_json.size).to eq 2 - expect([body_as_json[0][:id], body_as_json[1][:id]]).to match_array([alice.id.to_s, bob.id.to_s]) + expect([body_as_json[0][:id], body_as_json[1][:id]]).to match_array([alice.id.to_s, bob.id.to_s]) end it 'does not return blocked users' do diff --git a/spec/controllers/api/v1/statuses/reblogged_by_accounts_controller_spec.rb b/spec/controllers/api/v1/statuses/reblogged_by_accounts_controller_spec.rb index 8d4a6f91c..dc36d4ca0 100644 --- a/spec/controllers/api/v1/statuses/reblogged_by_accounts_controller_spec.rb +++ b/spec/controllers/api/v1/statuses/reblogged_by_accounts_controller_spec.rb @@ -31,7 +31,7 @@ RSpec.describe Api::V1::Statuses::RebloggedByAccountsController, type: :controll it 'returns accounts who reblogged the status' do get :index, params: { status_id: status.id, limit: 2 } expect(body_as_json.size).to eq 2 - expect([body_as_json[0][:id], body_as_json[1][:id]]).to match_array([alice.id.to_s, bob.id.to_s]) + expect([body_as_json[0][:id], body_as_json[1][:id]]).to match_array([alice.id.to_s, bob.id.to_s]) end it 'does not return blocked users' do diff --git a/spec/controllers/api/v2/filters/statuses_controller_spec.rb b/spec/controllers/api/v2/filters/statuses_controller_spec.rb index 9740c1eb3..969b2ea73 100644 --- a/spec/controllers/api/v2/filters/statuses_controller_spec.rb +++ b/spec/controllers/api/v2/filters/statuses_controller_spec.rb @@ -64,7 +64,7 @@ RSpec.describe Api::V2::Filters::StatusesController, type: :controller do end describe 'GET #show' do - let(:scopes) { 'read:filters' } + let(:scopes) { 'read:filters' } let!(:status_filter) { Fabricate(:custom_filter_status, custom_filter: filter) } before do @@ -90,7 +90,7 @@ RSpec.describe Api::V2::Filters::StatusesController, type: :controller do end describe 'DELETE #destroy' do - let(:scopes) { 'write:filters' } + let(:scopes) { 'write:filters' } let(:status_filter) { Fabricate(:custom_filter_status, custom_filter: filter) } before do diff --git a/spec/controllers/auth/sessions_controller_spec.rb b/spec/controllers/auth/sessions_controller_spec.rb index d3db7aa1a..64433ddf4 100644 --- a/spec/controllers/auth/sessions_controller_spec.rb +++ b/spec/controllers/auth/sessions_controller_spec.rb @@ -339,11 +339,11 @@ RSpec.describe Auth::SessionsController, type: :controller do external_id: public_key_credential.id, public_key: public_key_credential.public_key, sign_count: '1000' - ) + ) user.webauthn_credentials.take end - let(:domain) { "#{Rails.configuration.x.use_https ? 'https' : 'http' }://#{Rails.configuration.x.web_domain}" } + let(:domain) { "#{Rails.configuration.x.use_https ? 'https' : 'http'}://#{Rails.configuration.x.web_domain}" } let(:fake_client) { WebAuthn::FakeClient.new(domain) } @@ -400,7 +400,7 @@ RSpec.describe Auth::SessionsController, type: :controller do describe 'GET #webauthn_options' do context 'with WebAuthn and OTP enabled as second factor' do - let(:domain) { "#{Rails.configuration.x.use_https ? 'https' : 'http' }://#{Rails.configuration.x.web_domain}" } + let(:domain) { "#{Rails.configuration.x.use_https ? 'https' : 'http'}://#{Rails.configuration.x.web_domain}" } let(:fake_client) { WebAuthn::FakeClient.new(domain) } diff --git a/spec/controllers/authorize_interactions_controller_spec.rb b/spec/controllers/authorize_interactions_controller_spec.rb index 44f52df69..e52103941 100644 --- a/spec/controllers/authorize_interactions_controller_spec.rb +++ b/spec/controllers/authorize_interactions_controller_spec.rb @@ -99,7 +99,6 @@ describe AuthorizeInteractionsController do allow(ResolveAccountService).to receive(:new).and_return(service) allow(service).to receive(:call).with('user@hostname').and_return(target_account) - post :create, params: { acct: 'acct:user@hostname' } expect(account.following?(target_account)).to be true diff --git a/spec/controllers/settings/applications_controller_spec.rb b/spec/controllers/settings/applications_controller_spec.rb index 1292e9ff8..9074574e4 100644 --- a/spec/controllers/settings/applications_controller_spec.rb +++ b/spec/controllers/settings/applications_controller_spec.rb @@ -73,7 +73,7 @@ describe Settings::ApplicationsController do name: 'My New App', redirect_uri: 'urn:ietf:wg:oauth:2.0:oob', website: 'http://google.com', - scopes: [ 'read', 'write', 'follow' ] + scopes: ['read', 'write', 'follow'] } } response diff --git a/spec/controllers/settings/two_factor_authentication/confirmations_controller_spec.rb b/spec/controllers/settings/two_factor_authentication/confirmations_controller_spec.rb index 569c8322b..0b807b280 100644 --- a/spec/controllers/settings/two_factor_authentication/confirmations_controller_spec.rb +++ b/spec/controllers/settings/two_factor_authentication/confirmations_controller_spec.rb @@ -5,7 +5,6 @@ require 'rails_helper' describe Settings::TwoFactorAuthentication::ConfirmationsController do render_views - shared_examples 'renders :new' do it 'renders the new view' do subject diff --git a/spec/controllers/settings/two_factor_authentication/webauthn_credentials_controller_spec.rb b/spec/controllers/settings/two_factor_authentication/webauthn_credentials_controller_spec.rb index fe53b4dfc..06989ffd2 100644 --- a/spec/controllers/settings/two_factor_authentication/webauthn_credentials_controller_spec.rb +++ b/spec/controllers/settings/two_factor_authentication/webauthn_credentials_controller_spec.rb @@ -7,7 +7,7 @@ describe Settings::TwoFactorAuthentication::WebauthnCredentialsController do render_views let(:user) { Fabricate(:user) } - let(:domain) { "#{Rails.configuration.x.use_https ? 'https' : 'http' }://#{Rails.configuration.x.web_domain}" } + let(:domain) { "#{Rails.configuration.x.use_https ? 'https' : 'http'}://#{Rails.configuration.x.web_domain}" } let(:fake_client) { WebAuthn::FakeClient.new(domain) } def add_webauthn_credential(user) diff --git a/spec/controllers/well_known/host_meta_controller_spec.rb b/spec/controllers/well_known/host_meta_controller_spec.rb index c02aa0d59..654bad406 100644 --- a/spec/controllers/well_known/host_meta_controller_spec.rb +++ b/spec/controllers/well_known/host_meta_controller_spec.rb @@ -9,12 +9,12 @@ describe WellKnown::HostMetaController, type: :controller do expect(response).to have_http_status(200) expect(response.media_type).to eq 'application/xrd+xml' - expect(response.body).to eq < - - - -XML + expect(response.body).to eq <<~XML + + + + + XML end end end diff --git a/spec/fabricators/custom_filter_keyword_fabricator.rb b/spec/fabricators/custom_filter_keyword_fabricator.rb index 0f101dcd1..201566cbe 100644 --- a/spec/fabricators/custom_filter_keyword_fabricator.rb +++ b/spec/fabricators/custom_filter_keyword_fabricator.rb @@ -1,4 +1,4 @@ Fabricator(:custom_filter_keyword) do custom_filter - keyword 'discourse' + keyword 'discourse' end diff --git a/spec/fabricators/ip_block_fabricator.rb b/spec/fabricators/ip_block_fabricator.rb index 31dc336e6..1797f6877 100644 --- a/spec/fabricators/ip_block_fabricator.rb +++ b/spec/fabricators/ip_block_fabricator.rb @@ -3,4 +3,4 @@ Fabricator(:ip_block) do severity "" expires_at "2020-10-08 22:20:37" comment "MyText" -end \ No newline at end of file +end diff --git a/spec/fabricators/poll_vote_fabricator.rb b/spec/fabricators/poll_vote_fabricator.rb index 51f9b006e..c06e61f67 100644 --- a/spec/fabricators/poll_vote_fabricator.rb +++ b/spec/fabricators/poll_vote_fabricator.rb @@ -1,5 +1,5 @@ Fabricator(:poll_vote) do account poll - choice 0 + choice 0 end diff --git a/spec/fabricators/status_edit_fabricator.rb b/spec/fabricators/status_edit_fabricator.rb index 21b793747..3141759e5 100644 --- a/spec/fabricators/status_edit_fabricator.rb +++ b/spec/fabricators/status_edit_fabricator.rb @@ -4,4 +4,4 @@ Fabricator(:status_edit) do text "MyText" spoiler_text "MyText" media_attachments_changed false -end \ No newline at end of file +end diff --git a/spec/fabricators/system_key_fabricator.rb b/spec/fabricators/system_key_fabricator.rb index f808495e0..c744bb286 100644 --- a/spec/fabricators/system_key_fabricator.rb +++ b/spec/fabricators/system_key_fabricator.rb @@ -1,3 +1,2 @@ Fabricator(:system_key) do - end diff --git a/spec/lib/activitypub/activity/create_spec.rb b/spec/lib/activitypub/activity/create_spec.rb index 1a25395fa..cd0f2df6e 100644 --- a/spec/lib/activitypub/activity/create_spec.rb +++ b/spec/lib/activitypub/activity/create_spec.rb @@ -408,7 +408,6 @@ RSpec.describe ActivityPub::Activity::Create do end end - context 'with media attachments with long description' do let(:object_json) do { diff --git a/spec/lib/extractor_spec.rb b/spec/lib/extractor_spec.rb index dba4bd0bb..9c9f5ef04 100644 --- a/spec/lib/extractor_spec.rb +++ b/spec/lib/extractor_spec.rb @@ -20,7 +20,7 @@ describe Extractor do text = '@screen_name' extracted = Extractor.extract_mentions_or_lists_with_indices(text) expect(extracted).to eq [ - { screen_name: 'screen_name', indices: [ 0, 12 ] } + { screen_name: 'screen_name', indices: [0, 12] } ] end @@ -44,19 +44,19 @@ describe Extractor do it 'does not exclude normal hash text before ://' do text = '#hashtag://' extracted = Extractor.extract_hashtags_with_indices(text) - expect(extracted).to eq [ { hashtag: 'hashtag', indices: [ 0, 8 ] } ] + expect(extracted).to eq [{ hashtag: 'hashtag', indices: [0, 8] }] end it 'excludes http://' do text = '#hashtaghttp://' extracted = Extractor.extract_hashtags_with_indices(text) - expect(extracted).to eq [ { hashtag: 'hashtag', indices: [ 0, 8 ] } ] + expect(extracted).to eq [{ hashtag: 'hashtag', indices: [0, 8] }] end it 'excludes https://' do text = '#hashtaghttps://' extracted = Extractor.extract_hashtags_with_indices(text) - expect(extracted).to eq [ { hashtag: 'hashtag', indices: [ 0, 8 ] } ] + expect(extracted).to eq [{ hashtag: 'hashtag', indices: [0, 8] }] end it 'yields hashtags if a block is given' do diff --git a/spec/lib/fast_ip_map_spec.rb b/spec/lib/fast_ip_map_spec.rb index c66f64828..78b3ddb05 100644 --- a/spec/lib/fast_ip_map_spec.rb +++ b/spec/lib/fast_ip_map_spec.rb @@ -4,7 +4,7 @@ require 'rails_helper' describe FastIpMap do describe '#include?' do - subject { described_class.new([IPAddr.new('20.4.0.0/16'), IPAddr.new('145.22.30.0/24'), IPAddr.new('189.45.86.3')])} + subject { described_class.new([IPAddr.new('20.4.0.0/16'), IPAddr.new('145.22.30.0/24'), IPAddr.new('189.45.86.3')]) } it 'returns true for an exact match' do expect(subject.include?(IPAddr.new('189.45.86.3'))).to be true diff --git a/spec/lib/link_details_extractor_spec.rb b/spec/lib/link_details_extractor_spec.rb index 7ea867c61..7eb15ced3 100644 --- a/spec/lib/link_details_extractor_spec.rb +++ b/spec/lib/link_details_extractor_spec.rb @@ -39,17 +39,17 @@ RSpec.describe LinkDetailsExtractor do let(:original_url) { 'https://example.com/page.html' } context 'and is wrapped in CDATA tags' do - let(:html) { <<-HTML } - - - - - - + let(:html) { <<~HTML } + + + + + + HTML describe '#title' do @@ -78,57 +78,57 @@ RSpec.describe LinkDetailsExtractor do end context 'but the first tag is invalid JSON' do - let(:html) { <<-HTML } - - - - - - - + let(:html) { <<~HTML } + + + + + + + HTML describe '#title' do diff --git a/spec/models/account/field_spec.rb b/spec/models/account/field_spec.rb index 0ac9769bc..40bbee025 100644 --- a/spec/models/account/field_spec.rb +++ b/spec/models/account/field_spec.rb @@ -97,7 +97,7 @@ RSpec.describe Account::Field, type: :model do expect(subject.verifiable?).to be false end end - + context 'for text which is blank' do let(:value) { '' } @@ -149,7 +149,7 @@ RSpec.describe Account::Field, type: :model do expect(subject.verifiable?).to be false end end - + context 'for text which is blank' do let(:value) { '' } diff --git a/spec/models/account_alias_spec.rb b/spec/models/account_alias_spec.rb index 27ec215aa..c48b804b2 100644 --- a/spec/models/account_alias_spec.rb +++ b/spec/models/account_alias_spec.rb @@ -1,5 +1,4 @@ require 'rails_helper' RSpec.describe AccountAlias, type: :model do - end diff --git a/spec/models/account_statuses_cleanup_policy_spec.rb b/spec/models/account_statuses_cleanup_policy_spec.rb index 684a1aa41..f11684516 100644 --- a/spec/models/account_statuses_cleanup_policy_spec.rb +++ b/spec/models/account_statuses_cleanup_policy_spec.rb @@ -16,16 +16,15 @@ RSpec.describe AccountStatusesCleanupPolicy, type: :model do context 'when widening a policy' do let!(:account_statuses_cleanup_policy) do Fabricate(:account_statuses_cleanup_policy, - account: account, - keep_direct: true, - keep_pinned: true, - keep_polls: true, - keep_media: true, - keep_self_fav: true, - keep_self_bookmark: true, - min_favs: 1, - min_reblogs: 1 - ) + account: account, + keep_direct: true, + keep_pinned: true, + keep_polls: true, + keep_media: true, + keep_self_fav: true, + keep_self_bookmark: true, + min_favs: 1, + min_reblogs: 1) end before do @@ -96,16 +95,15 @@ RSpec.describe AccountStatusesCleanupPolicy, type: :model do context 'when narrowing a policy' do let!(:account_statuses_cleanup_policy) do Fabricate(:account_statuses_cleanup_policy, - account: account, - keep_direct: false, - keep_pinned: false, - keep_polls: false, - keep_media: false, - keep_self_fav: false, - keep_self_bookmark: false, - min_favs: nil, - min_reblogs: nil - ) + account: account, + keep_direct: false, + keep_pinned: false, + keep_polls: false, + keep_media: false, + keep_self_fav: false, + keep_self_bookmark: false, + min_favs: nil, + min_reblogs: nil) end it 'does not unnecessarily invalidate last_inspected' do @@ -232,7 +230,7 @@ RSpec.describe AccountStatusesCleanupPolicy, type: :model do end describe '#compute_cutoff_id' do - let!(:unrelated_status) { Fabricate(:status, created_at: 3.years.ago) } + let!(:unrelated_status) { Fabricate(:status, created_at: 3.years.ago) } let(:account_statuses_cleanup_policy) { Fabricate(:account_statuses_cleanup_policy, account: account) } subject { account_statuses_cleanup_policy.compute_cutoff_id } diff --git a/spec/models/concerns/account_interactions_spec.rb b/spec/models/concerns/account_interactions_spec.rb index 5cb4a83f7..e628384d0 100644 --- a/spec/models/concerns/account_interactions_spec.rb +++ b/spec/models/concerns/account_interactions_spec.rb @@ -400,7 +400,7 @@ describe AccountInteractions do subject { account.domain_blocking?(domain) } context 'blocking the domain' do - it' returns true' do + it ' returns true' do account_domain_block = Fabricate(:account_domain_block, domain: domain) account.domain_blocks << account_domain_block is_expected.to be true diff --git a/spec/models/device_spec.rb b/spec/models/device_spec.rb index f56fbf978..307552e91 100644 --- a/spec/models/device_spec.rb +++ b/spec/models/device_spec.rb @@ -1,5 +1,4 @@ require 'rails_helper' RSpec.describe Device, type: :model do - end diff --git a/spec/models/encrypted_message_spec.rb b/spec/models/encrypted_message_spec.rb index 1238d57b6..64f9c6912 100644 --- a/spec/models/encrypted_message_spec.rb +++ b/spec/models/encrypted_message_spec.rb @@ -1,5 +1,4 @@ require 'rails_helper' RSpec.describe EncryptedMessage, type: :model do - end diff --git a/spec/models/export_spec.rb b/spec/models/export_spec.rb index 135d7a36b..5202ae9e1 100644 --- a/spec/models/export_spec.rb +++ b/spec/models/export_spec.rb @@ -3,7 +3,7 @@ require 'rails_helper' describe Export do let(:account) { Fabricate(:account) } let(:target_accounts) do - [ {}, { username: 'one', domain: 'local.host' } ].map(&method(:Fabricate).curry(2).call(:account)) + [{}, { username: 'one', domain: 'local.host' }].map(&method(:Fabricate).curry(2).call(:account)) end describe 'to_csv' do diff --git a/spec/models/login_activity_spec.rb b/spec/models/login_activity_spec.rb index ba2d207c9..12d8c4363 100644 --- a/spec/models/login_activity_spec.rb +++ b/spec/models/login_activity_spec.rb @@ -1,5 +1,4 @@ require 'rails_helper' RSpec.describe LoginActivity, type: :model do - end diff --git a/spec/models/one_time_key_spec.rb b/spec/models/one_time_key_spec.rb index 34598334c..4b231c600 100644 --- a/spec/models/one_time_key_spec.rb +++ b/spec/models/one_time_key_spec.rb @@ -1,5 +1,4 @@ require 'rails_helper' RSpec.describe OneTimeKey, type: :model do - end diff --git a/spec/models/system_key_spec.rb b/spec/models/system_key_spec.rb index a138bc131..86f07f964 100644 --- a/spec/models/system_key_spec.rb +++ b/spec/models/system_key_spec.rb @@ -1,5 +1,4 @@ require 'rails_helper' RSpec.describe SystemKey, type: :model do - end diff --git a/spec/models/trends/statuses_spec.rb b/spec/models/trends/statuses_spec.rb index 5f338a65e..98a8c7264 100644 --- a/spec/models/trends/statuses_spec.rb +++ b/spec/models/trends/statuses_spec.rb @@ -76,7 +76,7 @@ RSpec.describe Trends::Statuses do before do 13.times { reblog(status1, today) } 13.times { reblog(status2, today) } - 4.times { reblog(status3, today) } + 4.times { reblog(status3, today) } end context do diff --git a/spec/models/user_role_spec.rb b/spec/models/user_role_spec.rb index 28019593e..abf7d0e27 100644 --- a/spec/models/user_role_spec.rb +++ b/spec/models/user_role_spec.rb @@ -58,7 +58,7 @@ RSpec.describe UserRole, type: :model do end describe '#permissions_as_keys=' do - let(:input) { } + let(:input) {} before do subject.permissions_as_keys = input diff --git a/spec/routing/api_routing_spec.rb b/spec/routing/api_routing_spec.rb index 2683ccb8d..a822fba4c 100644 --- a/spec/routing/api_routing_spec.rb +++ b/spec/routing/api_routing_spec.rb @@ -5,99 +5,99 @@ require 'rails_helper' describe 'API routes' do describe 'Credentials routes' do it 'routes to verify credentials' do - expect(get('/api/v1/accounts/verify_credentials')). - to route_to('api/v1/accounts/credentials#show') + expect(get('/api/v1/accounts/verify_credentials')) + .to route_to('api/v1/accounts/credentials#show') end it 'routes to update credentials' do - expect(patch('/api/v1/accounts/update_credentials')). - to route_to('api/v1/accounts/credentials#update') + expect(patch('/api/v1/accounts/update_credentials')) + .to route_to('api/v1/accounts/credentials#update') end end describe 'Account routes' do it 'routes to statuses' do - expect(get('/api/v1/accounts/user/statuses')). - to route_to('api/v1/accounts/statuses#index', account_id: 'user') + expect(get('/api/v1/accounts/user/statuses')) + .to route_to('api/v1/accounts/statuses#index', account_id: 'user') end it 'routes to followers' do - expect(get('/api/v1/accounts/user/followers')). - to route_to('api/v1/accounts/follower_accounts#index', account_id: 'user') + expect(get('/api/v1/accounts/user/followers')) + .to route_to('api/v1/accounts/follower_accounts#index', account_id: 'user') end it 'routes to following' do - expect(get('/api/v1/accounts/user/following')). - to route_to('api/v1/accounts/following_accounts#index', account_id: 'user') + expect(get('/api/v1/accounts/user/following')) + .to route_to('api/v1/accounts/following_accounts#index', account_id: 'user') end it 'routes to search' do - expect(get('/api/v1/accounts/search')). - to route_to('api/v1/accounts/search#show') + expect(get('/api/v1/accounts/search')) + .to route_to('api/v1/accounts/search#show') end it 'routes to relationships' do - expect(get('/api/v1/accounts/relationships')). - to route_to('api/v1/accounts/relationships#index') + expect(get('/api/v1/accounts/relationships')) + .to route_to('api/v1/accounts/relationships#index') end end describe 'Statuses routes' do it 'routes reblogged_by' do - expect(get('/api/v1/statuses/123/reblogged_by')). - to route_to('api/v1/statuses/reblogged_by_accounts#index', status_id: '123') + expect(get('/api/v1/statuses/123/reblogged_by')) + .to route_to('api/v1/statuses/reblogged_by_accounts#index', status_id: '123') end it 'routes favourited_by' do - expect(get('/api/v1/statuses/123/favourited_by')). - to route_to('api/v1/statuses/favourited_by_accounts#index', status_id: '123') + expect(get('/api/v1/statuses/123/favourited_by')) + .to route_to('api/v1/statuses/favourited_by_accounts#index', status_id: '123') end it 'routes reblog' do - expect(post('/api/v1/statuses/123/reblog')). - to route_to('api/v1/statuses/reblogs#create', status_id: '123') + expect(post('/api/v1/statuses/123/reblog')) + .to route_to('api/v1/statuses/reblogs#create', status_id: '123') end it 'routes unreblog' do - expect(post('/api/v1/statuses/123/unreblog')). - to route_to('api/v1/statuses/reblogs#destroy', status_id: '123') + expect(post('/api/v1/statuses/123/unreblog')) + .to route_to('api/v1/statuses/reblogs#destroy', status_id: '123') end it 'routes favourite' do - expect(post('/api/v1/statuses/123/favourite')). - to route_to('api/v1/statuses/favourites#create', status_id: '123') + expect(post('/api/v1/statuses/123/favourite')) + .to route_to('api/v1/statuses/favourites#create', status_id: '123') end it 'routes unfavourite' do - expect(post('/api/v1/statuses/123/unfavourite')). - to route_to('api/v1/statuses/favourites#destroy', status_id: '123') + expect(post('/api/v1/statuses/123/unfavourite')) + .to route_to('api/v1/statuses/favourites#destroy', status_id: '123') end it 'routes mute' do - expect(post('/api/v1/statuses/123/mute')). - to route_to('api/v1/statuses/mutes#create', status_id: '123') + expect(post('/api/v1/statuses/123/mute')) + .to route_to('api/v1/statuses/mutes#create', status_id: '123') end it 'routes unmute' do - expect(post('/api/v1/statuses/123/unmute')). - to route_to('api/v1/statuses/mutes#destroy', status_id: '123') + expect(post('/api/v1/statuses/123/unmute')) + .to route_to('api/v1/statuses/mutes#destroy', status_id: '123') end end describe 'Timeline routes' do it 'routes to home timeline' do - expect(get('/api/v1/timelines/home')). - to route_to('api/v1/timelines/home#show') + expect(get('/api/v1/timelines/home')) + .to route_to('api/v1/timelines/home#show') end it 'routes to public timeline' do - expect(get('/api/v1/timelines/public')). - to route_to('api/v1/timelines/public#show') + expect(get('/api/v1/timelines/public')) + .to route_to('api/v1/timelines/public#show') end it 'routes to tag timeline' do - expect(get('/api/v1/timelines/tag/test')). - to route_to('api/v1/timelines/tag#show', id: 'test') + expect(get('/api/v1/timelines/tag/test')) + .to route_to('api/v1/timelines/tag#show', id: 'test') end end end diff --git a/spec/routing/well_known_routes_spec.rb b/spec/routing/well_known_routes_spec.rb index 2e25605c2..03a562843 100644 --- a/spec/routing/well_known_routes_spec.rb +++ b/spec/routing/well_known_routes_spec.rb @@ -2,14 +2,14 @@ require 'rails_helper' describe 'the host-meta route' do it 'routes to correct place with xml format' do - expect(get('/.well-known/host-meta')). - to route_to('well_known/host_meta#show', format: 'xml') + expect(get('/.well-known/host-meta')) + .to route_to('well_known/host_meta#show', format: 'xml') end end describe 'the webfinger route' do it 'routes to correct place with json format' do - expect(get('/.well-known/webfinger')). - to route_to('well_known/webfinger#show') + expect(get('/.well-known/webfinger')) + .to route_to('well_known/webfinger#show') end end diff --git a/spec/serializers/rest/account_serializer_spec.rb b/spec/serializers/rest/account_serializer_spec.rb index 5b08d5aca..3bca06b73 100644 --- a/spec/serializers/rest/account_serializer_spec.rb +++ b/spec/serializers/rest/account_serializer_spec.rb @@ -5,7 +5,7 @@ require 'rails_helper' describe REST::AccountSerializer do let(:role) { Fabricate(:user_role, name: 'Role', highlighted: true) } let(:user) { Fabricate(:user, role: role) } - let(:account) { user.account} + let(:account) { user.account } subject { JSON.parse(ActiveModelSerializers::SerializableResource.new(account, serializer: REST::AccountSerializer).to_json) } diff --git a/spec/services/account_statuses_cleanup_service_spec.rb b/spec/services/account_statuses_cleanup_service_spec.rb index 257655c41..a30e14ab6 100644 --- a/spec/services/account_statuses_cleanup_service_spec.rb +++ b/spec/services/account_statuses_cleanup_service_spec.rb @@ -42,8 +42,8 @@ describe AccountStatusesCleanupService, type: :service do context 'when called repeatedly with a budget of 2' do it 'reports 2 then 1 deleted statuses' do - expect(subject.call(account_policy, 2)).to eq 2 - expect(subject.call(account_policy, 2)).to eq 1 + expect(subject.call(account_policy, 2)).to eq 2 + expect(subject.call(account_policy, 2)).to eq 1 end it 'actually deletes the statuses in the expected order' do diff --git a/spec/services/activitypub/fetch_remote_status_service_spec.rb b/spec/services/activitypub/fetch_remote_status_service_spec.rb index a81dcad81..d6145c9b8 100644 --- a/spec/services/activitypub/fetch_remote_status_service_spec.rb +++ b/spec/services/activitypub/fetch_remote_status_service_spec.rb @@ -298,7 +298,7 @@ RSpec.describe ActivityPub::FetchRemoteStatusService, type: :service do first: { type: 'CollectionPage', partOf: "https://foo.bar/@foo/#{i}/replies", - items: ["https://foo.bar/@foo/#{i+1}"], + items: ["https://foo.bar/@foo/#{i + 1}"], }, }, attributedTo: ActivityPub::TagManager.instance.uri_for(sender), diff --git a/spec/services/activitypub/process_account_service_spec.rb b/spec/services/activitypub/process_account_service_spec.rb index 2b20d17b1..40caa6eb0 100644 --- a/spec/services/activitypub/process_account_service_spec.rb +++ b/spec/services/activitypub/process_account_service_spec.rb @@ -172,10 +172,10 @@ RSpec.describe ActivityPub::ProcessAccountService, type: :service do { type: 'Mention', href: "https://foo.test/users/#{i + 1}", - name: "@user#{i + 1 }", + name: "@user#{i + 1}", } ], - to: [ 'as:Public', "https://foo.test/users/#{i + 1}" ] + to: ['as:Public', "https://foo.test/users/#{i + 1}"] }.with_indifferent_access featured_json = { '@context': ['https://www.w3.org/ns/activitystreams'], diff --git a/spec/services/activitypub/process_collection_service_spec.rb b/spec/services/activitypub/process_collection_service_spec.rb index a308cede7..cb60e1cb8 100644 --- a/spec/services/activitypub/process_collection_service_spec.rb +++ b/spec/services/activitypub/process_collection_service_spec.rb @@ -95,11 +95,11 @@ RSpec.describe ActivityPub::ProcessCollectionService, type: :service do context 'when receiving a fabricated status' do let!(:actor) do Fabricate(:account, - username: 'bob', - domain: 'example.com', - uri: 'https://example.com/users/bob', - public_key: "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuuYyoyfsRkYnXRotMsId\nW3euBDDfiv9oVqOxUVC7bhel8KednIMrMCRWFAkgJhbrlzbIkjVr68o1MP9qLcn7\nCmH/BXHp7yhuFTr4byjdJKpwB+/i2jNEsvDH5jR8WTAeTCe0x/QHg21V3F7dSI5m\nCCZ/1dSIyOXLRTWVlfDlm3rE4ntlCo+US3/7oSWbg/4/4qEnt1HC32kvklgScxua\n4LR5ATdoXa5bFoopPWhul7MJ6NyWCyQyScUuGdlj8EN4kmKQJvphKHrI9fvhgOuG\nTvhTR1S5InA4azSSchY0tXEEw/VNxraeX0KPjbgr6DPcwhPd/m0nhVDq0zVyVBBD\nMwIDAQAB\n-----END PUBLIC KEY-----\n", - private_key: nil) + username: 'bob', + domain: 'example.com', + uri: 'https://example.com/users/bob', + public_key: "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuuYyoyfsRkYnXRotMsId\nW3euBDDfiv9oVqOxUVC7bhel8KednIMrMCRWFAkgJhbrlzbIkjVr68o1MP9qLcn7\nCmH/BXHp7yhuFTr4byjdJKpwB+/i2jNEsvDH5jR8WTAeTCe0x/QHg21V3F7dSI5m\nCCZ/1dSIyOXLRTWVlfDlm3rE4ntlCo+US3/7oSWbg/4/4qEnt1HC32kvklgScxua\n4LR5ATdoXa5bFoopPWhul7MJ6NyWCyQyScUuGdlj8EN4kmKQJvphKHrI9fvhgOuG\nTvhTR1S5InA4azSSchY0tXEEw/VNxraeX0KPjbgr6DPcwhPd/m0nhVDq0zVyVBBD\nMwIDAQAB\n-----END PUBLIC KEY-----\n", + private_key: nil) end let(:payload) do @@ -107,7 +107,7 @@ RSpec.describe ActivityPub::ProcessCollectionService, type: :service do '@context': [ 'https://www.w3.org/ns/activitystreams', nil, - {'object': 'https://www.w3.org/ns/activitystreams#object'} + { 'object': 'https://www.w3.org/ns/activitystreams#object' } ], 'id': 'https://example.com/users/bob/fake-status/activity', 'type': 'Create', diff --git a/spec/services/activitypub/process_status_update_service_spec.rb b/spec/services/activitypub/process_status_update_service_spec.rb index 750369d57..04292c507 100644 --- a/spec/services/activitypub/process_status_update_service_spec.rb +++ b/spec/services/activitypub/process_status_update_service_spec.rb @@ -104,20 +104,19 @@ RSpec.describe ActivityPub::ProcessStatusUpdateService, type: :service do end context 'when the status has not been explicitly edited and features a poll' do - let(:account) { Fabricate(:account, domain: 'example.com') } + let(:account) { Fabricate(:account, domain: 'example.com') } let!(:expiration) { 10.days.from_now.utc } let!(:status) do Fabricate(:status, - text: 'Hello world', - account: account, - poll_attributes: { - options: %w(Foo Bar), - account: account, - multiple: false, - hide_totals: false, - expires_at: expiration - } - ) + text: 'Hello world', + account: account, + poll_attributes: { + options: %w(Foo Bar), + account: account, + multiple: false, + hide_totals: false, + expires_at: expiration + }) end let(:payload) do @@ -156,20 +155,19 @@ RSpec.describe ActivityPub::ProcessStatusUpdateService, type: :service do end context 'when the status changes a poll despite being not explicitly marked as updated' do - let(:account) { Fabricate(:account, domain: 'example.com') } + let(:account) { Fabricate(:account, domain: 'example.com') } let!(:expiration) { 10.days.from_now.utc } let!(:status) do Fabricate(:status, - text: 'Hello world', - account: account, - poll_attributes: { - options: %w(Foo Bar), - account: account, - multiple: false, - hide_totals: false, - expires_at: expiration - } - ) + text: 'Hello world', + account: account, + poll_attributes: { + options: %w(Foo Bar), + account: account, + multiple: false, + hide_totals: false, + expires_at: expiration + }) end let(:payload) do diff --git a/spec/services/bootstrap_timeline_service_spec.rb b/spec/services/bootstrap_timeline_service_spec.rb index 16f3e9962..149f6e6df 100644 --- a/spec/services/bootstrap_timeline_service_spec.rb +++ b/spec/services/bootstrap_timeline_service_spec.rb @@ -32,6 +32,5 @@ RSpec.describe BootstrapTimelineService, type: :service do expect(service).to_not have_received(:call) end end - end end diff --git a/spec/services/fetch_oembed_service_spec.rb b/spec/services/fetch_oembed_service_spec.rb index 88f0113ed..da2a8d0d1 100644 --- a/spec/services/fetch_oembed_service_spec.rb +++ b/spec/services/fetch_oembed_service_spec.rb @@ -151,7 +151,6 @@ describe FetchOEmbedService, type: :service do expect(subject.format).to eq :json end end - end context 'when endpoint is cached' do diff --git a/spec/services/import_service_spec.rb b/spec/services/import_service_spec.rb index e2d182920..217d0ee24 100644 --- a/spec/services/import_service_spec.rb +++ b/spec/services/import_service_spec.rb @@ -178,7 +178,7 @@ RSpec.describe ImportService, type: :service do context 'utf-8 encoded domains' do subject { ImportService.new } - let!(:nare) { Fabricate(:account, username: 'nare', domain: 'թութ.հայ', locked: false, protocol: :activitypub, inbox_url: 'https://թութ.հայ/inbox') } + let!(:nare) { Fabricate(:account, username: 'nare', domain: 'թութ.հայ', locked: false, protocol: :activitypub, inbox_url: 'https://թութ.հայ/inbox') } # Make sure to not actually go to the remote server before do @@ -189,7 +189,7 @@ RSpec.describe ImportService, type: :service do let(:import) { Import.create(account: account, type: 'following', data: csv) } it 'follows the listed account' do - expect(account.follow_requests.count).to eq 0 + expect(account.follow_requests.count).to eq 0 subject.call(import) expect(account.follow_requests.count).to eq 1 end diff --git a/spec/services/remove_from_follwers_service_spec.rb b/spec/services/remove_from_follwers_service_spec.rb index a83f6f49a..9b9c846cf 100644 --- a/spec/services/remove_from_follwers_service_spec.rb +++ b/spec/services/remove_from_follwers_service_spec.rb @@ -7,7 +7,7 @@ RSpec.describe RemoveFromFollowersService, type: :service do describe 'local' do let(:sender) { Fabricate(:account, username: 'alice') } - + before do Follow.create(account: sender, target_account: bob) subject.call(bob, sender) diff --git a/spec/services/remove_status_service_spec.rb b/spec/services/remove_status_service_spec.rb index 482068d58..e253052f3 100644 --- a/spec/services/remove_status_service_spec.rb +++ b/spec/services/remove_status_service_spec.rb @@ -37,29 +37,29 @@ RSpec.describe RemoveStatusService, type: :service do it 'sends Delete activity to followers' do subject.call(@status) expect(a_request(:post, 'http://example.com/inbox').with( - body: hash_including({ - 'type' => 'Delete', - 'object' => { - 'type' => 'Tombstone', - 'id' => ActivityPub::TagManager.instance.uri_for(@status), - 'atomUri' => OStatus::TagManager.instance.uri_for(@status), - }, - }) - )).to have_been_made.once + body: hash_including({ + 'type' => 'Delete', + 'object' => { + 'type' => 'Tombstone', + 'id' => ActivityPub::TagManager.instance.uri_for(@status), + 'atomUri' => OStatus::TagManager.instance.uri_for(@status), + }, + }) + )).to have_been_made.once end it 'sends Delete activity to rebloggers' do subject.call(@status) expect(a_request(:post, 'http://example2.com/inbox').with( - body: hash_including({ - 'type' => 'Delete', - 'object' => { - 'type' => 'Tombstone', - 'id' => ActivityPub::TagManager.instance.uri_for(@status), - 'atomUri' => OStatus::TagManager.instance.uri_for(@status), - }, - }) - )).to have_been_made.once + body: hash_including({ + 'type' => 'Delete', + 'object' => { + 'type' => 'Tombstone', + 'id' => ActivityPub::TagManager.instance.uri_for(@status), + 'atomUri' => OStatus::TagManager.instance.uri_for(@status), + }, + }) + )).to have_been_made.once end it 'remove status from notifications' do @@ -78,14 +78,14 @@ RSpec.describe RemoveStatusService, type: :service do it 'sends Undo activity to followers' do subject.call(@status) expect(a_request(:post, 'http://example.com/inbox').with( - body: hash_including({ - 'type' => 'Undo', - 'object' => hash_including({ - 'type' => 'Announce', - 'object' => ActivityPub::TagManager.instance.uri_for(@original_status), - }), - }) - )).to have_been_made.once + body: hash_including({ + 'type' => 'Undo', + 'object' => hash_including({ + 'type' => 'Announce', + 'object' => ActivityPub::TagManager.instance.uri_for(@original_status), + }), + }) + )).to have_been_made.once end end @@ -98,14 +98,14 @@ RSpec.describe RemoveStatusService, type: :service do it 'sends Undo activity to followers' do subject.call(@status) expect(a_request(:post, 'http://example.com/inbox').with( - body: hash_including({ - 'type' => 'Undo', - 'object' => hash_including({ - 'type' => 'Announce', - 'object' => ActivityPub::TagManager.instance.uri_for(@original_status), - }), - }) - )).to have_been_made.once + body: hash_including({ + 'type' => 'Undo', + 'object' => hash_including({ + 'type' => 'Announce', + 'object' => ActivityPub::TagManager.instance.uri_for(@original_status), + }), + }) + )).to have_been_made.once end end end diff --git a/spec/services/resolve_account_service_spec.rb b/spec/services/resolve_account_service_spec.rb index 654606bea..1df30ea57 100644 --- a/spec/services/resolve_account_service_spec.rb +++ b/spec/services/resolve_account_service_spec.rb @@ -190,7 +190,7 @@ RSpec.describe ResolveAccountService, type: :service do context 'with an already-known acct: URI changing ActivityPub id' do let!(:old_account) { Fabricate(:account, username: 'foo', domain: 'ap.example.com', uri: 'https://old.example.com/users/foo', last_webfingered_at: nil) } - let!(:status) { Fabricate(:status, account: old_account, text: 'foo') } + let!(:status) { Fabricate(:status, account: old_account, text: 'foo') } it 'returns new remote account' do account = subject.call('foo@ap.example.com') diff --git a/spec/services/resolve_url_service_spec.rb b/spec/services/resolve_url_service_spec.rb index b3e3defbf..3598311ee 100644 --- a/spec/services/resolve_url_service_spec.rb +++ b/spec/services/resolve_url_service_spec.rb @@ -133,7 +133,7 @@ describe ResolveURLService, type: :service do let!(:status) { Fabricate(:status, account: poster, visibility: :public) } let(:url) { 'https://link.to/foobar' } let(:status_url) { ActivityPub::TagManager.instance.url_for(status) } - let(:uri) { ActivityPub::TagManager.instance.uri_for(status) } + let(:uri) { ActivityPub::TagManager.instance.uri_for(status) } before do stub_request(:get, url).to_return(status: 302, headers: { 'Location' => status_url }) diff --git a/spec/services/update_status_service_spec.rb b/spec/services/update_status_service_spec.rb index 16e981d2b..a7364ca8b 100644 --- a/spec/services/update_status_service_spec.rb +++ b/spec/services/update_status_service_spec.rb @@ -111,7 +111,7 @@ RSpec.describe UpdateStatusService, type: :service do context 'when poll changes' do let(:account) { Fabricate(:account) } - let!(:status) { Fabricate(:status, text: 'Foo', account: account, poll_attributes: {options: %w(Foo Bar), account: account, multiple: false, hide_totals: false, expires_at: 7.days.from_now }) } + let!(:status) { Fabricate(:status, text: 'Foo', account: account, poll_attributes: { options: %w(Foo Bar), account: account, multiple: false, hide_totals: false, expires_at: 7.days.from_now }) } let!(:poll) { status.poll } let!(:voter) { Fabricate(:account) } diff --git a/spec/support/stories/profile_stories.rb b/spec/support/stories/profile_stories.rb index 0c4a14d1c..de7ae17e6 100644 --- a/spec/support/stories/profile_stories.rb +++ b/spec/support/stories/profile_stories.rb @@ -20,8 +20,8 @@ module ProfileStories end def with_alice_as_local_user - @alice_bio = '@alice and @bob are fictional characters commonly used as'\ - 'placeholder names in #cryptology, as well as #science and'\ + @alice_bio = '@alice and @bob are fictional characters commonly used as' \ + 'placeholder names in #cryptology, as well as #science and' \ 'engineering 📖 literature. Not affiliated with @pepe.' @alice = Fabricate( diff --git a/spec/validators/note_length_validator_spec.rb b/spec/validators/note_length_validator_spec.rb index 6e9b4e132..390ac8d90 100644 --- a/spec/validators/note_length_validator_spec.rb +++ b/spec/validators/note_length_validator_spec.rb @@ -15,7 +15,7 @@ describe NoteLengthValidator do end it 'counts URLs as 23 characters flat' do - text = ('a' * 476) + " http://#{'b' * 30}.com/example" + text = ('a' * 476) + " http://#{'b' * 30}.com/example" account = double(note: text, errors: double(add: nil)) subject.validate_each(account, 'note', text) @@ -23,7 +23,7 @@ describe NoteLengthValidator do end it 'does not count non-autolinkable URLs as 23 characters flat' do - text = ('a' * 476) + "http://#{'b' * 30}.com/example" + text = ('a' * 476) + "http://#{'b' * 30}.com/example" account = double(note: text, errors: double(add: nil)) subject.validate_each(account, 'note', text) diff --git a/spec/validators/unreserved_username_validator_spec.rb b/spec/validators/unreserved_username_validator_spec.rb index 746b3866c..e2f051b08 100644 --- a/spec/validators/unreserved_username_validator_spec.rb +++ b/spec/validators/unreserved_username_validator_spec.rb @@ -11,10 +11,10 @@ RSpec.describe UnreservedUsernameValidator, type: :validator do let(:validator) { described_class.new } let(:account) { double(username: username, errors: errors) } - let(:errors ) { double(add: nil) } + let(:errors) { double(add: nil) } context '@username.blank?' do - let(:username) { nil } + let(:username) { nil } it 'not calls errors.add' do expect(errors).not_to have_received(:add).with(:username, any_args) @@ -22,7 +22,7 @@ RSpec.describe UnreservedUsernameValidator, type: :validator do end context '!@username.blank?' do - let(:username) { 'f' } + let(:username) { 'f' } context 'reserved_username?' do let(:reserved_username) { true } diff --git a/spec/workers/activitypub/distribution_worker_spec.rb b/spec/workers/activitypub/distribution_worker_spec.rb index 3a5900d9b..7f63e197b 100644 --- a/spec/workers/activitypub/distribution_worker_spec.rb +++ b/spec/workers/activitypub/distribution_worker_spec.rb @@ -34,7 +34,7 @@ describe ActivityPub::DistributionWorker do end context 'with direct status' do - let(:mentioned_account) { Fabricate(:account, protocol: :activitypub, inbox_url: 'https://foo.bar/inbox')} + let(:mentioned_account) { Fabricate(:account, protocol: :activitypub, inbox_url: 'https://foo.bar/inbox') } before do status.update(visibility: :direct) diff --git a/spec/workers/activitypub/move_distribution_worker_spec.rb b/spec/workers/activitypub/move_distribution_worker_spec.rb index af8c44cc0..57941065a 100644 --- a/spec/workers/activitypub/move_distribution_worker_spec.rb +++ b/spec/workers/activitypub/move_distribution_worker_spec.rb @@ -3,7 +3,7 @@ require 'rails_helper' describe ActivityPub::MoveDistributionWorker do subject { described_class.new } - let(:migration) { Fabricate(:account_migration) } + let(:migration) { Fabricate(:account_migration) } let(:follower) { Fabricate(:account, protocol: :activitypub, inbox_url: 'http://example.com') } let(:blocker) { Fabricate(:account, protocol: :activitypub, inbox_url: 'http://example2.com') } @@ -15,9 +15,9 @@ describe ActivityPub::MoveDistributionWorker do it 'delivers to followers and known blockers' do expect_push_bulk_to_match(ActivityPub::DeliveryWorker, [ - [kind_of(String), migration.account.id, 'http://example.com'], - [kind_of(String), migration.account.id, 'http://example2.com'] - ]) + [kind_of(String), migration.account.id, 'http://example.com'], + [kind_of(String), migration.account.id, 'http://example2.com'] + ]) subject.perform(migration.id) end end diff --git a/spec/workers/scheduler/accounts_statuses_cleanup_scheduler_spec.rb b/spec/workers/scheduler/accounts_statuses_cleanup_scheduler_spec.rb index 8f20725c8..8faf04836 100644 --- a/spec/workers/scheduler/accounts_statuses_cleanup_scheduler_spec.rb +++ b/spec/workers/scheduler/accounts_statuses_cleanup_scheduler_spec.rb @@ -82,7 +82,7 @@ describe Scheduler::AccountsStatusesCleanupScheduler do describe '#get_budget' do context 'on a single thread' do - let(:process_set_stub) { [ { 'concurrency' => 1, 'queues' => ['push', 'default'] } ] } + let(:process_set_stub) { [{ 'concurrency' => 1, 'queues' => ['push', 'default'] }] } it 'returns a low value' do expect(subject.compute_budget).to be < 10 -- cgit From 2177daeae92b77be6797ba8f2ab6ebe1e641e078 Mon Sep 17 00:00:00 2001 From: Nick Schonning Date: Sat, 18 Feb 2023 17:09:40 -0500 Subject: Autofix Rubocop Style/RedundantBegin (#23703) --- .rubocop_todo.yml | 73 ---------------------- app/controllers/admin/dashboard_controller.rb | 12 ++-- app/controllers/api/v1/announcements_controller.rb | 4 +- app/controllers/api/v1/trends/links_controller.rb | 12 ++-- .../api/v1/trends/statuses_controller.rb | 12 ++-- app/controllers/api/v1/trends/tags_controller.rb | 12 ++-- app/controllers/concerns/rate_limit_headers.rb | 12 ++-- .../concerns/two_factor_authentication_concern.rb | 12 ++-- app/helpers/admin/dashboard_helper.rb | 24 ++++--- app/helpers/admin/trends/statuses_helper.rb | 12 ++-- app/helpers/branding_helper.rb | 14 ++--- app/helpers/domain_control_helper.rb | 12 ++-- app/helpers/formatting_helper.rb | 44 ++++++------- app/helpers/instance_helper.rb | 12 ++-- app/helpers/jsonld_helper.rb | 16 +++-- app/lib/activity_tracker.rb | 14 ++--- app/lib/activitypub/activity/create.rb | 38 ++++++----- app/lib/activitypub/forwarder.rb | 12 ++-- .../dimension/software_versions_dimension.rb | 12 ++-- .../metrics/dimension/space_usage_dimension.rb | 12 ++-- app/lib/extractor.rb | 10 ++- app/lib/importer/statuses_index_importer.rb | 12 ++-- app/lib/link_details_extractor.rb | 30 +++++---- app/lib/request.rb | 34 +++++----- app/models/account.rb | 13 ++-- app/models/account/field.rb | 12 ++-- app/models/admin/account_action.rb | 12 ++-- app/models/announcement.rb | 12 ++-- app/models/concerns/account_merging.rb | 16 ++--- app/models/concerns/pam_authenticable.rb | 12 ++-- app/models/email_domain_block.rb | 12 ++-- app/models/form/admin_settings.rb | 12 ++-- app/models/form/custom_emoji_batch.rb | 12 ++-- app/models/notification.rb | 12 ++-- app/models/remote_follow.rb | 12 ++-- app/models/status.rb | 13 ++-- app/models/status_edit.rb | 14 ++--- app/models/trends/links.rb | 24 +++---- app/models/trends/statuses.rb | 26 ++++---- app/models/trends/tag_filter.rb | 12 ++-- app/models/trends/tags.rb | 12 ++-- app/models/web/push_subscription.rb | 24 +++---- app/presenters/tag_relationships_presenter.rb | 12 ++-- app/services/account_search_service.rb | 16 +++-- .../fetch_featured_tags_collection_service.rb | 14 ++--- .../activitypub/fetch_remote_status_service.rb | 12 ++-- app/services/fetch_link_card_service.rb | 18 +++--- app/services/process_mentions_service.rb | 12 ++-- app/services/reblog_service.rb | 12 ++-- app/services/resolve_account_service.rb | 12 ++-- app/validators/domain_validator.rb | 12 ++-- app/validators/existing_username_validator.rb | 14 ++--- app/validators/import_validator.rb | 12 ++-- app/workers/backup_worker.rb | 10 ++- app/workers/post_process_media_worker.rb | 12 ++-- .../scheduler/follow_recommendations_scheduler.rb | 12 ++-- .../20180528141303_fix_accounts_unique_index.rb | 16 ++--- db/migrate/20180812173710_copy_status_stats.rb | 10 ++- db/migrate/20181116173541_copy_account_stats.rb | 10 ++- lib/mastodon/accounts_cli.rb | 28 ++++----- lib/mastodon/cli_helper.rb | 42 ++++++------- lib/mastodon/ip_blocks_cli.rb | 12 ++-- lib/mastodon/maintenance_cli.rb | 64 +++++++------------ lib/mastodon/media_cli.rb | 12 ++-- lib/mastodon/search_cli.rb | 12 ++-- lib/mastodon/upgrade_cli.rb | 18 +++--- lib/paperclip/color_extractor.rb | 12 ++-- lib/sanitize_ext/sanitize_config.rb | 12 ++-- lib/tasks/db.rake | 14 ++--- 69 files changed, 462 insertions(+), 699 deletions(-) (limited to 'app/lib/activitypub/activity/create.rb') diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 73dae59c5..7620025cf 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -2958,79 +2958,6 @@ Style/RedundantArgument: - 'app/helpers/application_helper.rb' - 'lib/tasks/emojis.rake' -# Offense count: 83 -# This cop supports safe autocorrection (--autocorrect). -Style/RedundantBegin: - Exclude: - - 'app/controllers/admin/dashboard_controller.rb' - - 'app/controllers/api/v1/announcements_controller.rb' - - 'app/controllers/api/v1/trends/links_controller.rb' - - 'app/controllers/api/v1/trends/statuses_controller.rb' - - 'app/controllers/api/v1/trends/tags_controller.rb' - - 'app/controllers/concerns/rate_limit_headers.rb' - - 'app/controllers/concerns/two_factor_authentication_concern.rb' - - 'app/helpers/admin/dashboard_helper.rb' - - 'app/helpers/admin/trends/statuses_helper.rb' - - 'app/helpers/branding_helper.rb' - - 'app/helpers/domain_control_helper.rb' - - 'app/helpers/formatting_helper.rb' - - 'app/helpers/instance_helper.rb' - - 'app/helpers/jsonld_helper.rb' - - 'app/lib/activity_tracker.rb' - - 'app/lib/activitypub/activity/create.rb' - - 'app/lib/activitypub/forwarder.rb' - - 'app/lib/admin/metrics/dimension/software_versions_dimension.rb' - - 'app/lib/admin/metrics/dimension/space_usage_dimension.rb' - - 'app/lib/extractor.rb' - - 'app/lib/importer/statuses_index_importer.rb' - - 'app/lib/link_details_extractor.rb' - - 'app/lib/request.rb' - - 'app/models/account.rb' - - 'app/models/account/field.rb' - - 'app/models/admin/account_action.rb' - - 'app/models/announcement.rb' - - 'app/models/concerns/account_merging.rb' - - 'app/models/concerns/pam_authenticable.rb' - - 'app/models/email_domain_block.rb' - - 'app/models/form/admin_settings.rb' - - 'app/models/form/custom_emoji_batch.rb' - - 'app/models/notification.rb' - - 'app/models/remote_follow.rb' - - 'app/models/status.rb' - - 'app/models/status_edit.rb' - - 'app/models/trends/links.rb' - - 'app/models/trends/statuses.rb' - - 'app/models/trends/tag_filter.rb' - - 'app/models/trends/tags.rb' - - 'app/models/web/push_subscription.rb' - - 'app/presenters/tag_relationships_presenter.rb' - - 'app/services/account_search_service.rb' - - 'app/services/activitypub/fetch_featured_tags_collection_service.rb' - - 'app/services/activitypub/fetch_remote_status_service.rb' - - 'app/services/fetch_link_card_service.rb' - - 'app/services/process_mentions_service.rb' - - 'app/services/reblog_service.rb' - - 'app/services/resolve_account_service.rb' - - 'app/validators/domain_validator.rb' - - 'app/validators/existing_username_validator.rb' - - 'app/validators/import_validator.rb' - - 'app/workers/backup_worker.rb' - - 'app/workers/post_process_media_worker.rb' - - 'app/workers/scheduler/follow_recommendations_scheduler.rb' - - 'db/migrate/20180528141303_fix_accounts_unique_index.rb' - - 'db/migrate/20180812173710_copy_status_stats.rb' - - 'db/migrate/20181116173541_copy_account_stats.rb' - - 'lib/mastodon/accounts_cli.rb' - - 'lib/mastodon/cli_helper.rb' - - 'lib/mastodon/ip_blocks_cli.rb' - - 'lib/mastodon/maintenance_cli.rb' - - 'lib/mastodon/media_cli.rb' - - 'lib/mastodon/search_cli.rb' - - 'lib/mastodon/upgrade_cli.rb' - - 'lib/paperclip/color_extractor.rb' - - 'lib/sanitize_ext/sanitize_config.rb' - - 'lib/tasks/db.rake' - # Offense count: 16 # This cop supports safe autocorrection (--autocorrect). Style/RedundantRegexpCharacterClass: diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb index 924b623ad..099512248 100644 --- a/app/controllers/admin/dashboard_controller.rb +++ b/app/controllers/admin/dashboard_controller.rb @@ -18,13 +18,11 @@ module Admin private def redis_info - @redis_info ||= begin - if redis.is_a?(Redis::Namespace) - redis.redis.info - else - redis.info - end - end + @redis_info ||= if redis.is_a?(Redis::Namespace) + redis.redis.info + else + redis.info + end end end end diff --git a/app/controllers/api/v1/announcements_controller.rb b/app/controllers/api/v1/announcements_controller.rb index ee79fc19f..82e9cf7de 100644 --- a/app/controllers/api/v1/announcements_controller.rb +++ b/app/controllers/api/v1/announcements_controller.rb @@ -18,9 +18,7 @@ class Api::V1::AnnouncementsController < Api::BaseController private def set_announcements - @announcements = begin - Announcement.published.chronological - end + @announcements = Announcement.published.chronological end def set_announcement diff --git a/app/controllers/api/v1/trends/links_controller.rb b/app/controllers/api/v1/trends/links_controller.rb index 8ff3b364e..3ce20fb78 100644 --- a/app/controllers/api/v1/trends/links_controller.rb +++ b/app/controllers/api/v1/trends/links_controller.rb @@ -18,13 +18,11 @@ class Api::V1::Trends::LinksController < Api::BaseController end def set_links - @links = begin - if enabled? - links_from_trends.offset(offset_param).limit(limit_param(DEFAULT_LINKS_LIMIT)) - else - [] - end - end + @links = if enabled? + links_from_trends.offset(offset_param).limit(limit_param(DEFAULT_LINKS_LIMIT)) + else + [] + end end def links_from_trends diff --git a/app/controllers/api/v1/trends/statuses_controller.rb b/app/controllers/api/v1/trends/statuses_controller.rb index c275d5fc8..3aab92477 100644 --- a/app/controllers/api/v1/trends/statuses_controller.rb +++ b/app/controllers/api/v1/trends/statuses_controller.rb @@ -16,13 +16,11 @@ class Api::V1::Trends::StatusesController < Api::BaseController end def set_statuses - @statuses = begin - if enabled? - cache_collection(statuses_from_trends.offset(offset_param).limit(limit_param(DEFAULT_STATUSES_LIMIT)), Status) - else - [] - end - end + @statuses = if enabled? + cache_collection(statuses_from_trends.offset(offset_param).limit(limit_param(DEFAULT_STATUSES_LIMIT)), Status) + else + [] + end end def statuses_from_trends diff --git a/app/controllers/api/v1/trends/tags_controller.rb b/app/controllers/api/v1/trends/tags_controller.rb index 21adfa2a1..75c3ed218 100644 --- a/app/controllers/api/v1/trends/tags_controller.rb +++ b/app/controllers/api/v1/trends/tags_controller.rb @@ -18,13 +18,11 @@ class Api::V1::Trends::TagsController < Api::BaseController end def set_tags - @tags = begin - if enabled? - tags_from_trends.offset(offset_param).limit(limit_param(DEFAULT_TAGS_LIMIT)) - else - [] - end - end + @tags = if enabled? + tags_from_trends.offset(offset_param).limit(limit_param(DEFAULT_TAGS_LIMIT)) + else + [] + end end def tags_from_trends diff --git a/app/controllers/concerns/rate_limit_headers.rb b/app/controllers/concerns/rate_limit_headers.rb index b21abfb03..30702f00e 100644 --- a/app/controllers/concerns/rate_limit_headers.rb +++ b/app/controllers/concerns/rate_limit_headers.rb @@ -6,13 +6,11 @@ module RateLimitHeaders class_methods do def override_rate_limit_headers(method_name, options = {}) around_action(only: method_name, if: :current_account) do |_controller, block| - begin - block.call - ensure - rate_limiter = RateLimiter.new(current_account, options) - rate_limit_headers = rate_limiter.to_headers - response.headers.merge!(rate_limit_headers) unless response.headers['X-RateLimit-Remaining'].present? && rate_limit_headers['X-RateLimit-Remaining'].to_i > response.headers['X-RateLimit-Remaining'].to_i - end + block.call + ensure + rate_limiter = RateLimiter.new(current_account, options) + rate_limit_headers = rate_limiter.to_headers + response.headers.merge!(rate_limit_headers) unless response.headers['X-RateLimit-Remaining'].present? && rate_limit_headers['X-RateLimit-Remaining'].to_i > response.headers['X-RateLimit-Remaining'].to_i end end end diff --git a/app/controllers/concerns/two_factor_authentication_concern.rb b/app/controllers/concerns/two_factor_authentication_concern.rb index 27f2367a8..e69b67a79 100644 --- a/app/controllers/concerns/two_factor_authentication_concern.rb +++ b/app/controllers/concerns/two_factor_authentication_concern.rb @@ -79,13 +79,11 @@ module TwoFactorAuthenticationConcern @body_classes = 'lighter' @webauthn_enabled = user.webauthn_enabled? - @scheme_type = begin - if user.webauthn_enabled? && user_params[:otp_attempt].blank? - 'webauthn' - else - 'totp' - end - end + @scheme_type = if user.webauthn_enabled? && user_params[:otp_attempt].blank? + 'webauthn' + else + 'totp' + end set_locale { render :two_factor } end diff --git a/app/helpers/admin/dashboard_helper.rb b/app/helpers/admin/dashboard_helper.rb index c21d41341..6096ff138 100644 --- a/app/helpers/admin/dashboard_helper.rb +++ b/app/helpers/admin/dashboard_helper.rb @@ -19,19 +19,17 @@ module Admin::DashboardHelper end def relevant_account_timestamp(account) - timestamp, exact = begin - if account.user_current_sign_in_at && account.user_current_sign_in_at < 24.hours.ago - [account.user_current_sign_in_at, true] - elsif account.user_current_sign_in_at - [account.user_current_sign_in_at, false] - elsif account.user_pending? - [account.user_created_at, true] - elsif account.last_status_at.present? - [account.last_status_at, true] - else - [nil, false] - end - end + timestamp, exact = if account.user_current_sign_in_at && account.user_current_sign_in_at < 24.hours.ago + [account.user_current_sign_in_at, true] + elsif account.user_current_sign_in_at + [account.user_current_sign_in_at, false] + elsif account.user_pending? + [account.user_created_at, true] + elsif account.last_status_at.present? + [account.last_status_at, true] + else + [nil, false] + end return '-' if timestamp.nil? return t('generic.today') unless exact diff --git a/app/helpers/admin/trends/statuses_helper.rb b/app/helpers/admin/trends/statuses_helper.rb index 214c1e2a6..79fee44dc 100644 --- a/app/helpers/admin/trends/statuses_helper.rb +++ b/app/helpers/admin/trends/statuses_helper.rb @@ -2,13 +2,11 @@ module Admin::Trends::StatusesHelper def one_line_preview(status) - text = begin - if status.local? - status.text.split("\n").first - else - Nokogiri::HTML(status.text).css('html > body > *').first&.text - end - end + text = if status.local? + status.text.split("\n").first + else + Nokogiri::HTML(status.text).css('html > body > *').first&.text + end return '' if text.blank? diff --git a/app/helpers/branding_helper.rb b/app/helpers/branding_helper.rb index ad7702aea..548c95411 100644 --- a/app/helpers/branding_helper.rb +++ b/app/helpers/branding_helper.rb @@ -23,14 +23,12 @@ module BrandingHelper end def render_symbol(version = :icon) - path = begin - case version - when :icon - 'logo-symbol-icon.svg' - when :wordmark - 'logo-symbol-wordmark.svg' - end - end + path = case version + when :icon + 'logo-symbol-icon.svg' + when :wordmark + 'logo-symbol-wordmark.svg' + end render(file: Rails.root.join('app', 'javascript', 'images', path)).html_safe # rubocop:disable Rails/OutputSafety end diff --git a/app/helpers/domain_control_helper.rb b/app/helpers/domain_control_helper.rb index ac60cad29..ffcf375ea 100644 --- a/app/helpers/domain_control_helper.rb +++ b/app/helpers/domain_control_helper.rb @@ -4,13 +4,11 @@ module DomainControlHelper def domain_not_allowed?(uri_or_domain) return if uri_or_domain.blank? - domain = begin - if uri_or_domain.include?('://') - Addressable::URI.parse(uri_or_domain).host - else - uri_or_domain - end - end + domain = if uri_or_domain.include?('://') + Addressable::URI.parse(uri_or_domain).host + else + uri_or_domain + end if whitelist_mode? !DomainAllow.allowed?(domain) diff --git a/app/helpers/formatting_helper.rb b/app/helpers/formatting_helper.rb index c70931489..d390b9bc9 100644 --- a/app/helpers/formatting_helper.rb +++ b/app/helpers/formatting_helper.rb @@ -21,30 +21,26 @@ module FormattingHelper def rss_status_content_format(status) html = status_content_format(status) - before_html = begin - if status.spoiler_text? - tag.p do - tag.strong do - I18n.t('rss.content_warning', locale: available_locale_or_nil(status.language) || I18n.default_locale) - end - - status.spoiler_text - end + tag.hr - end - end - - after_html = begin - if status.preloadable_poll - tag.p do - safe_join( - status.preloadable_poll.options.map do |o| - tag.send(status.preloadable_poll.multiple? ? 'checkbox' : 'radio', o, disabled: true) - end, - tag.br - ) - end - end - end + before_html = if status.spoiler_text? + tag.p do + tag.strong do + I18n.t('rss.content_warning', locale: available_locale_or_nil(status.language) || I18n.default_locale) + end + + status.spoiler_text + end + tag.hr + end + + after_html = if status.preloadable_poll + tag.p do + safe_join( + status.preloadable_poll.options.map do |o| + tag.send(status.preloadable_poll.multiple? ? 'checkbox' : 'radio', o, disabled: true) + end, + tag.br + ) + end + end prerender_custom_emojis( safe_join([before_html, html, after_html]), diff --git a/app/helpers/instance_helper.rb b/app/helpers/instance_helper.rb index daacb535b..bedfe6f30 100644 --- a/app/helpers/instance_helper.rb +++ b/app/helpers/instance_helper.rb @@ -10,13 +10,11 @@ module InstanceHelper end def description_for_sign_up - prefix = begin - if @invite.present? - I18n.t('auth.description.prefix_invited_by_user', name: @invite.user.account.username) - else - I18n.t('auth.description.prefix_sign_up') - end - end + prefix = if @invite.present? + I18n.t('auth.description.prefix_invited_by_user', name: @invite.user.account.username) + else + I18n.t('auth.description.prefix_sign_up') + end safe_join([prefix, I18n.t('auth.description.suffix')], ' ') end diff --git a/app/helpers/jsonld_helper.rb b/app/helpers/jsonld_helper.rb index e5787fd47..24362b61e 100644 --- a/app/helpers/jsonld_helper.rb +++ b/app/helpers/jsonld_helper.rb @@ -26,15 +26,13 @@ module JsonLdHelper # The url attribute can be a string, an array of strings, or an array of objects. # The objects could include a mimeType. Not-included mimeType means it's text/html. def url_to_href(value, preferred_type = nil) - single_value = begin - if value.is_a?(Array) && !value.first.is_a?(String) - value.find { |link| preferred_type.nil? || ((link['mimeType'].presence || 'text/html') == preferred_type) } - elsif value.is_a?(Array) - value.first - else - value - end - end + single_value = if value.is_a?(Array) && !value.first.is_a?(String) + value.find { |link| preferred_type.nil? || ((link['mimeType'].presence || 'text/html') == preferred_type) } + elsif value.is_a?(Array) + value.first + else + value + end if single_value.nil? || single_value.is_a?(String) single_value diff --git a/app/lib/activity_tracker.rb b/app/lib/activity_tracker.rb index 6d3401b37..8829d8605 100644 --- a/app/lib/activity_tracker.rb +++ b/app/lib/activity_tracker.rb @@ -27,14 +27,12 @@ class ActivityTracker (start_at.to_date...end_at.to_date).map do |date| key = key_at(date.to_time(:utc)) - value = begin - case @type - when :basic - redis.get(key).to_i - when :unique - redis.pfcount(key) - end - end + value = case @type + when :basic + redis.get(key).to_i + when :unique + redis.pfcount(key) + end [date, value] end diff --git a/app/lib/activitypub/activity/create.rb b/app/lib/activitypub/activity/create.rb index f82112c02..e2355bfbc 100644 --- a/app/lib/activitypub/activity/create.rb +++ b/app/lib/activitypub/activity/create.rb @@ -108,26 +108,24 @@ class ActivityPub::Activity::Create < ActivityPub::Activity def process_status_params @status_parser = ActivityPub::Parser::StatusParser.new(@json, followers_collection: @account.followers_url) - @params = begin - { - uri: @status_parser.uri, - url: @status_parser.url || @status_parser.uri, - account: @account, - text: converted_object_type? ? converted_text : (@status_parser.text || ''), - language: @status_parser.language, - spoiler_text: converted_object_type? ? '' : (@status_parser.spoiler_text || ''), - created_at: @status_parser.created_at, - edited_at: @status_parser.edited_at && @status_parser.edited_at != @status_parser.created_at ? @status_parser.edited_at : nil, - override_timestamps: @options[:override_timestamps], - reply: @status_parser.reply, - sensitive: @account.sensitized? || @status_parser.sensitive || false, - visibility: @status_parser.visibility, - thread: replied_to_status, - conversation: conversation_from_uri(@object['conversation']), - media_attachment_ids: process_attachments.take(4).map(&:id), - poll: process_poll, - } - end + @params = { + uri: @status_parser.uri, + url: @status_parser.url || @status_parser.uri, + account: @account, + text: converted_object_type? ? converted_text : (@status_parser.text || ''), + language: @status_parser.language, + spoiler_text: converted_object_type? ? '' : (@status_parser.spoiler_text || ''), + created_at: @status_parser.created_at, + edited_at: @status_parser.edited_at && @status_parser.edited_at != @status_parser.created_at ? @status_parser.edited_at : nil, + override_timestamps: @options[:override_timestamps], + reply: @status_parser.reply, + sensitive: @account.sensitized? || @status_parser.sensitive || false, + visibility: @status_parser.visibility, + thread: replied_to_status, + conversation: conversation_from_uri(@object['conversation']), + media_attachment_ids: process_attachments.take(4).map(&:id), + poll: process_poll, + } end def process_audience diff --git a/app/lib/activitypub/forwarder.rb b/app/lib/activitypub/forwarder.rb index 4206b9d82..b01d63e58 100644 --- a/app/lib/activitypub/forwarder.rb +++ b/app/lib/activitypub/forwarder.rb @@ -28,13 +28,11 @@ class ActivityPub::Forwarder end def signature_account_id - @signature_account_id ||= begin - if in_reply_to_local? - in_reply_to.account_id - else - reblogged_by_account_ids.first - end - end + @signature_account_id ||= if in_reply_to_local? + in_reply_to.account_id + else + reblogged_by_account_ids.first + end end def inboxes diff --git a/app/lib/admin/metrics/dimension/software_versions_dimension.rb b/app/lib/admin/metrics/dimension/software_versions_dimension.rb index 816615f99..9ab3776c9 100644 --- a/app/lib/admin/metrics/dimension/software_versions_dimension.rb +++ b/app/lib/admin/metrics/dimension/software_versions_dimension.rb @@ -58,12 +58,10 @@ class Admin::Metrics::Dimension::SoftwareVersionsDimension < Admin::Metrics::Dim end def redis_info - @redis_info ||= begin - if redis.is_a?(Redis::Namespace) - redis.redis.info - else - redis.info - end - end + @redis_info ||= if redis.is_a?(Redis::Namespace) + redis.redis.info + else + redis.info + end end end diff --git a/app/lib/admin/metrics/dimension/space_usage_dimension.rb b/app/lib/admin/metrics/dimension/space_usage_dimension.rb index 5867c5bab..cc8560890 100644 --- a/app/lib/admin/metrics/dimension/space_usage_dimension.rb +++ b/app/lib/admin/metrics/dimension/space_usage_dimension.rb @@ -59,12 +59,10 @@ class Admin::Metrics::Dimension::SpaceUsageDimension < Admin::Metrics::Dimension end def redis_info - @redis_info ||= begin - if redis.is_a?(Redis::Namespace) - redis.redis.info - else - redis.info - end - end + @redis_info ||= if redis.is_a?(Redis::Namespace) + redis.redis.info + else + redis.info + end end end diff --git a/app/lib/extractor.rb b/app/lib/extractor.rb index 1eba689ef..540bbe1a9 100644 --- a/app/lib/extractor.rb +++ b/app/lib/extractor.rb @@ -8,12 +8,10 @@ module Extractor module_function def extract_entities_with_indices(text, options = {}, &block) - entities = begin - extract_urls_with_indices(text, options) + - extract_hashtags_with_indices(text, check_url_overlap: false) + - extract_mentions_or_lists_with_indices(text) + - extract_extra_uris_with_indices(text) - end + entities = extract_urls_with_indices(text, options) + + extract_hashtags_with_indices(text, check_url_overlap: false) + + extract_mentions_or_lists_with_indices(text) + + extract_extra_uris_with_indices(text) return [] if entities.empty? diff --git a/app/lib/importer/statuses_index_importer.rb b/app/lib/importer/statuses_index_importer.rb index 5b5153d5c..b0721c2e0 100644 --- a/app/lib/importer/statuses_index_importer.rb +++ b/app/lib/importer/statuses_index_importer.rb @@ -24,13 +24,11 @@ class Importer::StatusesIndexImporter < Importer::BaseImporter # is called before rendering the data and we need to filter based # on the results of the filter, so this filtering happens here instead bulk.map! do |entry| - new_entry = begin - if entry[:index] && entry.dig(:index, :data, 'searchable_by').blank? - { delete: entry[:index].except(:data) } - else - entry - end - end + new_entry = if entry[:index] && entry.dig(:index, :data, 'searchable_by').blank? + { delete: entry[:index].except(:data) } + else + entry + end if new_entry[:index] indexed += 1 diff --git a/app/lib/link_details_extractor.rb b/app/lib/link_details_extractor.rb index 2e0672abe..74a7d0f3b 100644 --- a/app/lib/link_details_extractor.rb +++ b/app/lib/link_details_extractor.rb @@ -232,26 +232,24 @@ class LinkDetailsExtractor end def structured_data - @structured_data ||= begin - # Some publications have more than one JSON-LD definition on the page, - # and some of those definitions aren't valid JSON either, so we have - # to loop through here until we find something that is the right type - # and doesn't break - document.xpath('//script[@type="application/ld+json"]').filter_map do |element| - json_ld = element.content&.gsub(CDATA_JUNK_PATTERN, '') + # Some publications have more than one JSON-LD definition on the page, + # and some of those definitions aren't valid JSON either, so we have + # to loop through here until we find something that is the right type + # and doesn't break + @structured_data ||= document.xpath('//script[@type="application/ld+json"]').filter_map do |element| + json_ld = element.content&.gsub(CDATA_JUNK_PATTERN, '') - next if json_ld.blank? + next if json_ld.blank? - structured_data = StructuredData.new(html_entities.decode(json_ld)) + structured_data = StructuredData.new(html_entities.decode(json_ld)) - next unless structured_data.valid? + next unless structured_data.valid? - structured_data - rescue Oj::ParseError, EncodingError - Rails.logger.debug { "Invalid JSON-LD in #{@original_url}" } - next - end.first - end + structured_data + rescue Oj::ParseError, EncodingError + Rails.logger.debug { "Invalid JSON-LD in #{@original_url}" } + next + end.first end def document diff --git a/app/lib/request.rb b/app/lib/request.rb index 0508169dc..be6a69b3f 100644 --- a/app/lib/request.rb +++ b/app/lib/request.rb @@ -215,26 +215,24 @@ class Request addr_by_socket = {} addresses.each do |address| - begin - check_private_address(address, host) + check_private_address(address, host) - sock = ::Socket.new(address.is_a?(Resolv::IPv6) ? ::Socket::AF_INET6 : ::Socket::AF_INET, ::Socket::SOCK_STREAM, 0) - sockaddr = ::Socket.pack_sockaddr_in(port, address.to_s) + sock = ::Socket.new(address.is_a?(Resolv::IPv6) ? ::Socket::AF_INET6 : ::Socket::AF_INET, ::Socket::SOCK_STREAM, 0) + sockaddr = ::Socket.pack_sockaddr_in(port, address.to_s) - sock.setsockopt(::Socket::IPPROTO_TCP, ::Socket::TCP_NODELAY, 1) + sock.setsockopt(::Socket::IPPROTO_TCP, ::Socket::TCP_NODELAY, 1) - sock.connect_nonblock(sockaddr) + sock.connect_nonblock(sockaddr) - # If that hasn't raised an exception, we somehow managed to connect - # immediately, close pending sockets and return immediately - socks.each(&:close) - return sock - rescue IO::WaitWritable - socks << sock - addr_by_socket[sock] = sockaddr - rescue => e - outer_e = e - end + # If that hasn't raised an exception, we somehow managed to connect + # immediately, close pending sockets and return immediately + socks.each(&:close) + return sock + rescue IO::WaitWritable + socks << sock + addr_by_socket[sock] = sockaddr + rescue => e + outer_e = e end until socks.empty? @@ -279,9 +277,7 @@ class Request end def private_address_exceptions - @private_address_exceptions = begin - (ENV['ALLOWED_PRIVATE_ADDRESSES'] || '').split(',').map { |addr| IPAddr.new(addr) } - end + @private_address_exceptions = (ENV['ALLOWED_PRIVATE_ADDRESSES'] || '').split(',').map { |addr| IPAddr.new(addr) } end end end diff --git a/app/models/account.rb b/app/models/account.rb index a96e204fa..2c0cd577e 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -459,13 +459,12 @@ class Account < ApplicationRecord return [] if text.blank? text.scan(MENTION_RE).map { |match| match.first.split('@', 2) }.uniq.filter_map do |(username, domain)| - domain = begin - if TagManager.instance.local_domain?(domain) - nil - else - TagManager.instance.normalize_domain(domain) - end - end + domain = if TagManager.instance.local_domain?(domain) + nil + else + TagManager.instance.normalize_domain(domain) + end + EntityCache.instance.mention(username, domain) end end diff --git a/app/models/account/field.rb b/app/models/account/field.rb index 4db4cac30..98c29726d 100644 --- a/app/models/account/field.rb +++ b/app/models/account/field.rb @@ -25,13 +25,11 @@ class Account::Field < ActiveModelSerializers::Model end def value_for_verification - @value_for_verification ||= begin - if account.local? - value - else - extract_url_from_html - end - end + @value_for_verification ||= if account.local? + value + else + extract_url_from_html + end end def verifiable? diff --git a/app/models/admin/account_action.rb b/app/models/admin/account_action.rb index bce0d6e17..1ce28f5c8 100644 --- a/app/models/admin/account_action.rb +++ b/app/models/admin/account_action.rb @@ -166,13 +166,11 @@ class Admin::AccountAction end def reports - @reports ||= begin - if type == 'none' - with_report? ? [report] : [] - else - Report.where(target_account: target_account).unresolved - end - end + @reports ||= if type == 'none' + with_report? ? [report] : [] + else + Report.where(target_account: target_account).unresolved + end end def warning_preset diff --git a/app/models/announcement.rb b/app/models/announcement.rb index 4b2cb4c6d..898bf3efa 100644 --- a/app/models/announcement.rb +++ b/app/models/announcement.rb @@ -54,13 +54,11 @@ class Announcement < ApplicationRecord end def statuses - @statuses ||= begin - if status_ids.nil? - [] - else - Status.where(id: status_ids, visibility: [:public, :unlisted]) - end - end + @statuses ||= if status_ids.nil? + [] + else + Status.where(id: status_ids, visibility: [:public, :unlisted]) + end end def tags diff --git a/app/models/concerns/account_merging.rb b/app/models/concerns/account_merging.rb index 8161761fb..41071633d 100644 --- a/app/models/concerns/account_merging.rb +++ b/app/models/concerns/account_merging.rb @@ -21,11 +21,9 @@ module AccountMerging owned_classes.each do |klass| klass.where(account_id: other_account.id).find_each do |record| - begin - record.update_attribute(:account_id, id) - rescue ActiveRecord::RecordNotUnique - next - end + record.update_attribute(:account_id, id) + rescue ActiveRecord::RecordNotUnique + next end end @@ -36,11 +34,9 @@ module AccountMerging target_classes.each do |klass| klass.where(target_account_id: other_account.id).find_each do |record| - begin - record.update_attribute(:target_account_id, id) - rescue ActiveRecord::RecordNotUnique - next - end + record.update_attribute(:target_account_id, id) + rescue ActiveRecord::RecordNotUnique + next end end diff --git a/app/models/concerns/pam_authenticable.rb b/app/models/concerns/pam_authenticable.rb index 6169d4dfa..f97f986a4 100644 --- a/app/models/concerns/pam_authenticable.rb +++ b/app/models/concerns/pam_authenticable.rb @@ -42,13 +42,11 @@ module PamAuthenticable def self.pam_get_user(attributes = {}) return nil unless attributes[:email] - resource = begin - if Devise.check_at_sign && !attributes[:email].index('@') - joins(:account).find_by(accounts: { username: attributes[:email] }) - else - find_by(email: attributes[:email]) - end - end + resource = if Devise.check_at_sign && !attributes[:email].index('@') + joins(:account).find_by(accounts: { username: attributes[:email] }) + else + find_by(email: attributes[:email]) + end if resource.nil? resource = new(email: attributes[:email], agreement: true) diff --git a/app/models/email_domain_block.rb b/app/models/email_domain_block.rb index 10a0e5102..3a56e4f2a 100644 --- a/app/models/email_domain_block.rb +++ b/app/models/email_domain_block.rb @@ -69,13 +69,11 @@ class EmailDomainBlock < ApplicationRecord def extract_uris(domain_or_domains) Array(domain_or_domains).map do |str| - domain = begin - if str.include?('@') - str.split('@', 2).last - else - str - end - end + domain = if str.include?('@') + str.split('@', 2).last + else + str + end Addressable::URI.new.tap { |u| u.host = domain.strip } if domain.present? rescue Addressable::URI::InvalidURIError, IDN::Idna::IdnaError diff --git a/app/models/form/admin_settings.rb b/app/models/form/admin_settings.rb index 070478e8e..95c53084a 100644 --- a/app/models/form/admin_settings.rb +++ b/app/models/form/admin_settings.rb @@ -76,13 +76,11 @@ class Form::AdminSettings define_method(key) do return instance_variable_get("@#{key}") if instance_variable_defined?("@#{key}") - stored_value = begin - if UPLOAD_KEYS.include?(key) - SiteUpload.where(var: key).first_or_initialize(var: key) - else - Setting.public_send(key) - end - end + stored_value = if UPLOAD_KEYS.include?(key) + SiteUpload.where(var: key).first_or_initialize(var: key) + else + Setting.public_send(key) + end instance_variable_set("@#{key}", stored_value) end diff --git a/app/models/form/custom_emoji_batch.rb b/app/models/form/custom_emoji_batch.rb index f4fa84c10..484415f90 100644 --- a/app/models/form/custom_emoji_batch.rb +++ b/app/models/form/custom_emoji_batch.rb @@ -36,13 +36,11 @@ class Form::CustomEmojiBatch def update! custom_emojis.each { |custom_emoji| authorize(custom_emoji, :update?) } - category = begin - if category_id.present? - CustomEmojiCategory.find(category_id) - elsif category_name.present? - CustomEmojiCategory.find_or_create_by!(name: category_name) - end - end + category = if category_id.present? + CustomEmojiCategory.find(category_id) + elsif category_name.present? + CustomEmojiCategory.find_or_create_by!(name: category_name) + end custom_emojis.each do |custom_emoji| custom_emoji.update(category_id: category&.id) diff --git a/app/models/notification.rb b/app/models/notification.rb index bbc63c1c0..01155c363 100644 --- a/app/models/notification.rb +++ b/app/models/notification.rb @@ -87,13 +87,11 @@ class Notification < ApplicationRecord class << self def browserable(types: [], exclude_types: [], from_account_id: nil) - requested_types = begin - if types.empty? - TYPES - else - types.map(&:to_sym) & TYPES - end - end + requested_types = if types.empty? + TYPES + else + types.map(&:to_sym) & TYPES + end requested_types -= exclude_types.map(&:to_sym) diff --git a/app/models/remote_follow.rb b/app/models/remote_follow.rb index 911c06713..10715ac97 100644 --- a/app/models/remote_follow.rb +++ b/app/models/remote_follow.rb @@ -36,13 +36,11 @@ class RemoteFollow username, domain = value.strip.gsub(/\A@/, '').split('@') - domain = begin - if TagManager.instance.local_domain?(domain) - nil - else - TagManager.instance.normalize_domain(domain) - end - end + domain = if TagManager.instance.local_domain?(domain) + nil + else + TagManager.instance.normalize_domain(domain) + end [username, domain].compact.join('@') rescue Addressable::URI::InvalidURIError diff --git a/app/models/status.rb b/app/models/status.rb index a924a985f..102dfa994 100644 --- a/app/models/status.rb +++ b/app/models/status.rb @@ -368,13 +368,12 @@ class Status < ApplicationRecord return [] if text.blank? text.scan(FetchLinkCardService::URL_PATTERN).map(&:second).uniq.filter_map do |url| - status = begin - if TagManager.instance.local_url?(url) - ActivityPub::TagManager.instance.uri_to_resource(url, Status) - else - EntityCache.instance.status(url) - end - end + status = if TagManager.instance.local_url?(url) + ActivityPub::TagManager.instance.uri_to_resource(url, Status) + else + EntityCache.instance.status(url) + end + status&.distributable? ? status : nil end end diff --git a/app/models/status_edit.rb b/app/models/status_edit.rb index e33470226..dd2d5fc1e 100644 --- a/app/models/status_edit.rb +++ b/app/models/status_edit.rb @@ -51,14 +51,12 @@ class StatusEdit < ApplicationRecord def ordered_media_attachments return @ordered_media_attachments if defined?(@ordered_media_attachments) - @ordered_media_attachments = begin - if ordered_media_attachment_ids.nil? - [] - else - map = status.media_attachments.index_by(&:id) - ordered_media_attachment_ids.map.with_index { |media_attachment_id, index| PreservedMediaAttachment.new(media_attachment: map[media_attachment_id], description: media_descriptions[index]) } - end - end + @ordered_media_attachments = if ordered_media_attachment_ids.nil? + [] + else + map = status.media_attachments.index_by(&:id) + ordered_media_attachment_ids.map.with_index { |media_attachment_id, index| PreservedMediaAttachment.new(media_attachment: map[media_attachment_id], description: media_descriptions[index]) } + end end def proper diff --git a/app/models/trends/links.rb b/app/models/trends/links.rb index 8808b3ab6..c94f7c023 100644 --- a/app/models/trends/links.rb +++ b/app/models/trends/links.rb @@ -113,13 +113,11 @@ class Trends::Links < Trends::Base max_score = preview_card.max_score max_score = 0 if max_time.nil? || max_time < (at_time - options[:max_score_cooldown]) - score = begin - if expected > observed || observed < options[:threshold] - 0 - else - ((observed - expected)**2) / expected - end - end + score = if expected > observed || observed < options[:threshold] + 0 + else + ((observed - expected)**2) / expected + end if score > max_score max_score = score @@ -129,13 +127,11 @@ class Trends::Links < Trends::Base preview_card.update_columns(max_score: max_score, max_score_at: max_time) end - decaying_score = begin - if max_score.zero? || !valid_locale?(preview_card.language) - 0 - else - max_score * (0.5**((at_time.to_f - max_time.to_f) / options[:max_score_halflife].to_f)) - end - end + decaying_score = if max_score.zero? || !valid_locale?(preview_card.language) + 0 + else + max_score * (0.5**((at_time.to_f - max_time.to_f) / options[:max_score_halflife].to_f)) + end [decaying_score, preview_card] end diff --git a/app/models/trends/statuses.rb b/app/models/trends/statuses.rb index c9ef7c8f2..84bff9c02 100644 --- a/app/models/trends/statuses.rb +++ b/app/models/trends/statuses.rb @@ -99,21 +99,17 @@ class Trends::Statuses < Trends::Base expected = 1.0 observed = (status.reblogs_count + status.favourites_count).to_f - score = begin - if expected > observed || observed < options[:threshold] - 0 - else - ((observed - expected)**2) / expected - end - end - - decaying_score = begin - if score.zero? || !eligible?(status) - 0 - else - score * (0.5**((at_time.to_f - status.created_at.to_f) / options[:score_halflife].to_f)) - end - end + score = if expected > observed || observed < options[:threshold] + 0 + else + ((observed - expected)**2) / expected + end + + decaying_score = if score.zero? || !eligible?(status) + 0 + else + score * (0.5**((at_time.to_f - status.created_at.to_f) / options[:score_halflife].to_f)) + end [decaying_score, status] end diff --git a/app/models/trends/tag_filter.rb b/app/models/trends/tag_filter.rb index 3b142efc4..46b747819 100644 --- a/app/models/trends/tag_filter.rb +++ b/app/models/trends/tag_filter.rb @@ -13,13 +13,11 @@ class Trends::TagFilter end def results - scope = begin - if params[:status] == 'pending_review' - Tag.unscoped - else - trending_scope - end - end + scope = if params[:status] == 'pending_review' + Tag.unscoped + else + trending_scope + end params.each do |key, value| next if key.to_s == 'page' diff --git a/app/models/trends/tags.rb b/app/models/trends/tags.rb index 19ade52ba..931532990 100644 --- a/app/models/trends/tags.rb +++ b/app/models/trends/tags.rb @@ -63,13 +63,11 @@ class Trends::Tags < Trends::Base max_score = tag.max_score max_score = 0 if max_time.nil? || max_time < (at_time - options[:max_score_cooldown]) - score = begin - if expected > observed || observed < options[:threshold] - 0 - else - ((observed - expected)**2) / expected - end - end + score = if expected > observed || observed < options[:threshold] + 0 + else + ((observed - expected)**2) / expected + end if score > max_score max_score = score diff --git a/app/models/web/push_subscription.rb b/app/models/web/push_subscription.rb index 6e46573ae..dfaadf5cc 100644 --- a/app/models/web/push_subscription.rb +++ b/app/models/web/push_subscription.rb @@ -53,25 +53,21 @@ class Web::PushSubscription < ApplicationRecord def associated_user return @associated_user if defined?(@associated_user) - @associated_user = begin - if user_id.nil? - session_activation.user - else - user - end - end + @associated_user = if user_id.nil? + session_activation.user + else + user + end end def associated_access_token return @associated_access_token if defined?(@associated_access_token) - @associated_access_token = begin - if access_token_id.nil? - find_or_create_access_token.token - else - access_token.token - end - end + @associated_access_token = if access_token_id.nil? + find_or_create_access_token.token + else + access_token.token + end end class << self diff --git a/app/presenters/tag_relationships_presenter.rb b/app/presenters/tag_relationships_presenter.rb index c3bdbaf07..52e24314b 100644 --- a/app/presenters/tag_relationships_presenter.rb +++ b/app/presenters/tag_relationships_presenter.rb @@ -4,12 +4,10 @@ class TagRelationshipsPresenter attr_reader :following_map def initialize(tags, current_account_id = nil, **options) - @following_map = begin - if current_account_id.nil? - {} - else - TagFollow.select(:tag_id).where(tag_id: tags.map(&:id), account_id: current_account_id).each_with_object({}) { |f, h| h[f.tag_id] = true }.merge(options[:following_map] || {}) - end - end + @following_map = if current_account_id.nil? + {} + else + TagFollow.select(:tag_id).where(tag_id: tags.map(&:id), account_id: current_account_id).each_with_object({}) { |f, h| h[f.tag_id] = true }.merge(options[:following_map] || {}) + end end end diff --git a/app/services/account_search_service.rb b/app/services/account_search_service.rb index 85538870b..dfc3a45f8 100644 --- a/app/services/account_search_service.rb +++ b/app/services/account_search_service.rb @@ -32,15 +32,13 @@ class AccountSearchService < BaseService return @exact_match if defined?(@exact_match) - match = begin - if options[:resolve] - ResolveAccountService.new.call(query) - elsif domain_is_local? - Account.find_local(query_username) - else - Account.find_remote(query_username, query_domain) - end - end + match = if options[:resolve] + ResolveAccountService.new.call(query) + elsif domain_is_local? + Account.find_local(query_username) + else + Account.find_remote(query_username, query_domain) + end match = nil if !match.nil? && !account.nil? && options[:following] && !account.following?(match) diff --git a/app/services/activitypub/fetch_featured_tags_collection_service.rb b/app/services/activitypub/fetch_featured_tags_collection_service.rb index ab047a0f8..ff1a88aa1 100644 --- a/app/services/activitypub/fetch_featured_tags_collection_service.rb +++ b/app/services/activitypub/fetch_featured_tags_collection_service.rb @@ -22,14 +22,12 @@ class ActivityPub::FetchFeaturedTagsCollectionService < BaseService collection = fetch_collection(collection['first']) if collection['first'].present? while collection.is_a?(Hash) - items = begin - case collection['type'] - when 'Collection', 'CollectionPage' - collection['items'] - when 'OrderedCollection', 'OrderedCollectionPage' - collection['orderedItems'] - end - end + items = case collection['type'] + when 'Collection', 'CollectionPage' + collection['items'] + when 'OrderedCollection', 'OrderedCollectionPage' + collection['orderedItems'] + end break if items.blank? diff --git a/app/services/activitypub/fetch_remote_status_service.rb b/app/services/activitypub/fetch_remote_status_service.rb index 936737bf6..aea80f078 100644 --- a/app/services/activitypub/fetch_remote_status_service.rb +++ b/app/services/activitypub/fetch_remote_status_service.rb @@ -9,13 +9,11 @@ class ActivityPub::FetchRemoteStatusService < BaseService # Should be called when uri has already been checked for locality def call(uri, id: true, prefetched_body: nil, on_behalf_of: nil, expected_actor_uri: nil, request_id: nil) @request_id = request_id || "#{Time.now.utc.to_i}-status-#{uri}" - @json = begin - if prefetched_body.nil? - fetch_resource(uri, id, on_behalf_of) - else - body_to_json(prefetched_body, compare_id: id ? uri : nil) - end - end + @json = if prefetched_body.nil? + fetch_resource(uri, id, on_behalf_of) + else + body_to_json(prefetched_body, compare_id: id ? uri : nil) + end return unless supported_context? diff --git a/app/services/fetch_link_card_service.rb b/app/services/fetch_link_card_service.rb index 4d55aa5e2..d5fa9af54 100644 --- a/app/services/fetch_link_card_service.rb +++ b/app/services/fetch_link_card_service.rb @@ -69,16 +69,14 @@ class FetchLinkCardService < BaseService end def parse_urls - urls = begin - if @status.local? - @status.text.scan(URL_PATTERN).map { |array| Addressable::URI.parse(array[1]).normalize } - else - document = Nokogiri::HTML(@status.text) - links = document.css('a') - - links.filter_map { |a| Addressable::URI.parse(a['href']) unless skip_link?(a) }.filter_map(&:normalize) - end - end + urls = if @status.local? + @status.text.scan(URL_PATTERN).map { |array| Addressable::URI.parse(array[1]).normalize } + else + document = Nokogiri::HTML(@status.text) + links = document.css('a') + + links.filter_map { |a| Addressable::URI.parse(a['href']) unless skip_link?(a) }.filter_map(&:normalize) + end urls.reject { |uri| bad_url?(uri) }.first end diff --git a/app/services/process_mentions_service.rb b/app/services/process_mentions_service.rb index 93a96667e..b3b279147 100644 --- a/app/services/process_mentions_service.rb +++ b/app/services/process_mentions_service.rb @@ -28,13 +28,11 @@ class ProcessMentionsService < BaseService @status.text = @status.text.gsub(Account::MENTION_RE) do |match| username, domain = Regexp.last_match(1).split('@') - domain = begin - if TagManager.instance.local_domain?(domain) - nil - else - TagManager.instance.normalize_domain(domain) - end - end + domain = if TagManager.instance.local_domain?(domain) + nil + else + TagManager.instance.normalize_domain(domain) + end mentioned_account = Account.find_remote(username, domain) diff --git a/app/services/reblog_service.rb b/app/services/reblog_service.rb index 7d2981709..6ec094474 100644 --- a/app/services/reblog_service.rb +++ b/app/services/reblog_service.rb @@ -20,13 +20,11 @@ class ReblogService < BaseService return reblog unless reblog.nil? - visibility = begin - if reblogged_status.hidden? - reblogged_status.visibility - else - options[:visibility] || account.user&.setting_default_privacy - end - end + visibility = if reblogged_status.hidden? + reblogged_status.visibility + else + options[:visibility] || account.user&.setting_default_privacy + end reblog = account.statuses.create!(reblog: reblogged_status, text: '', visibility: visibility, rate_limit: options[:with_rate_limit]) diff --git a/app/services/resolve_account_service.rb b/app/services/resolve_account_service.rb index c76df5a0e..abe1534a5 100644 --- a/app/services/resolve_account_service.rb +++ b/app/services/resolve_account_service.rb @@ -71,13 +71,11 @@ class ResolveAccountService < BaseService @username, @domain = uri.strip.gsub(/\A@/, '').split('@') end - @domain = begin - if TagManager.instance.local_domain?(@domain) - nil - else - TagManager.instance.normalize_domain(@domain) - end - end + @domain = if TagManager.instance.local_domain?(@domain) + nil + else + TagManager.instance.normalize_domain(@domain) + end @uri = [@username, @domain].compact.join('@') end diff --git a/app/validators/domain_validator.rb b/app/validators/domain_validator.rb index 6e4a854ff..3a951f9a7 100644 --- a/app/validators/domain_validator.rb +++ b/app/validators/domain_validator.rb @@ -4,13 +4,11 @@ class DomainValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) return if value.blank? - domain = begin - if options[:acct] - value.split('@').last - else - value - end - end + domain = if options[:acct] + value.split('@').last + else + value + end record.errors.add(attribute, I18n.t('domain_validator.invalid_domain')) unless compliant?(domain) end diff --git a/app/validators/existing_username_validator.rb b/app/validators/existing_username_validator.rb index 1c5596821..45de4f4a4 100644 --- a/app/validators/existing_username_validator.rb +++ b/app/validators/existing_username_validator.rb @@ -4,16 +4,14 @@ class ExistingUsernameValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) return if value.blank? - usernames_and_domains = begin - value.split(',').map do |str| - username, domain = str.strip.gsub(/\A@/, '').split('@', 2) - domain = nil if TagManager.instance.local_domain?(domain) + usernames_and_domains = value.split(',').map do |str| + username, domain = str.strip.gsub(/\A@/, '').split('@', 2) + domain = nil if TagManager.instance.local_domain?(domain) - next if username.blank? + next if username.blank? - [str, username, domain] - end.compact - end + [str, username, domain] + end.compact usernames_with_no_accounts = usernames_and_domains.filter_map do |(str, username, domain)| str unless Account.find_remote(username, domain) diff --git a/app/validators/import_validator.rb b/app/validators/import_validator.rb index cbad56df6..782baf5d6 100644 --- a/app/validators/import_validator.rb +++ b/app/validators/import_validator.rb @@ -35,13 +35,11 @@ class ImportValidator < ActiveModel::Validator def validate_following_import(import, row_count) base_limit = FollowLimitValidator.limit_for_account(import.account) - limit = begin - if import.overwrite? - base_limit - else - base_limit - import.account.following_count - end - end + limit = if import.overwrite? + base_limit + else + base_limit - import.account.following_count + end import.errors.add(:data, I18n.t('users.follow_limit_reached', limit: base_limit)) if row_count > limit end diff --git a/app/workers/backup_worker.rb b/app/workers/backup_worker.rb index 7b0b52844..df933142a 100644 --- a/app/workers/backup_worker.rb +++ b/app/workers/backup_worker.rb @@ -9,12 +9,10 @@ class BackupWorker backup_id = msg['args'].first ActiveRecord::Base.connection_pool.with_connection do - begin - backup = Backup.find(backup_id) - backup.destroy - rescue ActiveRecord::RecordNotFound - true - end + backup = Backup.find(backup_id) + backup.destroy + rescue ActiveRecord::RecordNotFound + true end end diff --git a/app/workers/post_process_media_worker.rb b/app/workers/post_process_media_worker.rb index 24201101c..996d5def9 100644 --- a/app/workers/post_process_media_worker.rb +++ b/app/workers/post_process_media_worker.rb @@ -9,13 +9,11 @@ class PostProcessMediaWorker media_attachment_id = msg['args'].first ActiveRecord::Base.connection_pool.with_connection do - begin - media_attachment = MediaAttachment.find(media_attachment_id) - media_attachment.processing = :failed - media_attachment.save - rescue ActiveRecord::RecordNotFound - true - end + media_attachment = MediaAttachment.find(media_attachment_id) + media_attachment.processing = :failed + media_attachment.save + rescue ActiveRecord::RecordNotFound + true end Sidekiq.logger.error("Processing media attachment #{media_attachment_id} failed with #{msg['error_message']}") diff --git a/app/workers/scheduler/follow_recommendations_scheduler.rb b/app/workers/scheduler/follow_recommendations_scheduler.rb index 57f78170e..04008a9d9 100644 --- a/app/workers/scheduler/follow_recommendations_scheduler.rb +++ b/app/workers/scheduler/follow_recommendations_scheduler.rb @@ -19,13 +19,11 @@ class Scheduler::FollowRecommendationsScheduler fallback_recommendations = FollowRecommendation.order(rank: :desc).limit(SET_SIZE) Trends.available_locales.each do |locale| - recommendations = begin - if AccountSummary.safe.filtered.localized(locale).exists? # We can skip the work if no accounts with that language exist - FollowRecommendation.localized(locale).order(rank: :desc).limit(SET_SIZE).map { |recommendation| [recommendation.account_id, recommendation.rank] } - else - [] - end - end + recommendations = if AccountSummary.safe.filtered.localized(locale).exists? # We can skip the work if no accounts with that language exist + FollowRecommendation.localized(locale).order(rank: :desc).limit(SET_SIZE).map { |recommendation| [recommendation.account_id, recommendation.rank] } + else + [] + end # Use language-agnostic results if there are not enough language-specific ones missing = SET_SIZE - recommendations.size diff --git a/db/migrate/20180528141303_fix_accounts_unique_index.rb b/db/migrate/20180528141303_fix_accounts_unique_index.rb index 3e33e2cac..0b39f7107 100644 --- a/db/migrate/20180528141303_fix_accounts_unique_index.rb +++ b/db/migrate/20180528141303_fix_accounts_unique_index.rb @@ -106,21 +106,17 @@ class FixAccountsUniqueIndex < ActiveRecord::Migration[5.2] # to check for (and skip past) uniqueness errors [Favourite, Follow, FollowRequest, Block, Mute].each do |klass| klass.where(account_id: duplicate_account.id).find_each do |record| - begin - record.update_attribute(:account_id, main_account.id) - rescue ActiveRecord::RecordNotUnique - next - end + record.update_attribute(:account_id, main_account.id) + rescue ActiveRecord::RecordNotUnique + next end end [Follow, FollowRequest, Block, Mute].each do |klass| klass.where(target_account_id: duplicate_account.id).find_each do |record| - begin - record.update_attribute(:target_account_id, main_account.id) - rescue ActiveRecord::RecordNotUnique - next - end + record.update_attribute(:target_account_id, main_account.id) + rescue ActiveRecord::RecordNotUnique + next end end end diff --git a/db/migrate/20180812173710_copy_status_stats.rb b/db/migrate/20180812173710_copy_status_stats.rb index 9b2971beb..45eb9501c 100644 --- a/db/migrate/20180812173710_copy_status_stats.rb +++ b/db/migrate/20180812173710_copy_status_stats.rb @@ -43,12 +43,10 @@ class CopyStatusStats < ActiveRecord::Migration[5.2] # We cannot use bulk INSERT or overarching transactions here because of possible # uniqueness violations that we need to skip over Status.unscoped.select('id, reblogs_count, favourites_count, created_at, updated_at').find_each do |status| - begin - params = [[nil, status.id], [nil, status.reblogs_count], [nil, status.favourites_count], [nil, status.created_at], [nil, status.updated_at]] - exec_insert('INSERT INTO status_stats (status_id, reblogs_count, favourites_count, created_at, updated_at) VALUES ($1, $2, $3, $4, $5)', nil, params) - rescue ActiveRecord::RecordNotUnique - next - end + params = [[nil, status.id], [nil, status.reblogs_count], [nil, status.favourites_count], [nil, status.created_at], [nil, status.updated_at]] + exec_insert('INSERT INTO status_stats (status_id, reblogs_count, favourites_count, created_at, updated_at) VALUES ($1, $2, $3, $4, $5)', nil, params) + rescue ActiveRecord::RecordNotUnique + next end end end diff --git a/db/migrate/20181116173541_copy_account_stats.rb b/db/migrate/20181116173541_copy_account_stats.rb index 20dc85195..f908575cb 100644 --- a/db/migrate/20181116173541_copy_account_stats.rb +++ b/db/migrate/20181116173541_copy_account_stats.rb @@ -43,12 +43,10 @@ class CopyAccountStats < ActiveRecord::Migration[5.2] # We cannot use bulk INSERT or overarching transactions here because of possible # uniqueness violations that we need to skip over Account.unscoped.select('id, statuses_count, following_count, followers_count, created_at, updated_at').find_each do |account| - begin - params = [[nil, account.id], [nil, account[:statuses_count]], [nil, account[:following_count]], [nil, account[:followers_count]], [nil, account.created_at], [nil, account.updated_at]] - exec_insert('INSERT INTO account_stats (account_id, statuses_count, following_count, followers_count, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6)', nil, params) - rescue ActiveRecord::RecordNotUnique - next - end + params = [[nil, account.id], [nil, account[:statuses_count]], [nil, account[:following_count]], [nil, account[:followers_count]], [nil, account.created_at], [nil, account.updated_at]] + exec_insert('INSERT INTO account_stats (account_id, statuses_count, following_count, followers_count, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6)', nil, params) + rescue ActiveRecord::RecordNotUnique + next end end end diff --git a/lib/mastodon/accounts_cli.rb b/lib/mastodon/accounts_cli.rb index 34afbc699..db379eb85 100644 --- a/lib/mastodon/accounts_cli.rb +++ b/lib/mastodon/accounts_cli.rb @@ -490,14 +490,12 @@ module Mastodon scope = Account.where(id: ::Follow.where(account: account).select(:target_account_id)) scope.find_each do |target_account| - begin - UnfollowService.new.call(account, target_account) - rescue => e - progress.log pastel.red("Error processing #{target_account.id}: #{e}") - ensure - progress.increment - processed += 1 - end + UnfollowService.new.call(account, target_account) + rescue => e + progress.log pastel.red("Error processing #{target_account.id}: #{e}") + ensure + progress.increment + processed += 1 end BootstrapTimelineWorker.perform_async(account.id) @@ -507,14 +505,12 @@ module Mastodon scope = Account.where(id: ::Follow.where(target_account: account).select(:account_id)) scope.find_each do |target_account| - begin - UnfollowService.new.call(target_account, account) - rescue => e - progress.log pastel.red("Error processing #{target_account.id}: #{e}") - ensure - progress.increment - processed += 1 - end + UnfollowService.new.call(target_account, account) + rescue => e + progress.log pastel.red("Error processing #{target_account.id}: #{e}") + ensure + progress.increment + processed += 1 end end diff --git a/lib/mastodon/cli_helper.rb b/lib/mastodon/cli_helper.rb index a78a28e27..8704edd75 100644 --- a/lib/mastodon/cli_helper.rb +++ b/lib/mastodon/cli_helper.rb @@ -42,30 +42,28 @@ module Mastodon items.each do |item| futures << Concurrent::Future.execute(executor: pool) do - begin - if !progress.total.nil? && progress.progress + 1 > progress.total - # The number of items has changed between start and now, - # since there is no good way to predict the final count from - # here, just change the progress bar to an indeterminate one - - progress.total = nil - end - - progress.log("Processing #{item.id}") if options[:verbose] - - result = ActiveRecord::Base.connection_pool.with_connection do - yield(item) - ensure - RedisConfiguration.pool.checkin if Thread.current[:redis] - Thread.current[:redis] = nil - end - - aggregate.increment(result) if result.is_a?(Integer) - rescue => e - progress.log pastel.red("Error processing #{item.id}: #{e}") + if !progress.total.nil? && progress.progress + 1 > progress.total + # The number of items has changed between start and now, + # since there is no good way to predict the final count from + # here, just change the progress bar to an indeterminate one + + progress.total = nil + end + + progress.log("Processing #{item.id}") if options[:verbose] + + result = ActiveRecord::Base.connection_pool.with_connection do + yield(item) ensure - progress.increment + RedisConfiguration.pool.checkin if Thread.current[:redis] + Thread.current[:redis] = nil end + + aggregate.increment(result) if result.is_a?(Integer) + rescue => e + progress.log pastel.red("Error processing #{item.id}: #{e}") + ensure + progress.increment end end diff --git a/lib/mastodon/ip_blocks_cli.rb b/lib/mastodon/ip_blocks_cli.rb index 5c38c1aca..08939c092 100644 --- a/lib/mastodon/ip_blocks_cli.rb +++ b/lib/mastodon/ip_blocks_cli.rb @@ -79,13 +79,11 @@ module Mastodon skipped = 0 addresses.each do |address| - ip_blocks = begin - if options[:force] - IpBlock.where('ip >>= ?', address) - else - IpBlock.where('ip <<= ?', address) - end - end + ip_blocks = if options[:force] + IpBlock.where('ip >>= ?', address) + else + IpBlock.where('ip <<= ?', address) + end if ip_blocks.empty? say("#{address} is not yet blocked", :yellow) diff --git a/lib/mastodon/maintenance_cli.rb b/lib/mastodon/maintenance_cli.rb index a86a4f2f6..bb3802f56 100644 --- a/lib/mastodon/maintenance_cli.rb +++ b/lib/mastodon/maintenance_cli.rb @@ -98,11 +98,9 @@ module Mastodon owned_classes.each do |klass| klass.where(account_id: other_account.id).find_each do |record| - begin - record.update_attribute(:account_id, id) - rescue ActiveRecord::RecordNotUnique - next - end + record.update_attribute(:account_id, id) + rescue ActiveRecord::RecordNotUnique + next end end @@ -111,11 +109,9 @@ module Mastodon target_classes.each do |klass| klass.where(target_account_id: other_account.id).find_each do |record| - begin - record.update_attribute(:target_account_id, id) - rescue ActiveRecord::RecordNotUnique - next - end + record.update_attribute(:target_account_id, id) + rescue ActiveRecord::RecordNotUnique + next end end @@ -601,11 +597,9 @@ module Mastodon owned_classes = [ConversationMute, AccountConversation] owned_classes.each do |klass| klass.where(conversation_id: duplicate_conv.id).find_each do |record| - begin - record.update_attribute(:account_id, main_conv.id) - rescue ActiveRecord::RecordNotUnique - next - end + record.update_attribute(:account_id, main_conv.id) + rescue ActiveRecord::RecordNotUnique + next end end end @@ -629,47 +623,37 @@ module Mastodon owned_classes << Bookmark if ActiveRecord::Base.connection.table_exists?(:bookmarks) owned_classes.each do |klass| klass.where(status_id: duplicate_status.id).find_each do |record| - begin - record.update_attribute(:status_id, main_status.id) - rescue ActiveRecord::RecordNotUnique - next - end - end - end - - StatusPin.where(account_id: main_status.account_id, status_id: duplicate_status.id).find_each do |record| - begin record.update_attribute(:status_id, main_status.id) rescue ActiveRecord::RecordNotUnique next end end + StatusPin.where(account_id: main_status.account_id, status_id: duplicate_status.id).find_each do |record| + record.update_attribute(:status_id, main_status.id) + rescue ActiveRecord::RecordNotUnique + next + end + Status.where(in_reply_to_id: duplicate_status.id).find_each do |record| - begin - record.update_attribute(:in_reply_to_id, main_status.id) - rescue ActiveRecord::RecordNotUnique - next - end + record.update_attribute(:in_reply_to_id, main_status.id) + rescue ActiveRecord::RecordNotUnique + next end Status.where(reblog_of_id: duplicate_status.id).find_each do |record| - begin - record.update_attribute(:reblog_of_id, main_status.id) - rescue ActiveRecord::RecordNotUnique - next - end + record.update_attribute(:reblog_of_id, main_status.id) + rescue ActiveRecord::RecordNotUnique + next end end def merge_tags!(main_tag, duplicate_tag) [FeaturedTag].each do |klass| klass.where(tag_id: duplicate_tag.id).find_each do |record| - begin - record.update_attribute(:tag_id, main_tag.id) - rescue ActiveRecord::RecordNotUnique - next - end + record.update_attribute(:tag_id, main_tag.id) + rescue ActiveRecord::RecordNotUnique + next end end end diff --git a/lib/mastodon/media_cli.rb b/lib/mastodon/media_cli.rb index a901a6ab9..fc70c8785 100644 --- a/lib/mastodon/media_cli.rb +++ b/lib/mastodon/media_cli.rb @@ -116,13 +116,11 @@ module Mastodon loop do objects = begin - begin - bucket.objects(start_after: last_key, prefix: prefix).limit(1000).map { |x| x } - rescue => e - progress.log(pastel.red("Error fetching list of files: #{e}")) - progress.log("If you want to continue from this point, add --start-after=#{last_key} to your command") if last_key - break - end + bucket.objects(start_after: last_key, prefix: prefix).limit(1000).map { |x| x } + rescue => e + progress.log(pastel.red("Error fetching list of files: #{e}")) + progress.log("If you want to continue from this point, add --start-after=#{last_key} to your command") if last_key + break end break if objects.empty? diff --git a/lib/mastodon/search_cli.rb b/lib/mastodon/search_cli.rb index b206854ab..31e9a3d5a 100644 --- a/lib/mastodon/search_cli.rb +++ b/lib/mastodon/search_cli.rb @@ -43,13 +43,11 @@ module Mastodon exit(1) end - indices = begin - if options[:only] - options[:only].map { |str| "#{str.camelize}Index".constantize } - else - INDICES - end - end + indices = if options[:only] + options[:only].map { |str| "#{str.camelize}Index".constantize } + else + INDICES + end pool = Concurrent::FixedThreadPool.new(options[:concurrency], max_queue: options[:concurrency] * 10) importers = indices.index_with { |index| "Importer::#{index.name}Importer".constantize.new(batch_size: options[:batch_size], executor: pool) } diff --git a/lib/mastodon/upgrade_cli.rb b/lib/mastodon/upgrade_cli.rb index 570b7e6fa..2b60f9eee 100644 --- a/lib/mastodon/upgrade_cli.rb +++ b/lib/mastodon/upgrade_cli.rb @@ -50,16 +50,14 @@ module Mastodon styles << :original unless styles.include?(:original) styles.each do |style| - success = begin - case Paperclip::Attachment.default_options[:storage] - when :s3 - upgrade_storage_s3(progress, attachment, style) - when :fog - upgrade_storage_fog(progress, attachment, style) - when :filesystem - upgrade_storage_filesystem(progress, attachment, style) - end - end + success = case Paperclip::Attachment.default_options[:storage] + when :s3 + upgrade_storage_s3(progress, attachment, style) + when :fog + upgrade_storage_fog(progress, attachment, style) + when :filesystem + upgrade_storage_filesystem(progress, attachment, style) + end upgraded = true if style == :original && success diff --git a/lib/paperclip/color_extractor.rb b/lib/paperclip/color_extractor.rb index d8a042c90..733dcba80 100644 --- a/lib/paperclip/color_extractor.rb +++ b/lib/paperclip/color_extractor.rb @@ -161,13 +161,11 @@ module Paperclip def lighten_or_darken(color, by) hue, saturation, light = rgb_to_hsl(color.r, color.g, color.b) - light = begin - if light < 50 - [100, light + by].min - else - [0, light - by].max - end - end + light = if light < 50 + [100, light + by].min + else + [0, light - by].max + end ColorDiff::Color::RGB.new(*hsl_to_rgb(hue, saturation, light)) end diff --git a/lib/sanitize_ext/sanitize_config.rb b/lib/sanitize_ext/sanitize_config.rb index baf652662..d5e62897f 100644 --- a/lib/sanitize_ext/sanitize_config.rb +++ b/lib/sanitize_ext/sanitize_config.rb @@ -41,13 +41,11 @@ class Sanitize current_node = env[:node] - scheme = begin - if current_node['href'] =~ Sanitize::REGEX_PROTOCOL - Regexp.last_match(1).downcase - else - :relative - end - end + scheme = if current_node['href'] =~ Sanitize::REGEX_PROTOCOL + Regexp.last_match(1).downcase + else + :relative + end current_node.replace(Nokogiri::XML::Text.new(current_node.text, current_node.document)) unless LINK_PROTOCOLS.include?(scheme) end diff --git a/lib/tasks/db.rake b/lib/tasks/db.rake index ca939fd1f..e8a64b8fb 100644 --- a/lib/tasks/db.rake +++ b/lib/tasks/db.rake @@ -4,16 +4,14 @@ namespace :db do namespace :migrate do desc 'Setup the db or migrate depending on state of db' task setup: :environment do - begin - if ActiveRecord::Migrator.current_version.zero? - Rake::Task['db:migrate'].invoke - Rake::Task['db:seed'].invoke - end - rescue ActiveRecord::NoDatabaseError - Rake::Task['db:setup'].invoke - else + if ActiveRecord::Migrator.current_version.zero? Rake::Task['db:migrate'].invoke + Rake::Task['db:seed'].invoke end + rescue ActiveRecord::NoDatabaseError + Rake::Task['db:setup'].invoke + else + Rake::Task['db:migrate'].invoke end end -- cgit