follow.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: follows
  5. #
  6. # id :bigint(8) not null, primary key
  7. # created_at :datetime not null
  8. # updated_at :datetime not null
  9. # account_id :bigint(8) not null
  10. # target_account_id :bigint(8) not null
  11. # show_reblogs :boolean default(TRUE), not null
  12. # uri :string
  13. # notify :boolean default(FALSE), not null
  14. # languages :string is an Array
  15. #
  16. class Follow < ApplicationRecord
  17. include Paginable
  18. include RelationshipCacheable
  19. include RateLimitable
  20. include FollowLimitable
  21. rate_limit by: :account, family: :follows
  22. belongs_to :account
  23. belongs_to :target_account, class_name: 'Account'
  24. has_one :notification, as: :activity, dependent: :destroy
  25. validates :account_id, uniqueness: { scope: :target_account_id }
  26. validates :languages, language: true
  27. scope :recent, -> { reorder(id: :desc) }
  28. def local?
  29. false # Force uri_for to use uri attribute
  30. end
  31. def revoke_request!
  32. FollowRequest.create!(account: account, target_account: target_account, show_reblogs: show_reblogs, notify: notify, languages: languages, uri: uri)
  33. destroy!
  34. end
  35. before_validation :set_uri, only: :create
  36. after_create :increment_cache_counters
  37. after_create :invalidate_hash_cache
  38. after_destroy :remove_endorsements
  39. after_destroy :decrement_cache_counters
  40. after_destroy :invalidate_hash_cache
  41. private
  42. def set_uri
  43. self.uri = ActivityPub::TagManager.instance.generate_uri_for(self) if uri.nil?
  44. end
  45. def remove_endorsements
  46. AccountPin.where(target_account_id: target_account_id, account_id: account_id).delete_all
  47. end
  48. def increment_cache_counters
  49. account&.increment_count!(:following_count)
  50. target_account&.increment_count!(:followers_count)
  51. end
  52. def decrement_cache_counters
  53. account&.decrement_count!(:following_count)
  54. target_account&.decrement_count!(:followers_count)
  55. end
  56. def invalidate_hash_cache
  57. return if account.local? && target_account.local?
  58. Rails.cache.delete("followers_hash:#{target_account_id}:#{account.synchronization_uri_prefix}")
  59. end
  60. end