From 927333f4f89403c5a6a2b421065112e517d88193 Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Thu, 29 Sep 2016 21:28:21 +0200 Subject: [PATCH] Improve code style --- .rubocop.yml | 14 ++++++++ app/channels/application_cable/channel.rb | 1 - app/channels/application_cable/connection.rb | 1 - app/channels/timeline_channel.rb | 1 - app/controllers/accounts_controller.rb | 2 +- app/controllers/api/salmon_controller.rb | 2 +- .../api/subscriptions_controller.rb | 4 +-- app/controllers/api/v1/accounts_controller.rb | 6 ++-- app/controllers/api/v1/follows_controller.rb | 6 ++-- app/controllers/api/v1/statuses_controller.rb | 12 +++---- app/controllers/application_controller.rb | 2 +- .../auth/registrations_controller.rb | 4 +-- app/controllers/home_controller.rb | 2 +- app/controllers/settings_controller.rb | 2 +- app/controllers/stream_entries_controller.rb | 2 +- app/controllers/xrd_controller.rb | 6 ++-- app/helpers/atom_builder_helper.rb | 2 +- app/helpers/stream_entries_helper.rb | 6 ++-- app/lib/formatter.rb | 2 +- app/models/account.rb | 32 ++++++++----------- app/models/concerns/streamable.rb | 2 +- app/models/favourite.rb | 4 +-- app/models/feed.rb | 4 +-- app/models/follow.rb | 6 ++-- app/models/media_attachment.rb | 8 ++--- app/models/status.rb | 28 ++++++++-------- app/models/stream_entry.rb | 20 ++++++------ app/models/user.rb | 4 +-- app/services/fetch_atom_service.rb | 4 +-- app/services/fetch_remote_account_service.rb | 4 +-- app/services/fetch_remote_status_service.rb | 8 ++--- app/services/follow_remote_account_service.rb | 9 +++--- app/services/follow_service.rb | 4 +-- app/services/post_status_service.rb | 4 +-- app/services/process_feed_service.rb | 12 +++---- app/services/process_interaction_service.rb | 8 ++--- app/services/process_mentions_service.rb | 2 +- app/services/remove_status_service.rb | 2 +- app/workers/distribution_worker.rb | 2 +- app/workers/notification_worker.rb | 2 +- app/workers/thread_resolve_worker.rb | 2 +- 41 files changed, 126 insertions(+), 122 deletions(-) create mode 100644 .rubocop.yml diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 000000000..3a638a009 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,14 @@ +Rails: + Enabled: true + +Metrics/LineLength: + Enabled: false + +Style/PerlBackrefs: + AutoCorrect: false + +Style/ClassAndModuleChildren: + Enabled: false + +Documentation: + Enabled: false diff --git a/app/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb index d56fa30f4..d67269728 100644 --- a/app/channels/application_cable/channel.rb +++ b/app/channels/application_cable/channel.rb @@ -1,4 +1,3 @@ -# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. module ApplicationCable class Channel < ActionCable::Channel::Base end diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb index 772b76a6e..0c4cac875 100644 --- a/app/channels/application_cable/connection.rb +++ b/app/channels/application_cable/connection.rb @@ -1,4 +1,3 @@ -# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user diff --git a/app/channels/timeline_channel.rb b/app/channels/timeline_channel.rb index 4b34f8ed5..9e5a81188 100644 --- a/app/channels/timeline_channel.rb +++ b/app/channels/timeline_channel.rb @@ -1,4 +1,3 @@ -# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. class TimelineChannel < ApplicationCable::Channel def subscribed stream_from "timeline:#{current_user.account_id}" diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb index bfdc5b6d9..55b1f3c45 100644 --- a/app/controllers/accounts_controller.rb +++ b/app/controllers/accounts_controller.rb @@ -7,7 +7,7 @@ class AccountsController < ApplicationController def show respond_to do |format| format.html do - @statuses = @account.statuses.order('id desc').with_includes.with_counters.paginate(page: params[:page], per_page: 10) + @statuses = @account.statuses.order('id desc').with_includes.with_counters.paginate(page: params[:page], per_page: 10) if user_signed_in? status_ids = @statuses.collect { |s| [s.id, s.reblog_of_id] }.flatten.uniq diff --git a/app/controllers/api/salmon_controller.rb b/app/controllers/api/salmon_controller.rb index 329b258a4..8bd653d7d 100644 --- a/app/controllers/api/salmon_controller.rb +++ b/app/controllers/api/salmon_controller.rb @@ -3,7 +3,7 @@ class Api::SalmonController < ApiController respond_to :txt def update - ProcessInteractionService.new.(request.body.read, @account) + ProcessInteractionService.new.call(request.body.read, @account) head 201 end diff --git a/app/controllers/api/subscriptions_controller.rb b/app/controllers/api/subscriptions_controller.rb index c8fa60260..c5190b136 100644 --- a/app/controllers/api/subscriptions_controller.rb +++ b/app/controllers/api/subscriptions_controller.rb @@ -4,7 +4,7 @@ class Api::SubscriptionsController < ApiController def show if @account.subscription(api_subscription_url(@account.id)).valid?(params['hub.topic']) - @account.update(subscription_expires_at: Time.now + ((params['hub.lease_seconds'] || 86400).to_i).seconds) + @account.update(subscription_expires_at: Time.now.utc + (params['hub.lease_seconds'] || 86_400).to_i.seconds) render plain: HTMLEntities.new.encode(params['hub.challenge']), status: 200 else head 404 @@ -15,7 +15,7 @@ class Api::SubscriptionsController < ApiController body = request.body.read if @account.subscription(api_subscription_url(@account.id)).verify(body, request.headers['HTTP_X_HUB_SIGNATURE']) - ProcessFeedService.new.(body, @account) + ProcessFeedService.new.call(body, @account) head 201 else head 202 diff --git a/app/controllers/api/v1/accounts_controller.rb b/app/controllers/api/v1/accounts_controller.rb index 23f48782f..50e6df80e 100644 --- a/app/controllers/api/v1/accounts_controller.rb +++ b/app/controllers/api/v1/accounts_controller.rb @@ -19,19 +19,19 @@ class Api::V1::AccountsController < ApiController end def follow - @follow = FollowService.new.(current_user.account, @account.acct) + @follow = FollowService.new.call(current_user.account, @account.acct) set_relationship render action: :relationship end def unfollow - @unfollow = UnfollowService.new.(current_user.account, @account) + @unfollow = UnfollowService.new.call(current_user.account, @account) set_relationship render action: :relationship end def relationships - ids = params[:id].is_a?(Enumerable) ? params[:id].map { |id| id.to_i } : [params[:id].to_i] + ids = params[:id].is_a?(Enumerable) ? params[:id].map(&:to_i) : [params[:id].to_i] @accounts = Account.find(ids) @following = Account.following_map(ids, current_user.account_id) @followed_by = Account.followed_by_map(ids, current_user.account_id) diff --git a/app/controllers/api/v1/follows_controller.rb b/app/controllers/api/v1/follows_controller.rb index de006f671..f688f2e72 100644 --- a/app/controllers/api/v1/follows_controller.rb +++ b/app/controllers/api/v1/follows_controller.rb @@ -3,11 +3,9 @@ class Api::V1::FollowsController < ApiController respond_to :json def create - if params[:uri].blank? - raise ActiveRecord::RecordNotFound - end + raise ActiveRecord::RecordNotFound if params[:uri].blank? - @account = FollowService.new.(current_user.account, params[:uri]).try(:target_account) + @account = FollowService.new.call(current_user.account, params[:uri]).try(:target_account) render action: :show end end diff --git a/app/controllers/api/v1/statuses_controller.rb b/app/controllers/api/v1/statuses_controller.rb index 4196852f2..14b86b2a2 100644 --- a/app/controllers/api/v1/statuses_controller.rb +++ b/app/controllers/api/v1/statuses_controller.rb @@ -13,34 +13,34 @@ class Api::V1::StatusesController < ApiController end def create - @status = PostStatusService.new.(current_user.account, params[:status], params[:in_reply_to_id].blank? ? nil : Status.find(params[:in_reply_to_id]), params[:media_ids]) + @status = PostStatusService.new.call(current_user.account, params[:status], params[:in_reply_to_id].blank? ? nil : Status.find(params[:in_reply_to_id]), params[:media_ids]) render action: :show end def destroy @status = Status.where(account_id: current_user.account).find(params[:id]) - RemoveStatusService.new.(@status) + RemoveStatusService.new.call(@status) render_empty end def reblog - @status = ReblogService.new.(current_user.account, Status.find(params[:id])).reload + @status = ReblogService.new.call(current_user.account, Status.find(params[:id])).reload render action: :show end def unreblog - RemoveStatusService.new.(Status.where(account_id: current_user.account, reblog_of_id: params[:id]).first!) + RemoveStatusService.new.call(Status.where(account_id: current_user.account, reblog_of_id: params[:id]).first!) @status = Status.find(params[:id]) render action: :show end def favourite - @status = FavouriteService.new.(current_user.account, Status.find(params[:id])).status.reload + @status = FavouriteService.new.call(current_user.account, Status.find(params[:id])).status.reload render action: :show end def unfavourite - @status = UnfavouriteService.new.(current_user.account, Status.find(params[:id])).status.reload + @status = UnfavouriteService.new.call(current_user.account, Status.find(params[:id])).status.reload render action: :show end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 90e923951..9b6367187 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -11,7 +11,7 @@ class ApplicationController < ActionController::Base rescue_from ActiveRecord::RecordNotFound, with: :not_found def raise_not_found - raise ActionController::RoutingError.new("No route matches #{params[:unmatched_route]}") + raise ActionController::RoutingError, "No route matches #{params[:unmatched_route]}" end protected diff --git a/app/controllers/auth/registrations_controller.rb b/app/controllers/auth/registrations_controller.rb index 8472edc69..71eb0905e 100644 --- a/app/controllers/auth/registrations_controller.rb +++ b/app/controllers/auth/registrations_controller.rb @@ -1,13 +1,13 @@ class Auth::RegistrationsController < Devise::RegistrationsController layout 'auth' - before_filter :configure_sign_up_params, only: [:create] + before_action :configure_sign_up_params, only: [:create] protected def build_resource(hash = nil) super(hash) - self.resource.build_account if self.resource.account.nil? + resource.build_account if resource.account.nil? end def configure_sign_up_params diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 974c5f7fd..4e6b2a879 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -7,7 +7,7 @@ class HomeController < ApplicationController @mentions = Feed.new(:mentions, current_user.account).get(20) @token = find_or_create_access_token.token end - + private def authenticate_user! diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index 0e6393a62..e4a246ec9 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -1,6 +1,6 @@ class SettingsController < ApplicationController layout 'auth' - + before_action :authenticate_user! before_action :set_account diff --git a/app/controllers/stream_entries_controller.rb b/app/controllers/stream_entries_controller.rb index 0d6b9ea8e..fd8b97c9f 100644 --- a/app/controllers/stream_entries_controller.rb +++ b/app/controllers/stream_entries_controller.rb @@ -13,7 +13,7 @@ class StreamEntriesController < ApplicationController @descendants = @stream_entry.activity.descendants if user_signed_in? - status_ids = [@stream_entry.activity_id] + @ancestors.map { |s| s.id } + @descendants.map { |s| s.id } + status_ids = [@stream_entry.activity_id] + @ancestors.map(&:id) + @descendants.map(&:id) @favourited = Status.favourites_map(status_ids, current_user.account_id) @reblogged = Status.reblogs_map(status_ids, current_user.account_id) else diff --git a/app/controllers/xrd_controller.rb b/app/controllers/xrd_controller.rb index 1e39a3e4c..9201eb6c1 100644 --- a/app/controllers/xrd_controller.rb +++ b/app/controllers/xrd_controller.rb @@ -31,9 +31,9 @@ class XrdController < ApplicationController def pem_to_magic_key(public_key) modulus, exponent = [public_key.n, public_key.e].map do |component| - result = "" + result = '' - until component == 0 do + until component.zero? result << [component % 256].pack('C') component >>= 8 end @@ -41,7 +41,7 @@ class XrdController < ApplicationController result.reverse! end - (["RSA"] + [modulus, exponent].map { |n| Base64.urlsafe_encode64(n) }).join('.') + (['RSA'] + [modulus, exponent].map { |n| Base64.urlsafe_encode64(n) }).join('.') end def resource_param diff --git a/app/helpers/atom_builder_helper.rb b/app/helpers/atom_builder_helper.rb index 39ea20e31..c1ca8c619 100644 --- a/app/helpers/atom_builder_helper.rb +++ b/app/helpers/atom_builder_helper.rb @@ -200,6 +200,6 @@ module AtomBuilderHelper end def single_link_avatar(xml, account, size, px) - xml.link('rel' => 'avatar', 'type' => account.avatar_content_type, 'media:width' => px, 'media:height' =>px, 'href' => full_asset_url(account.avatar.url(size, false))) + xml.link('rel' => 'avatar', 'type' => account.avatar_content_type, 'media:width' => px, 'media:height' => px, 'href' => full_asset_url(account.avatar.url(size, false))) end end diff --git a/app/helpers/stream_entries_helper.rb b/app/helpers/stream_entries_helper.rb index ce77206ea..e994155b6 100644 --- a/app/helpers/stream_entries_helper.rb +++ b/app/helpers/stream_entries_helper.rb @@ -17,15 +17,15 @@ module StreamEntriesHelper end def relative_time(date) - date < 5.days.ago ? date.strftime("%d.%m.%Y") : "#{time_ago_in_words(date)} ago" + date < 5.days.ago ? date.strftime('%d.%m.%Y') : "#{time_ago_in_words(date)} ago" end def reblogged_by_me_class(status) - user_signed_in? && @reblogged.has_key?(status.id) ? 'reblogged' : '' + user_signed_in? && @reblogged.key?(status.id) ? 'reblogged' : '' end def favourited_by_me_class(status) - user_signed_in? && @favourited.has_key?(status.id) ? 'favourited' : '' + user_signed_in? && @favourited.key?(status.id) ? 'favourited' : '' end def proper_status(status) diff --git a/app/lib/formatter.rb b/app/lib/formatter.rb index 959ede95e..17d2dfc58 100644 --- a/app/lib/formatter.rb +++ b/app/lib/formatter.rb @@ -35,7 +35,7 @@ class Formatter def link_mentions(html, mentions) html.gsub(Account::MENTION_RE) do |match| acct = Account::MENTION_RE.match(match)[1] - mention = mentions.find { |item| item.account.acct.eql?(acct) } + mention = mentions.find { |item| item.account.acct.casecmp(acct).zero? } mention.nil? ? match : mention_html(match, mention.account) end diff --git a/app/models/account.rb b/app/models/account.rb index 16db2d719..2fbd5a655 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -2,7 +2,7 @@ class Account < ApplicationRecord include Targetable MENTION_RE = /(?:^|\s|\.|>)@([a-z0-9_]+(?:@[a-z0-9\.\-]+)?)/i - IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'] + IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze # Local users has_one :user, inverse_of: :account @@ -45,11 +45,11 @@ class Account < ApplicationRecord scope :expiring, -> (time) { where(subscription_expires_at: nil).or(where('subscription_expires_at < ?', time)).remote.with_followers } def follow!(other_account) - self.active_relationships.where(target_account: other_account).first_or_create!(target_account: other_account) + active_relationships.where(target_account: other_account).first_or_create!(target_account: other_account) end def unfollow!(other_account) - follow = self.active_relationships.find_by(target_account: other_account) + follow = active_relationships.find_by(target_account: other_account) follow.destroy unless follow.nil? end @@ -58,15 +58,15 @@ class Account < ApplicationRecord end def local? - self.domain.nil? + domain.nil? end def acct - local? ? self.username : "#{self.username}@#{self.domain}" + local? ? username : "#{username}@#{domain}" end def subscribed? - !self.subscription_expires_at.nil? + !subscription_expires_at.nil? end def favourited?(status) @@ -78,11 +78,11 @@ class Account < ApplicationRecord end def keypair - self.private_key.nil? ? OpenSSL::PKey::RSA.new(self.public_key) : OpenSSL::PKey::RSA.new(self.private_key) + private_key.nil? ? OpenSSL::PKey::RSA.new(public_key) : OpenSSL::PKey::RSA.new(private_key) end def subscription(webhook_url) - OStatus2::Subscription.new(self.remote_url, secret: self.secret, lease_seconds: 86400 * 30, webhook: webhook_url, hub: self.hub_url) + OStatus2::Subscription.new(remote_url, secret: secret, lease_seconds: 86_400 * 30, webhook: webhook_url, hub: hub_url) end def ping!(atom_url, hubs) @@ -91,10 +91,7 @@ class Account < ApplicationRecord end def avatar_remote_url=(url) - unless self[:avatar_remote_url] == url - self.avatar = URI.parse(url) - end - + self.avatar = URI.parse(url) unless self[:avatar_remote_url] == url self[:avatar_remote_url] = url end @@ -103,26 +100,25 @@ class Account < ApplicationRecord end def to_param - self.username + username end def self.find_local!(username) - self.find_remote!(username, nil) + find_remote!(username, nil) end def self.find_remote!(username, domain) - table = self.arel_table - self.where(table[:username].matches(username)).where(domain: domain).take! + where(arel_table[:username].matches(username)).where(domain: domain).take! end def self.find_local(username) - self.find_local!(username) + find_local!(username) rescue ActiveRecord::RecordNotFound nil end def self.find_remote(username, domain) - self.find_remote!(username, domain) + find_remote!(username, domain) rescue ActiveRecord::RecordNotFound nil end diff --git a/app/models/concerns/streamable.rb b/app/models/concerns/streamable.rb index 8d754949e..b3354c819 100644 --- a/app/models/concerns/streamable.rb +++ b/app/models/concerns/streamable.rb @@ -25,7 +25,7 @@ module Streamable end after_create do - self.account.stream_entries.create!(activity: self) if self.account.local? + account.stream_entries.create!(activity: self) if account.local? end end end diff --git a/app/models/favourite.rb b/app/models/favourite.rb index e248ae561..3681181e5 100644 --- a/app/models/favourite.rb +++ b/app/models/favourite.rb @@ -11,7 +11,7 @@ class Favourite < ApplicationRecord end def title - "#{self.account.acct} favourited a status by #{self.status.account.acct}" + "#{account.acct} favourited a status by #{status.account.acct}" end def object_type @@ -19,7 +19,7 @@ class Favourite < ApplicationRecord end def thread - self.status + status end def target diff --git a/app/models/feed.rb b/app/models/feed.rb index bc3e960d4..5807ff176 100644 --- a/app/models/feed.rb +++ b/app/models/feed.rb @@ -7,11 +7,11 @@ class Feed def get(limit, max_id = nil) max_id = '+inf' if max_id.nil? unhydrated = redis.zrevrangebyscore(key, "(#{max_id}", '-inf', limit: [0, limit]) - status_map = Hash.new + status_map = {} # If we're after most recent items and none are there, we need to precompute the feed if unhydrated.empty? && max_id == '+inf' - PrecomputeFeedService.new.(@type, @account, limit) + PrecomputeFeedService.new.call(@type, @account, limit) else Status.where(id: unhydrated).with_includes.with_counters.each { |status| status_map[status.id.to_s] = status } unhydrated.map { |id| status_map[id] }.compact diff --git a/app/models/follow.rb b/app/models/follow.rb index 456e2c4f4..4f47580e1 100644 --- a/app/models/follow.rb +++ b/app/models/follow.rb @@ -8,11 +8,11 @@ class Follow < ApplicationRecord validates :account_id, uniqueness: { scope: :target_account_id } def verb - self.destroyed? ? :unfollow : :follow + destroyed? ? :unfollow : :follow end def target - self.target_account + target_account end def object_type @@ -20,6 +20,6 @@ class Follow < ApplicationRecord end def title - self.destroyed? ? "#{self.account.acct} is no longer following #{self.target_account.acct}" : "#{self.account.acct} started following #{self.target_account.acct}" + destroyed? ? "#{account.acct} is no longer following #{target_account.acct}" : "#{account.acct} started following #{target_account.acct}" end end diff --git a/app/models/media_attachment.rb b/app/models/media_attachment.rb index 73fb967c4..e2cbe397e 100644 --- a/app/models/media_attachment.rb +++ b/app/models/media_attachment.rb @@ -1,18 +1,18 @@ class MediaAttachment < ApplicationRecord - IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'] - VIDEO_MIME_TYPES = ['video/webm'] + IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze + VIDEO_MIME_TYPES = ['video/webm'].freeze belongs_to :account, inverse_of: :media_attachments belongs_to :status, inverse_of: :media_attachments - has_attached_file :file, styles: lambda { |f| f.instance.image? ? { small: '510x680>' } : { small: { convert_options: { output: { vf: 'scale="min(510\, iw):min(680\, ih)":force_original_aspect_ratio=decrease' } }, format: 'png', time: 1 } } }, processors: lambda { |f| f.video? ? [:transcoder] : [:thumbnail] } + has_attached_file :file, styles: -> (f) { f.instance.image? ? { small: '510x680>' } : { small: { convert_options: { output: { vf: 'scale="min(510\, iw):min(680\, ih)":force_original_aspect_ratio=decrease' } }, format: 'png', time: 1 } } }, processors: -> (f) { f.video? ? [:transcoder] : [:thumbnail] } validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES validates_attachment_size :file, less_than: 4.megabytes validates :account, presence: true def local? - self.remote_url.blank? + remote_url.blank? end def file_remote_url=(url) diff --git a/app/models/status.rb b/app/models/status.rb index cbcde69f4..1f1a70946 100644 --- a/app/models/status.rb +++ b/app/models/status.rb @@ -15,21 +15,21 @@ class Status < ApplicationRecord validates :account, presence: true validates :uri, uniqueness: true, unless: 'local?' - validates :text, presence: true, length: { maximum: 500 }, if: Proc.new { |s| s.local? && !s.reblog? } + validates :text, presence: true, length: { maximum: 500 }, if: proc { |s| s.local? && !s.reblog? } scope :with_counters, -> { select('statuses.*, (select count(r.id) from statuses as r where r.reblog_of_id = statuses.id) as reblogs_count, (select count(f.id) from favourites as f where f.status_id = statuses.id) as favourites_count') } scope :with_includes, -> { includes(:account, :media_attachments, :stream_entry, mentions: :account, reblog: [:account, mentions: :account], thread: :account) } def local? - self.uri.nil? + uri.nil? end def reblog? - !self.reblog_of_id.nil? + !reblog_of_id.nil? end def reply? - !self.in_reply_to_id.nil? + !in_reply_to_id.nil? end def verb @@ -41,11 +41,11 @@ class Status < ApplicationRecord end def content - reblog? ? self.reblog.text : self.text + reblog? ? reblog.text : text end def target - self.reblog + reblog end def title @@ -53,33 +53,33 @@ class Status < ApplicationRecord end def reblogs_count - self.attributes['reblogs_count'] || self.reblogs.count + attributes['reblogs_count'] || reblogs.count end def favourites_count - self.attributes['favourites_count'] || self.favourites.count + attributes['favourites_count'] || favourites.count end def ancestors - ids = (Status.find_by_sql(['WITH RECURSIVE search_tree(id, in_reply_to_id, path) AS (SELECT id, in_reply_to_id, ARRAY[id] FROM statuses WHERE id = ? UNION ALL SELECT statuses.id, statuses.in_reply_to_id, path || statuses.id FROM search_tree JOIN statuses ON statuses.id = search_tree.in_reply_to_id WHERE NOT statuses.id = ANY(path)) SELECT id FROM search_tree ORDER BY path DESC', self.id]) - [self]).pluck(:id) + ids = (Status.find_by_sql(['WITH RECURSIVE search_tree(id, in_reply_to_id, path) AS (SELECT id, in_reply_to_id, ARRAY[id] FROM statuses WHERE id = ? UNION ALL SELECT statuses.id, statuses.in_reply_to_id, path || statuses.id FROM search_tree JOIN statuses ON statuses.id = search_tree.in_reply_to_id WHERE NOT statuses.id = ANY(path)) SELECT id FROM search_tree ORDER BY path DESC', id]) - [self]).pluck(:id) statuses = Status.where(id: ids).with_counters.with_includes.group_by(&:id) ids.map { |id| statuses[id].first } end def descendants - ids = (Status.find_by_sql(['WITH RECURSIVE search_tree(id, path) AS (SELECT id, ARRAY[id] FROM statuses WHERE id = ? UNION ALL SELECT statuses.id, path || statuses.id FROM search_tree JOIN statuses ON statuses.in_reply_to_id = search_tree.id WHERE NOT statuses.id = ANY(path)) SELECT id FROM search_tree ORDER BY path', self.id]) - [self]).pluck(:id) + ids = (Status.find_by_sql(['WITH RECURSIVE search_tree(id, path) AS (SELECT id, ARRAY[id] FROM statuses WHERE id = ? UNION ALL SELECT statuses.id, path || statuses.id FROM search_tree JOIN statuses ON statuses.in_reply_to_id = search_tree.id WHERE NOT statuses.id = ANY(path)) SELECT id FROM search_tree ORDER BY path', id]) - [self]).pluck(:id) statuses = Status.where(id: ids).with_counters.with_includes.group_by(&:id) ids.map { |id| statuses[id].first } end def self.as_home_timeline(account) - self.where(account: [account] + account.following).with_includes.with_counters + where(account: [account] + account.following).with_includes.with_counters end def self.as_mentions_timeline(account) - self.where(id: Mention.where(account: account).pluck(:status_id)).with_includes.with_counters + where(id: Mention.where(account: account).pluck(:status_id)).with_includes.with_counters end def self.favourites_map(status_ids, account_id) @@ -87,10 +87,10 @@ class Status < ApplicationRecord end def self.reblogs_map(status_ids, account_id) - self.where(reblog_of_id: status_ids).where(account_id: account_id).map { |s| [s.reblog_of_id, true] }.to_h + where(reblog_of_id: status_ids).where(account_id: account_id).map { |s| [s.reblog_of_id, true] }.to_h end before_validation do - self.text.strip! + text.strip! end end diff --git a/app/models/stream_entry.rb b/app/models/stream_entry.rb index f33295796..261ecda53 100644 --- a/app/models/stream_entry.rb +++ b/app/models/stream_entry.rb @@ -10,16 +10,16 @@ class StreamEntry < ApplicationRecord validates :account, :activity, presence: true - STATUS_INCLUDES = [:account, :stream_entry, :media_attachments, mentions: :account, reblog: [:stream_entry, :account, mentions: :account], thread: [:stream_entry, :account]] + STATUS_INCLUDES = [:account, :stream_entry, :media_attachments, mentions: :account, reblog: [:stream_entry, :account, mentions: :account], thread: [:stream_entry, :account]].freeze scope :with_includes, -> { includes(:account, status: STATUS_INCLUDES, favourite: [:account, :stream_entry, status: STATUS_INCLUDES], follow: [:target_account, :stream_entry]) } def object_type - orphaned? ? :activity : (targeted? ? :activity : self.activity.object_type) + orphaned? ? :activity : (targeted? ? :activity : activity.object_type) end def verb - orphaned? ? :delete : self.activity.verb + orphaned? ? :delete : activity.verb end def targeted? @@ -27,15 +27,15 @@ class StreamEntry < ApplicationRecord end def target - orphaned? ? nil : self.activity.target + orphaned? ? nil : activity.target end def title - orphaned? ? nil : self.activity.title + orphaned? ? nil : activity.title end def content - orphaned? ? nil : self.activity.content + orphaned? ? nil : activity.content end def threaded? @@ -43,20 +43,20 @@ class StreamEntry < ApplicationRecord end def thread - orphaned? ? nil : self.activity.thread + orphaned? ? nil : activity.thread end def mentions - self.activity.respond_to?(:mentions) ? self.activity.mentions.map { |x| x.account } : [] + activity.respond_to?(:mentions) ? activity.mentions.map { |x| x.account } : [] end def activity - self.send(self.activity_type.downcase.to_sym) + send(activity_type.downcase.to_sym) end private def orphaned? - self.activity.nil? + activity.nil? end end diff --git a/app/models/user.rb b/app/models/user.rb index d4361ffa1..9c0546c2f 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -11,8 +11,8 @@ class User < ApplicationRecord scope :prolific, -> { joins('inner join statuses on statuses.account_id = users.account_id').select('users.*, count(statuses.id) as statuses_count').group('users.id').order('statuses_count desc') } scope :recent, -> { order('created_at desc') } scope :admins, -> { where(admin: true) } - + def admin? - self.admin + admin end end diff --git a/app/services/fetch_atom_service.rb b/app/services/fetch_atom_service.rb index 819bea02e..4be7f6355 100644 --- a/app/services/fetch_atom_service.rb +++ b/app/services/fetch_atom_service.rb @@ -17,7 +17,7 @@ class FetchAtomService < BaseService private def process_html(body) - Rails.logger.debug "Processing HTML" + Rails.logger.debug 'Processing HTML' page = Nokogiri::HTML(body) alternate_link = page.xpath('//link[@rel="alternate"]').find { |link| link['type'] == 'application/atom+xml' } @@ -27,7 +27,7 @@ class FetchAtomService < BaseService end def process_headers(url, response) - Rails.logger.debug "Processing link header" + Rails.logger.debug 'Processing link header' link_header = LinkHeader.parse(response['Link'].is_a?(Array) ? response['Link'].first : response['Link']) alternate_link = link_header.find_link(['rel', 'alternate'], ['type', 'application/atom+xml']) diff --git a/app/services/fetch_remote_account_service.rb b/app/services/fetch_remote_account_service.rb index 072eb2cd3..5f45f9b28 100644 --- a/app/services/fetch_remote_account_service.rb +++ b/app/services/fetch_remote_account_service.rb @@ -1,6 +1,6 @@ class FetchRemoteAccountService < BaseService def call(url) - atom_url, body = FetchAtomService.new.(url) + atom_url, body = FetchAtomService.new.call(url) return nil if atom_url.nil? return process_atom(atom_url, body) @@ -18,6 +18,6 @@ class FetchRemoteAccountService < BaseService Rails.logger.debug "Going to webfinger #{username}@#{domain}" - return FollowRemoteAccountService.new.("#{username}@#{domain}") + return FollowRemoteAccountService.new.call("#{username}@#{domain}") end end diff --git a/app/services/fetch_remote_status_service.rb b/app/services/fetch_remote_status_service.rb index 7613607b4..24a63e841 100644 --- a/app/services/fetch_remote_status_service.rb +++ b/app/services/fetch_remote_status_service.rb @@ -1,6 +1,6 @@ class FetchRemoteStatusService < BaseService def call(url) - atom_url, body = FetchAtomService.new.(url) + atom_url, body = FetchAtomService.new.call(url) return nil if atom_url.nil? return process_atom(atom_url, body) @@ -9,14 +9,14 @@ class FetchRemoteStatusService < BaseService private def process_atom(url, body) - Rails.logger.debug "Processing Atom for remote status" + Rails.logger.debug 'Processing Atom for remote status' xml = Nokogiri::XML(body) account = extract_author(url, xml) return nil if account.nil? - statuses = ProcessFeedService.new.(body, account) + statuses = ProcessFeedService.new.call(body, account) return statuses.first end @@ -30,6 +30,6 @@ class FetchRemoteStatusService < BaseService Rails.logger.debug "Going to webfinger #{username}@#{domain}" - return FollowRemoteAccountService.new.("#{username}@#{domain}") + return FollowRemoteAccountService.new.call("#{username}@#{domain}") end end diff --git a/app/services/follow_remote_account_service.rb b/app/services/follow_remote_account_service.rb index ef3949e36..9fbf17091 100644 --- a/app/services/follow_remote_account_service.rb +++ b/app/services/follow_remote_account_service.rb @@ -28,11 +28,11 @@ class FollowRemoteAccountService < BaseService hubs = feed.xpath('//xmlns:link[@rel="hub"]') if hubs.empty? || hubs.first.attribute('href').nil? - raise Goldfinger::Error, "No PubSubHubbub hubs found" + raise Goldfinger::Error, 'No PubSubHubbub hubs found' end if feed.at_xpath('/xmlns:feed/xmlns:author/xmlns:uri').nil? - raise Goldfinger::Error, "No author URI found" + raise Goldfinger::Error, 'No author URI found' end account.uri = feed.at_xpath('/xmlns:feed/xmlns:author/xmlns:uri').content @@ -53,12 +53,12 @@ class FollowRemoteAccountService < BaseService def get_profile(xml, account) author = xml.at_xpath('/xmlns:feed/xmlns:author') - update_remote_profile_service.(author, account) + update_remote_profile_service.call(author, account) end def magic_key_to_pem(magic_key) _, modulus, exponent = magic_key.split('.') - modulus, exponent = [modulus, exponent].map { |n| Base64.urlsafe_decode64(n).bytes.inject(0) { |num, byte| (num << 8) | byte } } + modulus, exponent = [modulus, exponent].map { |n| Base64.urlsafe_decode64(n).bytes.inject(0) { |a, e| (a << 8) | e } } key = OpenSSL::PKey::RSA.new key.n = modulus @@ -75,4 +75,3 @@ class FollowRemoteAccountService < BaseService HTTP.timeout(:per_operation, write: 20, connect: 20, read: 50) end end - diff --git a/app/services/follow_service.rb b/app/services/follow_service.rb index fb782e871..6dd85dd7d 100644 --- a/app/services/follow_service.rb +++ b/app/services/follow_service.rb @@ -3,7 +3,7 @@ class FollowService < BaseService # @param [Account] source_account From which to follow # @param [String] uri User URI to follow in the form of username@domain def call(source_account, uri) - target_account = follow_remote_account_service.(uri) + target_account = follow_remote_account_service.call(uri) return nil if target_account.nil? || target_account.id == source_account.id @@ -12,7 +12,7 @@ class FollowService < BaseService if target_account.local? NotificationMailer.follow(target_account, source_account).deliver_later else - subscribe_service.(target_account) + subscribe_service.call(target_account) NotificationWorker.perform_async(follow.stream_entry.id, target_account.id) end diff --git a/app/services/post_status_service.rb b/app/services/post_status_service.rb index 930e7ec9e..6e53c7e52 100644 --- a/app/services/post_status_service.rb +++ b/app/services/post_status_service.rb @@ -8,7 +8,7 @@ class PostStatusService < BaseService def call(account, text, in_reply_to = nil, media_ids = nil) status = account.statuses.create!(text: text, thread: in_reply_to) attach_media(status, media_ids) - process_mentions_service.(status) + process_mentions_service.call(status) DistributionWorker.perform_async(status.id) account.ping!(account_url(account, format: 'atom'), [Rails.configuration.x.hub_url]) status @@ -19,7 +19,7 @@ class PostStatusService < BaseService def attach_media(status, media_ids) return if media_ids.nil? || !media_ids.is_a?(Enumerable) - media = MediaAttachment.where(status_id: nil).where(id: media_ids.take(4).map { |id| id.to_i }) + media = MediaAttachment.where(status_id: nil).where(id: media_ids.take(4).map(&:to_i)) media.update(status_id: status.id) end diff --git a/app/services/process_feed_service.rb b/app/services/process_feed_service.rb index 47992b246..fdf59b41c 100644 --- a/app/services/process_feed_service.rb +++ b/app/services/process_feed_service.rb @@ -5,7 +5,7 @@ class ProcessFeedService < BaseService # @return [Enumerable] created statuses def call(body, account) xml = Nokogiri::XML(body) - update_remote_profile_service.(xml.at_xpath('/xmlns:feed/xmlns:author'), account) unless xml.at_xpath('/xmlns:feed').nil? + update_remote_profile_service.call(xml.at_xpath('/xmlns:feed/xmlns:author'), account) unless xml.at_xpath('/xmlns:feed').nil? xml.xpath('//xmlns:entry').reverse_each.map { |entry| process_entry(account, entry) }.compact end @@ -60,7 +60,7 @@ class ProcessFeedService < BaseService href_val = mention_link.attribute('href').value next if href_val == 'http://activityschema.org/collection/public' - + href = Addressable::URI.parse(href_val) if href.host == Rails.configuration.x.local_domain @@ -77,7 +77,7 @@ class ProcessFeedService < BaseService mentioned_account = Account.find_by(url: href.to_s) if mentioned_account.nil? - mentioned_account = FetchRemoteAccountService.new.(href) + mentioned_account = FetchRemoteAccountService.new.call(href) end unless mentioned_account.nil? @@ -94,7 +94,7 @@ class ProcessFeedService < BaseService media = MediaAttachment.where(status: status, remote_url: enclosure_link.attribute('href').value).first next unless media.nil? - + media = MediaAttachment.new(account: status.account, status: status, remote_url: enclosure_link.attribute('href').value) media.file_remote_url = enclosure_link.attribute('href').value media.save @@ -128,7 +128,7 @@ class ProcessFeedService < BaseService end def delete_post!(status) - remove_status_service.(status) + remove_status_service.call(status) end def find_original_status(_xml, id) @@ -148,7 +148,7 @@ class ProcessFeedService < BaseService account = Account.find_by(username: username, domain: domain) if account.nil? - account = follow_remote_account_service.("#{username}@#{domain}") + account = follow_remote_account_service.call("#{username}@#{domain}") end status = Status.new(account: account, uri: target_id(xml), text: target_content(xml), url: target_url(xml), created_at: published(xml), updated_at: updated(xml)) diff --git a/app/services/process_interaction_service.rb b/app/services/process_interaction_service.rb index 1e3ed6b12..96dae30da 100644 --- a/app/services/process_interaction_service.rb +++ b/app/services/process_interaction_service.rb @@ -14,11 +14,11 @@ class ProcessInteractionService < BaseService account = Account.find_by(username: username, domain: domain) if account.nil? - account = follow_remote_account_service.("#{username}@#{domain}") + account = follow_remote_account_service.call("#{username}@#{domain}") end if salmon.verify(envelope, account.keypair) - update_remote_profile_service.(xml.at_xpath('/xmlns:entry/xmlns:author'), account) + update_remote_profile_service.call(xml.at_xpath('/xmlns:entry/xmlns:author'), account) case verb(xml) when :follow @@ -71,7 +71,7 @@ class ProcessInteractionService < BaseService return if status.nil? if account.id == status.account_id - remove_status_service.(status) + remove_status_service.call(status) end end @@ -82,7 +82,7 @@ class ProcessInteractionService < BaseService end def add_post!(body, account) - process_feed_service.(body, account) + process_feed_service.call(body, account) end def status(xml) diff --git a/app/services/process_mentions_service.rb b/app/services/process_mentions_service.rb index 5ea184252..2d09fc2cd 100644 --- a/app/services/process_mentions_service.rb +++ b/app/services/process_mentions_service.rb @@ -12,7 +12,7 @@ class ProcessMentionsService < BaseService if mentioned_account.nil? && !domain.nil? begin - mentioned_account = follow_remote_account_service.("#{match.first}") + mentioned_account = follow_remote_account_service.call(match.first.to_s) rescue Goldfinger::Error, HTTP::Error mentioned_account = nil end diff --git a/app/services/remove_status_service.rb b/app/services/remove_status_service.rb index b64f04a14..030d23ff6 100644 --- a/app/services/remove_status_service.rb +++ b/app/services/remove_status_service.rb @@ -39,7 +39,7 @@ class RemoveStatusService < BaseService def remove_reblogs(status) status.reblogs.each do |reblog| - RemoveStatusService.new.(reblog) + RemoveStatusService.new.call(reblog) end end diff --git a/app/workers/distribution_worker.rb b/app/workers/distribution_worker.rb index d529ed87f..a69b39523 100644 --- a/app/workers/distribution_worker.rb +++ b/app/workers/distribution_worker.rb @@ -2,6 +2,6 @@ class DistributionWorker include Sidekiq::Worker def perform(status_id) - FanOutOnWriteService.new.(Status.find(status_id)) + FanOutOnWriteService.new.call(Status.find(status_id)) end end diff --git a/app/workers/notification_worker.rb b/app/workers/notification_worker.rb index 129512a5a..473a9232b 100644 --- a/app/workers/notification_worker.rb +++ b/app/workers/notification_worker.rb @@ -2,6 +2,6 @@ class NotificationWorker include Sidekiq::Worker def perform(stream_entry_id, target_account_id) - SendInteractionService.new.(StreamEntry.find(stream_entry_id), Account.find(target_account_id)) + SendInteractionService.new.call(StreamEntry.find(stream_entry_id), Account.find(target_account_id)) end end diff --git a/app/workers/thread_resolve_worker.rb b/app/workers/thread_resolve_worker.rb index ccc56380b..c59fb093a 100644 --- a/app/workers/thread_resolve_worker.rb +++ b/app/workers/thread_resolve_worker.rb @@ -3,7 +3,7 @@ class ThreadResolveWorker def perform(child_status_id, parent_url) child_status = Status.find(child_status_id) - parent_status = FetchRemoteStatusService.new.(parent_url) + parent_status = FetchRemoteStatusService.new.call(parent_url) unless parent_status.nil? child_status.thread = parent_status