follow.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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_destroy :remove_endorsements
  38. after_destroy :decrement_cache_counters
  39. after_commit :invalidate_follow_recommendations_cache
  40. after_commit :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. def invalidate_follow_recommendations_cache
  61. Rails.cache.delete("follow_recommendations/#{account_id}")
  62. end
  63. end