account.rb 19 KB

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