account.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: accounts
  5. #
  6. # id :integer not null, primary key
  7. # username :string default(""), not null
  8. # domain :string
  9. # secret :string default(""), not null
  10. # private_key :text
  11. # public_key :text default(""), not null
  12. # remote_url :string default(""), not null
  13. # salmon_url :string default(""), not null
  14. # hub_url :string default(""), not null
  15. # created_at :datetime not null
  16. # updated_at :datetime not null
  17. # note :text default(""), not null
  18. # display_name :string default(""), not null
  19. # uri :string default(""), not null
  20. # url :string
  21. # avatar_file_name :string
  22. # avatar_content_type :string
  23. # avatar_file_size :integer
  24. # avatar_updated_at :datetime
  25. # header_file_name :string
  26. # header_content_type :string
  27. # header_file_size :integer
  28. # header_updated_at :datetime
  29. # avatar_remote_url :string
  30. # subscription_expires_at :datetime
  31. # silenced :boolean default(FALSE), not null
  32. # suspended :boolean default(FALSE), not null
  33. # locked :boolean default(FALSE), not null
  34. # header_remote_url :string default(""), not null
  35. # statuses_count :integer default(0), not null
  36. # followers_count :integer default(0), not null
  37. # following_count :integer default(0), not null
  38. # last_webfingered_at :datetime
  39. # inbox_url :string default(""), not null
  40. # outbox_url :string default(""), not null
  41. # shared_inbox_url :string default(""), not null
  42. # followers_url :string default(""), not null
  43. # protocol :integer default("ostatus"), not null
  44. #
  45. class Account < ApplicationRecord
  46. MENTION_RE = /(?:^|[^\/[:word:]])@(([a-z0-9_]+)(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  47. include AccountAvatar
  48. include AccountFinderConcern
  49. include AccountHeader
  50. include AccountInteractions
  51. include Attachmentable
  52. include Remotable
  53. enum protocol: [:ostatus, :activitypub]
  54. # Local users
  55. has_one :user, inverse_of: :account
  56. validates :username, presence: true
  57. # Remote user validations
  58. validates :username, uniqueness: { scope: :domain, case_sensitive: true }, if: -> { !local? && will_save_change_to_username? }
  59. # Local user validations
  60. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, uniqueness: { scope: :domain, case_sensitive: false }, length: { maximum: 30 }, if: -> { local? && will_save_change_to_username? }
  61. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? }
  62. validates :display_name, length: { maximum: 30 }, if: -> { local? && will_save_change_to_display_name? }
  63. validates :note, length: { maximum: 160 }, if: -> { local? && will_save_change_to_note? }
  64. # Timelines
  65. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  66. has_many :statuses, inverse_of: :account, dependent: :destroy
  67. has_many :favourites, inverse_of: :account, dependent: :destroy
  68. has_many :mentions, inverse_of: :account, dependent: :destroy
  69. has_many :notifications, inverse_of: :account, dependent: :destroy
  70. # Pinned statuses
  71. has_many :status_pins, inverse_of: :account, dependent: :destroy
  72. has_many :pinned_statuses, -> { reorder('status_pins.created_at DESC') }, through: :status_pins, class_name: 'Status', source: :status
  73. # Media
  74. has_many :media_attachments, dependent: :destroy
  75. # PuSH subscriptions
  76. has_many :subscriptions, dependent: :destroy
  77. # Report relationships
  78. has_many :reports
  79. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  80. scope :remote, -> { where.not(domain: nil) }
  81. scope :local, -> { where(domain: nil) }
  82. scope :without_followers, -> { where(followers_count: 0) }
  83. scope :with_followers, -> { where('followers_count > 0') }
  84. scope :expiring, ->(time) { remote.where.not(subscription_expires_at: nil).where('subscription_expires_at < ?', time) }
  85. scope :partitioned, -> { order('row_number() over (partition by domain)') }
  86. scope :silenced, -> { where(silenced: true) }
  87. scope :suspended, -> { where(suspended: true) }
  88. scope :recent, -> { reorder(id: :desc) }
  89. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  90. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  91. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  92. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  93. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  94. delegate :email,
  95. :current_sign_in_ip,
  96. :current_sign_in_at,
  97. :confirmed?,
  98. :admin?,
  99. :locale,
  100. to: :user,
  101. prefix: true,
  102. allow_nil: true
  103. delegate :filtered_languages, to: :user, prefix: false, allow_nil: true
  104. def local?
  105. domain.nil?
  106. end
  107. def acct
  108. local? ? username : "#{username}@#{domain}"
  109. end
  110. def local_username_and_domain
  111. "#{username}@#{Rails.configuration.x.local_domain}"
  112. end
  113. def to_webfinger_s
  114. "acct:#{local_username_and_domain}"
  115. end
  116. def subscribed?
  117. subscription_expires_at.present?
  118. end
  119. def possibly_stale?
  120. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  121. end
  122. def refresh!
  123. return if local?
  124. ResolveRemoteAccountService.new.call(acct)
  125. end
  126. def keypair
  127. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  128. end
  129. def subscription(webhook_url)
  130. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  131. end
  132. def save_with_optional_media!
  133. save!
  134. rescue ActiveRecord::RecordInvalid
  135. self.avatar = nil
  136. self.header = nil
  137. self[:avatar_remote_url] = ''
  138. self[:header_remote_url] = ''
  139. save!
  140. end
  141. def object_type
  142. :person
  143. end
  144. def to_param
  145. username
  146. end
  147. def excluded_from_timeline_account_ids
  148. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  149. end
  150. def excluded_from_timeline_domains
  151. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  152. end
  153. class << self
  154. def readonly_attributes
  155. super - %w(statuses_count following_count followers_count)
  156. end
  157. def domains
  158. reorder(nil).pluck('distinct accounts.domain')
  159. end
  160. def inboxes
  161. urls = reorder(nil).where(protocol: :activitypub).pluck("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)")
  162. DeliveryFailureTracker.filter(urls)
  163. end
  164. def triadic_closures(account, limit: 5, offset: 0)
  165. sql = <<-SQL.squish
  166. WITH first_degree AS (
  167. SELECT target_account_id
  168. FROM follows
  169. WHERE account_id = :account_id
  170. )
  171. SELECT accounts.*
  172. FROM follows
  173. INNER JOIN accounts ON follows.target_account_id = accounts.id
  174. WHERE
  175. account_id IN (SELECT * FROM first_degree)
  176. AND target_account_id NOT IN (SELECT * FROM first_degree)
  177. AND target_account_id NOT IN (:excluded_account_ids)
  178. AND accounts.suspended = false
  179. GROUP BY target_account_id, accounts.id
  180. ORDER BY count(account_id) DESC
  181. OFFSET :offset
  182. LIMIT :limit
  183. SQL
  184. excluded_account_ids = account.excluded_from_timeline_account_ids + [account.id]
  185. find_by_sql(
  186. [sql, { account_id: account.id, excluded_account_ids: excluded_account_ids, limit: limit, offset: offset }]
  187. )
  188. end
  189. def search_for(terms, limit = 10)
  190. textsearch, query = generate_query_for_search(terms)
  191. sql = <<-SQL.squish
  192. SELECT
  193. accounts.*,
  194. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  195. FROM accounts
  196. WHERE #{query} @@ #{textsearch}
  197. AND accounts.suspended = false
  198. ORDER BY rank DESC
  199. LIMIT ?
  200. SQL
  201. find_by_sql([sql, limit])
  202. end
  203. def advanced_search_for(terms, account, limit = 10)
  204. textsearch, query = generate_query_for_search(terms)
  205. sql = <<-SQL.squish
  206. SELECT
  207. accounts.*,
  208. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  209. FROM accounts
  210. LEFT OUTER JOIN follows AS f ON (accounts.id = f.account_id AND f.target_account_id = ?) OR (accounts.id = f.target_account_id AND f.account_id = ?)
  211. WHERE #{query} @@ #{textsearch}
  212. AND accounts.suspended = false
  213. GROUP BY accounts.id
  214. ORDER BY rank DESC
  215. LIMIT ?
  216. SQL
  217. find_by_sql([sql, account.id, account.id, limit])
  218. end
  219. private
  220. def generate_query_for_search(terms)
  221. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  222. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  223. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  224. [textsearch, query]
  225. end
  226. end
  227. before_create :generate_keys
  228. before_validation :normalize_domain
  229. before_validation :prepare_contents, if: :local?
  230. private
  231. def prepare_contents
  232. display_name&.strip!
  233. note&.strip!
  234. end
  235. def generate_keys
  236. return unless local?
  237. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 512 : 2048)
  238. self.private_key = keypair.to_pem
  239. self.public_key = keypair.public_key.to_pem
  240. end
  241. def normalize_domain
  242. return if local?
  243. self.domain = TagManager.instance.normalize_domain(domain)
  244. end
  245. end