account.rb 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. include EmojiHelper
  54. enum protocol: [:ostatus, :activitypub]
  55. # Local users
  56. has_one :user, inverse_of: :account
  57. validates :username, presence: true
  58. # Remote user validations
  59. validates :username, uniqueness: { scope: :domain, case_sensitive: true }, if: -> { !local? && will_save_change_to_username? }
  60. # Local user validations
  61. 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? }
  62. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? }
  63. validates :display_name, length: { maximum: 30 }, if: -> { local? && will_save_change_to_display_name? }
  64. validates :note, length: { maximum: 160 }, if: -> { local? && will_save_change_to_note? }
  65. # Timelines
  66. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  67. has_many :statuses, inverse_of: :account, dependent: :destroy
  68. has_many :favourites, inverse_of: :account, dependent: :destroy
  69. has_many :mentions, inverse_of: :account, dependent: :destroy
  70. has_many :notifications, inverse_of: :account, dependent: :destroy
  71. # Pinned statuses
  72. has_many :status_pins, inverse_of: :account, dependent: :destroy
  73. has_many :pinned_statuses, -> { reorder('status_pins.created_at DESC') }, through: :status_pins, class_name: 'Status', source: :status
  74. # Media
  75. has_many :media_attachments, dependent: :destroy
  76. # PuSH subscriptions
  77. has_many :subscriptions, dependent: :destroy
  78. # Report relationships
  79. has_many :reports
  80. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  81. scope :remote, -> { where.not(domain: nil) }
  82. scope :local, -> { where(domain: nil) }
  83. scope :without_followers, -> { where(followers_count: 0) }
  84. scope :with_followers, -> { where('followers_count > 0') }
  85. scope :expiring, ->(time) { remote.where.not(subscription_expires_at: nil).where('subscription_expires_at < ?', time) }
  86. scope :partitioned, -> { order('row_number() over (partition by domain)') }
  87. scope :silenced, -> { where(silenced: true) }
  88. scope :suspended, -> { where(suspended: true) }
  89. scope :recent, -> { reorder(id: :desc) }
  90. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  91. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  92. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  93. scope :matches_display_name, ->(value) { where(arel_table[:display_name].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 keypair
  120. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  121. end
  122. def subscription(webhook_url)
  123. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  124. end
  125. def save_with_optional_media!
  126. save!
  127. rescue ActiveRecord::RecordInvalid
  128. self.avatar = nil
  129. self.header = nil
  130. self[:avatar_remote_url] = ''
  131. self[:header_remote_url] = ''
  132. save!
  133. end
  134. def object_type
  135. :person
  136. end
  137. def to_param
  138. username
  139. end
  140. def excluded_from_timeline_account_ids
  141. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  142. end
  143. def excluded_from_timeline_domains
  144. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  145. end
  146. class << self
  147. def domains
  148. reorder(nil).pluck('distinct accounts.domain')
  149. end
  150. def inboxes
  151. reorder(nil).where(protocol: :activitypub).pluck("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)")
  152. end
  153. def triadic_closures(account, limit: 5, offset: 0)
  154. sql = <<-SQL.squish
  155. WITH first_degree AS (
  156. SELECT target_account_id
  157. FROM follows
  158. WHERE account_id = :account_id
  159. )
  160. SELECT accounts.*
  161. FROM follows
  162. INNER JOIN accounts ON follows.target_account_id = accounts.id
  163. WHERE
  164. account_id IN (SELECT * FROM first_degree)
  165. AND target_account_id NOT IN (SELECT * FROM first_degree)
  166. AND target_account_id NOT IN (:excluded_account_ids)
  167. AND accounts.suspended = false
  168. GROUP BY target_account_id, accounts.id
  169. ORDER BY count(account_id) DESC
  170. OFFSET :offset
  171. LIMIT :limit
  172. SQL
  173. excluded_account_ids = account.excluded_from_timeline_account_ids + [account.id]
  174. find_by_sql(
  175. [sql, { account_id: account.id, excluded_account_ids: excluded_account_ids, limit: limit, offset: offset }]
  176. )
  177. end
  178. def search_for(terms, limit = 10)
  179. textsearch, query = generate_query_for_search(terms)
  180. sql = <<-SQL.squish
  181. SELECT
  182. accounts.*,
  183. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  184. FROM accounts
  185. WHERE #{query} @@ #{textsearch}
  186. AND accounts.suspended = false
  187. ORDER BY rank DESC
  188. LIMIT ?
  189. SQL
  190. find_by_sql([sql, limit])
  191. end
  192. def advanced_search_for(terms, account, limit = 10)
  193. textsearch, query = generate_query_for_search(terms)
  194. sql = <<-SQL.squish
  195. SELECT
  196. accounts.*,
  197. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  198. FROM accounts
  199. 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 = ?)
  200. WHERE #{query} @@ #{textsearch}
  201. AND accounts.suspended = false
  202. GROUP BY accounts.id
  203. ORDER BY rank DESC
  204. LIMIT ?
  205. SQL
  206. find_by_sql([sql, account.id, account.id, limit])
  207. end
  208. private
  209. def generate_query_for_search(terms)
  210. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  211. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  212. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  213. [textsearch, query]
  214. end
  215. end
  216. before_create :generate_keys
  217. before_validation :normalize_domain
  218. before_validation :prepare_contents, if: :local?
  219. private
  220. def prepare_contents
  221. display_name&.strip!
  222. note&.strip!
  223. self.display_name = emojify(display_name)
  224. self.note = emojify(note)
  225. end
  226. def generate_keys
  227. return unless local?
  228. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 512 : 2048)
  229. self.private_key = keypair.to_pem
  230. self.public_key = keypair.public_key.to_pem
  231. end
  232. def normalize_domain
  233. return if local?
  234. self.domain = TagManager.instance.normalize_domain(domain)
  235. end
  236. end