account.rb 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: accounts
  5. #
  6. # id :bigint(8) not null, primary key
  7. # username :string default(""), not null
  8. # domain :string
  9. # private_key :text
  10. # public_key :text default(""), not null
  11. # created_at :datetime not null
  12. # updated_at :datetime not null
  13. # note :text default(""), not null
  14. # display_name :string default(""), not null
  15. # uri :string default(""), not null
  16. # url :string
  17. # avatar_file_name :string
  18. # avatar_content_type :string
  19. # avatar_file_size :integer
  20. # avatar_updated_at :datetime
  21. # header_file_name :string
  22. # header_content_type :string
  23. # header_file_size :integer
  24. # header_updated_at :datetime
  25. # avatar_remote_url :string
  26. # locked :boolean default(FALSE), not null
  27. # header_remote_url :string default(""), not null
  28. # last_webfingered_at :datetime
  29. # inbox_url :string default(""), not null
  30. # outbox_url :string default(""), not null
  31. # shared_inbox_url :string default(""), not null
  32. # followers_url :string default(""), not null
  33. # protocol :integer default("ostatus"), not null
  34. # memorial :boolean default(FALSE), not null
  35. # moved_to_account_id :bigint(8)
  36. # featured_collection_url :string
  37. # fields :jsonb
  38. # actor_type :string
  39. # discoverable :boolean
  40. # also_known_as :string is an Array
  41. # silenced_at :datetime
  42. # suspended_at :datetime
  43. # hide_collections :boolean
  44. # avatar_storage_schema_version :integer
  45. # header_storage_schema_version :integer
  46. # devices_url :string
  47. # suspension_origin :integer
  48. # sensitized_at :datetime
  49. # trendable :boolean
  50. # reviewed_at :datetime
  51. # requested_review_at :datetime
  52. #
  53. class Account < ApplicationRecord
  54. self.ignored_columns = %w(
  55. subscription_expires_at
  56. secret
  57. remote_url
  58. salmon_url
  59. hub_url
  60. trust_level
  61. )
  62. USERNAME_RE = /[a-z0-9_]+([a-z0-9_.-]+[a-z0-9_]+)?/i
  63. MENTION_RE = %r{(?<![=/[:word:]])@((#{USERNAME_RE})(?:@[[:word:].-]+[[:word:]]+)?)}i
  64. URL_PREFIX_RE = %r{\Ahttp(s?)://[^/]+}
  65. USERNAME_ONLY_RE = /\A#{USERNAME_RE}\z/i
  66. include Attachmentable
  67. include AccountAssociations
  68. include AccountAvatar
  69. include AccountFinderConcern
  70. include AccountHeader
  71. include AccountInteractions
  72. include Paginable
  73. include AccountCounters
  74. include DomainNormalizable
  75. include DomainMaterializable
  76. include AccountMerging
  77. enum protocol: [:ostatus, :activitypub]
  78. enum suspension_origin: [:local, :remote], _prefix: true
  79. validates :username, presence: true
  80. validates_with UniqueUsernameValidator, if: -> { will_save_change_to_username? }
  81. # Remote user validations, also applies to internal actors
  82. validates :username, format: { with: USERNAME_ONLY_RE }, if: -> { (!local? || actor_type == 'Application') && will_save_change_to_username? }
  83. # Local user validations
  84. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, length: { maximum: 30 }, if: -> { local? && will_save_change_to_username? && actor_type != 'Application' }
  85. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? && actor_type != 'Application' }
  86. validates :display_name, length: { maximum: 30 }, if: -> { local? && will_save_change_to_display_name? }
  87. validates :note, note_length: { maximum: 500 }, if: -> { local? && will_save_change_to_note? }
  88. validates :fields, length: { maximum: 4 }, if: -> { local? && will_save_change_to_fields? }
  89. scope :remote, -> { where.not(domain: nil) }
  90. scope :local, -> { where(domain: nil) }
  91. scope :partitioned, -> { order(Arel.sql('row_number() over (partition by domain)')) }
  92. scope :silenced, -> { where.not(silenced_at: nil) }
  93. scope :suspended, -> { where.not(suspended_at: nil) }
  94. scope :sensitized, -> { where.not(sensitized_at: nil) }
  95. scope :without_suspended, -> { where(suspended_at: nil) }
  96. scope :without_silenced, -> { where(silenced_at: nil) }
  97. scope :without_instance_actor, -> { where.not(id: -99) }
  98. scope :recent, -> { reorder(id: :desc) }
  99. scope :bots, -> { where(actor_type: %w(Application Service)) }
  100. scope :groups, -> { where(actor_type: 'Group') }
  101. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  102. scope :matches_username, ->(value) { where('lower((username)::text) LIKE lower(?)', "#{value}%") }
  103. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  104. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  105. scope :without_unapproved, -> { left_outer_joins(:user).remote.or(left_outer_joins(:user).merge(User.approved.confirmed)) }
  106. scope :searchable, -> { without_unapproved.without_suspended.where(moved_to_account_id: nil) }
  107. scope :discoverable, -> { searchable.without_silenced.where(discoverable: true).joins(:account_stat) }
  108. scope :followable_by, ->(account) { joins(arel_table.join(Follow.arel_table, Arel::Nodes::OuterJoin).on(arel_table[:id].eq(Follow.arel_table[:target_account_id]).and(Follow.arel_table[:account_id].eq(account.id))).join_sources).where(Follow.arel_table[:id].eq(nil)).joins(arel_table.join(FollowRequest.arel_table, Arel::Nodes::OuterJoin).on(arel_table[:id].eq(FollowRequest.arel_table[:target_account_id]).and(FollowRequest.arel_table[:account_id].eq(account.id))).join_sources).where(FollowRequest.arel_table[:id].eq(nil)) }
  109. scope :by_recent_status, -> { includes(:account_stat).merge(AccountStat.order('last_status_at DESC NULLS LAST')).references(:account_stat) }
  110. scope :by_recent_sign_in, -> { order(Arel.sql('users.current_sign_in_at DESC NULLS LAST')) }
  111. scope :popular, -> { order('account_stats.followers_count desc') }
  112. scope :by_domain_and_subdomains, ->(domain) { where(domain: domain).or(where(arel_table[:domain].matches("%.#{domain}"))) }
  113. scope :not_excluded_by_account, ->(account) { where.not(id: account.excluded_from_timeline_account_ids) }
  114. scope :not_domain_blocked_by_account, ->(account) { where(arel_table[:domain].eq(nil).or(arel_table[:domain].not_in(account.excluded_from_timeline_domains))) }
  115. delegate :email,
  116. :unconfirmed_email,
  117. :current_sign_in_at,
  118. :created_at,
  119. :sign_up_ip,
  120. :confirmed?,
  121. :approved?,
  122. :pending?,
  123. :disabled?,
  124. :unconfirmed?,
  125. :unconfirmed_or_pending?,
  126. :role,
  127. :locale,
  128. :shows_application?,
  129. :prefers_noindex?,
  130. to: :user,
  131. prefix: true,
  132. allow_nil: true
  133. delegate :chosen_languages, to: :user, prefix: false, allow_nil: true
  134. update_index('accounts', :self)
  135. def local?
  136. domain.nil?
  137. end
  138. def moved?
  139. moved_to_account_id.present?
  140. end
  141. def bot?
  142. %w(Application Service).include? actor_type
  143. end
  144. def instance_actor?
  145. id == -99
  146. end
  147. alias bot bot?
  148. def bot=(val)
  149. self.actor_type = ActiveModel::Type::Boolean.new.cast(val) ? 'Service' : 'Person'
  150. end
  151. def group?
  152. actor_type == 'Group'
  153. end
  154. alias group group?
  155. def acct
  156. local? ? username : "#{username}@#{domain}"
  157. end
  158. def pretty_acct
  159. local? ? username : "#{username}@#{Addressable::IDNA.to_unicode(domain)}"
  160. end
  161. def local_username_and_domain
  162. "#{username}@#{Rails.configuration.x.local_domain}"
  163. end
  164. def local_followers_count
  165. Follow.where(target_account_id: id).count
  166. end
  167. def to_webfinger_s
  168. "acct:#{local_username_and_domain}"
  169. end
  170. def possibly_stale?
  171. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  172. end
  173. def refresh!
  174. ResolveAccountService.new.call(acct) unless local?
  175. end
  176. def silenced?
  177. silenced_at.present?
  178. end
  179. def silence!(date = Time.now.utc)
  180. update!(silenced_at: date)
  181. end
  182. def unsilence!
  183. update!(silenced_at: nil)
  184. end
  185. def suspended?
  186. suspended_at.present? && !instance_actor?
  187. end
  188. def suspended_permanently?
  189. suspended? && deletion_request.nil?
  190. end
  191. def suspended_temporarily?
  192. suspended? && deletion_request.present?
  193. end
  194. def suspend!(date: Time.now.utc, origin: :local, block_email: true)
  195. transaction do
  196. create_deletion_request!
  197. update!(suspended_at: date, suspension_origin: origin)
  198. create_canonical_email_block! if block_email
  199. end
  200. end
  201. def unsuspend!
  202. transaction do
  203. deletion_request&.destroy!
  204. update!(suspended_at: nil, suspension_origin: nil)
  205. destroy_canonical_email_block!
  206. end
  207. end
  208. def sensitized?
  209. sensitized_at.present?
  210. end
  211. def sensitize!(date = Time.now.utc)
  212. update!(sensitized_at: date)
  213. end
  214. def unsensitize!
  215. update!(sensitized_at: nil)
  216. end
  217. def memorialize!
  218. update!(memorial: true)
  219. end
  220. def trendable?
  221. boolean_with_default('trendable', Setting.trendable_by_default)
  222. end
  223. def sign?
  224. true
  225. end
  226. def previous_strikes_count
  227. strikes.where(overruled_at: nil).count
  228. end
  229. def keypair
  230. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  231. end
  232. def tags_as_strings=(tag_names)
  233. hashtags_map = Tag.find_or_create_by_names(tag_names).index_by(&:name)
  234. # Remove hashtags that are to be deleted
  235. tags.each do |tag|
  236. if hashtags_map.key?(tag.name)
  237. hashtags_map.delete(tag.name)
  238. else
  239. tags.delete(tag)
  240. end
  241. end
  242. # Add hashtags that were so far missing
  243. hashtags_map.each_value do |tag|
  244. tags << tag
  245. end
  246. end
  247. def also_known_as
  248. self[:also_known_as] || []
  249. end
  250. def fields
  251. (self[:fields] || []).map do |f|
  252. Account::Field.new(self, f)
  253. rescue
  254. nil
  255. end.compact
  256. end
  257. def fields_attributes=(attributes)
  258. fields = []
  259. old_fields = self[:fields] || []
  260. old_fields = [] if old_fields.is_a?(Hash)
  261. if attributes.is_a?(Hash)
  262. attributes.each_value do |attr|
  263. next if attr[:name].blank?
  264. previous = old_fields.find { |item| item['value'] == attr[:value] }
  265. if previous && previous['verified_at'].present?
  266. attr[:verified_at] = previous['verified_at']
  267. end
  268. fields << attr
  269. end
  270. end
  271. self[:fields] = fields
  272. end
  273. DEFAULT_FIELDS_SIZE = 4
  274. def build_fields
  275. return if fields.size >= DEFAULT_FIELDS_SIZE
  276. tmp = self[:fields] || []
  277. tmp = [] if tmp.is_a?(Hash)
  278. (DEFAULT_FIELDS_SIZE - tmp.size).times do
  279. tmp << { name: '', value: '' }
  280. end
  281. self.fields = tmp
  282. end
  283. def save_with_optional_media!
  284. save!
  285. rescue ActiveRecord::RecordInvalid => e
  286. errors = e.record.errors.errors
  287. errors.each do |err|
  288. if err.attribute == :avatar
  289. self.avatar = nil
  290. elsif err.attribute == :header
  291. self.header = nil
  292. end
  293. end
  294. save!
  295. end
  296. def hides_followers?
  297. hide_collections?
  298. end
  299. def hides_following?
  300. hide_collections?
  301. end
  302. def object_type
  303. :person
  304. end
  305. def to_param
  306. username
  307. end
  308. def to_log_human_identifier
  309. acct
  310. end
  311. def excluded_from_timeline_account_ids
  312. Rails.cache.fetch("exclude_account_ids_for:#{id}") { block_relationships.pluck(:target_account_id) + blocked_by_relationships.pluck(:account_id) + mute_relationships.pluck(:target_account_id) }
  313. end
  314. def excluded_from_timeline_domains
  315. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  316. end
  317. def preferred_inbox_url
  318. shared_inbox_url.presence || inbox_url
  319. end
  320. def synchronization_uri_prefix
  321. return 'local' if local?
  322. @synchronization_uri_prefix ||= "#{uri[URL_PREFIX_RE]}/"
  323. end
  324. def requires_review?
  325. reviewed_at.nil?
  326. end
  327. def reviewed?
  328. reviewed_at.present?
  329. end
  330. def requested_review?
  331. requested_review_at.present?
  332. end
  333. def requires_review_notification?
  334. requires_review? && !requested_review?
  335. end
  336. class << self
  337. DISALLOWED_TSQUERY_CHARACTERS = /['?\\:‘’]/.freeze
  338. TEXTSEARCH = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  339. REPUTATION_SCORE_FUNCTION = '(greatest(0, coalesce(s.followers_count, 0)) / (greatest(0, coalesce(s.following_count, 0)) + 1.0))'
  340. FOLLOWERS_SCORE_FUNCTION = 'log(greatest(0, coalesce(s.followers_count, 0)) + 2)'
  341. TIME_DISTANCE_FUNCTION = '(case when s.last_status_at is null then 0 else exp(-1.0 * ((greatest(0, abs(extract(DAY FROM age(s.last_status_at))) - 30.0)^2) / (2.0 * ((-1.0 * 30^2) / (2.0 * ln(0.3)))))) end)'
  342. BOOST = "((#{REPUTATION_SCORE_FUNCTION} + #{FOLLOWERS_SCORE_FUNCTION} + #{TIME_DISTANCE_FUNCTION}) / 3.0)"
  343. def readonly_attributes
  344. super - %w(statuses_count following_count followers_count)
  345. end
  346. def inboxes
  347. urls = reorder(nil).where(protocol: :activitypub).group(:preferred_inbox_url).pluck(Arel.sql("coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url) AS preferred_inbox_url"))
  348. DeliveryFailureTracker.without_unavailable(urls)
  349. end
  350. def search_for(terms, limit: 10, offset: 0)
  351. tsquery = generate_query_for_search(terms)
  352. sql = <<-SQL.squish
  353. SELECT
  354. accounts.*,
  355. #{BOOST} * ts_rank_cd(#{TEXTSEARCH}, to_tsquery('simple', :tsquery), 32) AS rank
  356. FROM accounts
  357. LEFT JOIN users ON accounts.id = users.account_id
  358. LEFT JOIN account_stats AS s ON accounts.id = s.account_id
  359. WHERE to_tsquery('simple', :tsquery) @@ #{TEXTSEARCH}
  360. AND accounts.suspended_at IS NULL
  361. AND accounts.moved_to_account_id IS NULL
  362. AND (accounts.domain IS NOT NULL OR (users.approved = TRUE AND users.confirmed_at IS NOT NULL))
  363. ORDER BY rank DESC
  364. LIMIT :limit OFFSET :offset
  365. SQL
  366. records = find_by_sql([sql, limit: limit, offset: offset, tsquery: tsquery])
  367. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  368. records
  369. end
  370. def advanced_search_for(terms, account, limit: 10, following: false, offset: 0)
  371. tsquery = generate_query_for_search(terms)
  372. sql = advanced_search_for_sql_template(following)
  373. records = find_by_sql([sql, id: account.id, limit: limit, offset: offset, tsquery: tsquery])
  374. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  375. records
  376. end
  377. def from_text(text)
  378. return [] if text.blank?
  379. text.scan(MENTION_RE).map { |match| match.first.split('@', 2) }.uniq.filter_map do |(username, domain)|
  380. domain = begin
  381. if TagManager.instance.local_domain?(domain)
  382. nil
  383. else
  384. TagManager.instance.normalize_domain(domain)
  385. end
  386. end
  387. EntityCache.instance.mention(username, domain)
  388. end
  389. end
  390. private
  391. def generate_query_for_search(unsanitized_terms)
  392. terms = unsanitized_terms.gsub(DISALLOWED_TSQUERY_CHARACTERS, ' ')
  393. # The final ":*" is for prefix search.
  394. # The trailing space does not seem to fit any purpose, but `to_tsquery`
  395. # behaves differently with and without a leading space if the terms start
  396. # with `./`, `../`, or `.. `. I don't understand why, so, in doubt, keep
  397. # the same query.
  398. "' #{terms} ':*"
  399. end
  400. def advanced_search_for_sql_template(following)
  401. if following
  402. <<-SQL.squish
  403. WITH first_degree AS (
  404. SELECT target_account_id
  405. FROM follows
  406. WHERE account_id = :id
  407. UNION ALL
  408. SELECT :id
  409. )
  410. SELECT
  411. accounts.*,
  412. (count(f.id) + 1) * #{BOOST} * ts_rank_cd(#{TEXTSEARCH}, to_tsquery('simple', :tsquery), 32) AS rank
  413. FROM accounts
  414. LEFT OUTER JOIN follows AS f ON (accounts.id = f.account_id AND f.target_account_id = :id)
  415. LEFT JOIN account_stats AS s ON accounts.id = s.account_id
  416. WHERE accounts.id IN (SELECT * FROM first_degree)
  417. AND to_tsquery('simple', :tsquery) @@ #{TEXTSEARCH}
  418. AND accounts.suspended_at IS NULL
  419. AND accounts.moved_to_account_id IS NULL
  420. GROUP BY accounts.id, s.id
  421. ORDER BY rank DESC
  422. LIMIT :limit OFFSET :offset
  423. SQL
  424. else
  425. <<-SQL.squish
  426. SELECT
  427. accounts.*,
  428. #{BOOST} * ts_rank_cd(#{TEXTSEARCH}, to_tsquery('simple', :tsquery), 32) AS rank,
  429. count(f.id) AS followed
  430. FROM accounts
  431. LEFT OUTER JOIN follows AS f ON (accounts.id = f.account_id AND f.target_account_id = :id) OR (accounts.id = f.target_account_id AND f.account_id = :id)
  432. LEFT JOIN users ON accounts.id = users.account_id
  433. LEFT JOIN account_stats AS s ON accounts.id = s.account_id
  434. WHERE to_tsquery('simple', :tsquery) @@ #{TEXTSEARCH}
  435. AND accounts.suspended_at IS NULL
  436. AND accounts.moved_to_account_id IS NULL
  437. AND (accounts.domain IS NOT NULL OR (users.approved = TRUE AND users.confirmed_at IS NOT NULL))
  438. GROUP BY accounts.id, s.id
  439. ORDER BY followed DESC, rank DESC
  440. LIMIT :limit OFFSET :offset
  441. SQL
  442. end
  443. end
  444. end
  445. def emojis
  446. @emojis ||= CustomEmoji.from_text(emojifiable_text, domain)
  447. end
  448. before_create :generate_keys
  449. before_validation :prepare_contents, if: :local?
  450. before_validation :prepare_username, on: :create
  451. before_destroy :clean_feed_manager
  452. def ensure_keys!
  453. return unless local? && private_key.blank? && public_key.blank?
  454. generate_keys
  455. save!
  456. end
  457. private
  458. def prepare_contents
  459. display_name&.strip!
  460. note&.strip!
  461. end
  462. def prepare_username
  463. username&.squish!
  464. end
  465. def generate_keys
  466. return unless local? && private_key.blank? && public_key.blank?
  467. keypair = OpenSSL::PKey::RSA.new(2048)
  468. self.private_key = keypair.to_pem
  469. self.public_key = keypair.public_key.to_pem
  470. end
  471. def normalize_domain
  472. return if local?
  473. super
  474. end
  475. def emojifiable_text
  476. [note, display_name, fields.map(&:name), fields.map(&:value)].join(' ')
  477. end
  478. def clean_feed_manager
  479. FeedManager.instance.clean_feeds!(:home, [id])
  480. end
  481. def create_canonical_email_block!
  482. return unless local? && user_email.present?
  483. begin
  484. CanonicalEmailBlock.create(reference_account: self, email: user_email)
  485. rescue ActiveRecord::RecordNotUnique
  486. # A canonical e-mail block may already exist for the same e-mail
  487. end
  488. end
  489. def destroy_canonical_email_block!
  490. return unless local?
  491. CanonicalEmailBlock.where(reference_account: self).delete_all
  492. end
  493. end