account.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. # 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. # locked :boolean default(FALSE), not null
  32. # header_remote_url :string default(""), not null
  33. # last_webfingered_at :datetime
  34. # inbox_url :string default(""), not null
  35. # outbox_url :string default(""), not null
  36. # shared_inbox_url :string default(""), not null
  37. # followers_url :string default(""), not null
  38. # protocol :integer default("ostatus"), not null
  39. # memorial :boolean default(FALSE), not null
  40. # moved_to_account_id :bigint(8)
  41. # featured_collection_url :string
  42. # fields :jsonb
  43. # actor_type :string
  44. # discoverable :boolean
  45. # also_known_as :string is an Array
  46. # silenced_at :datetime
  47. # suspended_at :datetime
  48. # trust_level :integer
  49. #
  50. class Account < ApplicationRecord
  51. USERNAME_RE = /[a-z0-9_]+([a-z0-9_\.-]+[a-z0-9_]+)?/i
  52. MENTION_RE = /(?<=^|[^\/[:word:]])@((#{USERNAME_RE})(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  53. MIN_FOLLOWERS_DISCOVERY = 10
  54. include AccountAssociations
  55. include AccountAvatar
  56. include AccountFinderConcern
  57. include AccountHeader
  58. include AccountInteractions
  59. include Attachmentable
  60. include Paginable
  61. include AccountCounters
  62. include DomainNormalizable
  63. TRUST_LEVELS = {
  64. untrusted: 0,
  65. trusted: 1,
  66. }.freeze
  67. enum protocol: [:ostatus, :activitypub]
  68. validates :username, presence: true
  69. # Remote user validations
  70. validates :username, uniqueness: { scope: :domain, case_sensitive: true }, if: -> { !local? && will_save_change_to_username? }
  71. validates :username, format: { with: /\A#{USERNAME_RE}\z/i }, if: -> { !local? && will_save_change_to_username? }
  72. # Local user validations
  73. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, length: { maximum: 30 }, if: -> { local? && will_save_change_to_username? && actor_type != 'Application' }
  74. validates_with UniqueUsernameValidator, if: -> { local? && will_save_change_to_username? }
  75. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? }
  76. validates :display_name, length: { maximum: 30 }, if: -> { local? && will_save_change_to_display_name? }
  77. validates :note, note_length: { maximum: 500 }, if: -> { local? && will_save_change_to_note? }
  78. validates :fields, length: { maximum: 4 }, if: -> { local? && will_save_change_to_fields? }
  79. scope :remote, -> { where.not(domain: nil) }
  80. scope :local, -> { where(domain: nil) }
  81. scope :expiring, ->(time) { remote.where.not(subscription_expires_at: nil).where('subscription_expires_at < ?', time) }
  82. scope :partitioned, -> { order(Arel.sql('row_number() over (partition by domain)')) }
  83. scope :silenced, -> { where.not(silenced_at: nil) }
  84. scope :suspended, -> { where.not(suspended_at: nil) }
  85. scope :without_suspended, -> { where(suspended_at: nil) }
  86. scope :without_silenced, -> { where(silenced_at: nil) }
  87. scope :recent, -> { reorder(id: :desc) }
  88. scope :bots, -> { where(actor_type: %w(Application Service)) }
  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. scope :searchable, -> { without_suspended.where(moved_to_account_id: nil) }
  95. scope :discoverable, -> { searchable.without_silenced.where(discoverable: true).joins(:account_stat).where(AccountStat.arel_table[:followers_count].gteq(MIN_FOLLOWERS_DISCOVERY)) }
  96. scope :tagged_with, ->(tag) { joins(:accounts_tags).where(accounts_tags: { tag_id: tag }) }
  97. 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')) }
  98. scope :popular, -> { order('account_stats.followers_count desc') }
  99. scope :by_domain_and_subdomains, ->(domain) { where(domain: domain).or(where(arel_table[:domain].matches('%.' + domain))) }
  100. delegate :email,
  101. :unconfirmed_email,
  102. :current_sign_in_ip,
  103. :current_sign_in_at,
  104. :confirmed?,
  105. :approved?,
  106. :pending?,
  107. :disabled?,
  108. :role,
  109. :admin?,
  110. :moderator?,
  111. :staff?,
  112. :locale,
  113. :hides_network?,
  114. :shows_application?,
  115. to: :user,
  116. prefix: true,
  117. allow_nil: true
  118. delegate :chosen_languages, to: :user, prefix: false, allow_nil: true
  119. def local?
  120. domain.nil?
  121. end
  122. def moved?
  123. moved_to_account_id.present?
  124. end
  125. def bot?
  126. %w(Application Service).include? actor_type
  127. end
  128. def instance_actor?
  129. id == -99
  130. end
  131. alias bot bot?
  132. def bot=(val)
  133. self.actor_type = ActiveModel::Type::Boolean.new.cast(val) ? 'Service' : 'Person'
  134. end
  135. def acct
  136. local? ? username : "#{username}@#{domain}"
  137. end
  138. def local_username_and_domain
  139. "#{username}@#{Rails.configuration.x.local_domain}"
  140. end
  141. def local_followers_count
  142. Follow.where(target_account_id: id).count
  143. end
  144. def to_webfinger_s
  145. "acct:#{local_username_and_domain}"
  146. end
  147. def subscribed?
  148. subscription_expires_at.present?
  149. end
  150. def possibly_stale?
  151. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  152. end
  153. def trust_level
  154. self[:trust_level] || 0
  155. end
  156. def refresh!
  157. ResolveAccountService.new.call(acct) unless local?
  158. end
  159. def silenced?
  160. silenced_at.present?
  161. end
  162. def silence!(date = Time.now.utc)
  163. update!(silenced_at: date)
  164. end
  165. def unsilence!
  166. update!(silenced_at: nil, trust_level: trust_level == TRUST_LEVELS[:untrusted] ? TRUST_LEVELS[:trusted] : trust_level)
  167. end
  168. def suspended?
  169. suspended_at.present?
  170. end
  171. def suspend!(date = Time.now.utc)
  172. transaction do
  173. user&.disable! if local?
  174. update!(suspended_at: date)
  175. end
  176. end
  177. def unsuspend!
  178. transaction do
  179. user&.enable! if local?
  180. update!(suspended_at: nil)
  181. end
  182. end
  183. def memorialize!
  184. transaction do
  185. user&.disable! if local?
  186. update!(memorial: true)
  187. end
  188. end
  189. def sign?
  190. true
  191. end
  192. def keypair
  193. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  194. end
  195. def tags_as_strings=(tag_names)
  196. tag_names.map! { |name| name.mb_chars.downcase.to_s }
  197. tag_names.uniq!
  198. # Existing hashtags
  199. hashtags_map = Tag.where(name: tag_names).each_with_object({}) { |tag, h| h[tag.name] = tag }
  200. # Initialize not yet existing hashtags
  201. tag_names.each do |name|
  202. next if hashtags_map.key?(name)
  203. hashtags_map[name] = Tag.new(name: name)
  204. end
  205. # Remove hashtags that are to be deleted
  206. tags.each do |tag|
  207. if hashtags_map.key?(tag.name)
  208. hashtags_map.delete(tag.name)
  209. else
  210. transaction do
  211. tags.delete(tag)
  212. tag.decrement_count!(:accounts_count)
  213. end
  214. end
  215. end
  216. # Add hashtags that were so far missing
  217. hashtags_map.each_value do |tag|
  218. transaction do
  219. tags << tag
  220. tag.increment_count!(:accounts_count)
  221. end
  222. end
  223. end
  224. def also_known_as
  225. self[:also_known_as] || []
  226. end
  227. def fields
  228. (self[:fields] || []).map { |f| Field.new(self, f) }
  229. end
  230. def fields_attributes=(attributes)
  231. fields = []
  232. old_fields = self[:fields] || []
  233. old_fields = [] if old_fields.is_a?(Hash)
  234. if attributes.is_a?(Hash)
  235. attributes.each_value do |attr|
  236. next if attr[:name].blank?
  237. previous = old_fields.find { |item| item['value'] == attr[:value] }
  238. if previous && previous['verified_at'].present?
  239. attr[:verified_at] = previous['verified_at']
  240. end
  241. fields << attr
  242. end
  243. end
  244. self[:fields] = fields
  245. end
  246. DEFAULT_FIELDS_SIZE = 4
  247. def build_fields
  248. return if fields.size >= DEFAULT_FIELDS_SIZE
  249. tmp = self[:fields] || []
  250. tmp = [] if tmp.is_a?(Hash)
  251. (DEFAULT_FIELDS_SIZE - tmp.size).times do
  252. tmp << { name: '', value: '' }
  253. end
  254. self.fields = tmp
  255. end
  256. def subscription(webhook_url)
  257. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  258. end
  259. def save_with_optional_media!
  260. save!
  261. rescue ActiveRecord::RecordInvalid
  262. self.avatar = nil
  263. self.header = nil
  264. self[:avatar_remote_url] = ''
  265. self[:header_remote_url] = ''
  266. save!
  267. end
  268. def object_type
  269. :person
  270. end
  271. def to_param
  272. username
  273. end
  274. def excluded_from_timeline_account_ids
  275. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  276. end
  277. def excluded_from_timeline_domains
  278. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  279. end
  280. def preferred_inbox_url
  281. shared_inbox_url.presence || inbox_url
  282. end
  283. class Field < ActiveModelSerializers::Model
  284. attributes :name, :value, :verified_at, :account, :errors
  285. def initialize(account, attributes)
  286. @account = account
  287. @attributes = attributes
  288. @name = attributes['name'].strip[0, string_limit]
  289. @value = attributes['value'].strip[0, string_limit]
  290. @verified_at = attributes['verified_at']&.to_datetime
  291. @errors = {}
  292. end
  293. def verified?
  294. verified_at.present?
  295. end
  296. def value_for_verification
  297. @value_for_verification ||= begin
  298. if account.local?
  299. value
  300. else
  301. ActionController::Base.helpers.strip_tags(value)
  302. end
  303. end
  304. end
  305. def verifiable?
  306. value_for_verification.present? && value_for_verification.start_with?('http://', 'https://')
  307. end
  308. def mark_verified!
  309. @verified_at = Time.now.utc
  310. @attributes['verified_at'] = @verified_at
  311. end
  312. def to_h
  313. { name: @name, value: @value, verified_at: @verified_at }
  314. end
  315. private
  316. def string_limit
  317. if account.local?
  318. 255
  319. else
  320. 2047
  321. end
  322. end
  323. end
  324. class << self
  325. def readonly_attributes
  326. super - %w(statuses_count following_count followers_count)
  327. end
  328. def domains
  329. reorder(nil).pluck(Arel.sql('distinct accounts.domain'))
  330. end
  331. def inboxes
  332. urls = reorder(nil).where(protocol: :activitypub).pluck(Arel.sql("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)"))
  333. DeliveryFailureTracker.filter(urls)
  334. end
  335. def search_for(terms, limit = 10, offset = 0)
  336. textsearch, query = generate_query_for_search(terms)
  337. sql = <<-SQL.squish
  338. SELECT
  339. accounts.*,
  340. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  341. FROM accounts
  342. WHERE #{query} @@ #{textsearch}
  343. AND accounts.suspended_at IS NULL
  344. AND accounts.moved_to_account_id IS NULL
  345. ORDER BY rank DESC
  346. LIMIT ? OFFSET ?
  347. SQL
  348. records = find_by_sql([sql, limit, offset])
  349. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  350. records
  351. end
  352. def advanced_search_for(terms, account, limit = 10, following = false, offset = 0)
  353. textsearch, query = generate_query_for_search(terms)
  354. if following
  355. sql = <<-SQL.squish
  356. WITH first_degree AS (
  357. SELECT target_account_id
  358. FROM follows
  359. WHERE account_id = ?
  360. )
  361. SELECT
  362. accounts.*,
  363. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  364. FROM accounts
  365. 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 = ?)
  366. WHERE accounts.id IN (SELECT * FROM first_degree)
  367. AND #{query} @@ #{textsearch}
  368. AND accounts.suspended_at IS NULL
  369. AND accounts.moved_to_account_id IS NULL
  370. GROUP BY accounts.id
  371. ORDER BY rank DESC
  372. LIMIT ? OFFSET ?
  373. SQL
  374. records = find_by_sql([sql, account.id, account.id, account.id, limit, offset])
  375. else
  376. sql = <<-SQL.squish
  377. SELECT
  378. accounts.*,
  379. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  380. FROM accounts
  381. 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 = ?)
  382. WHERE #{query} @@ #{textsearch}
  383. AND accounts.suspended_at IS NULL
  384. AND accounts.moved_to_account_id IS NULL
  385. GROUP BY accounts.id
  386. ORDER BY rank DESC
  387. LIMIT ? OFFSET ?
  388. SQL
  389. records = find_by_sql([sql, account.id, account.id, limit, offset])
  390. end
  391. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  392. records
  393. end
  394. private
  395. def generate_query_for_search(terms)
  396. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  397. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  398. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  399. [textsearch, query]
  400. end
  401. end
  402. def emojis
  403. @emojis ||= CustomEmoji.from_text(emojifiable_text, domain)
  404. end
  405. before_create :generate_keys
  406. before_validation :prepare_contents, if: :local?
  407. before_validation :prepare_username, on: :create
  408. before_destroy :clean_feed_manager
  409. private
  410. def prepare_contents
  411. display_name&.strip!
  412. note&.strip!
  413. end
  414. def prepare_username
  415. username&.squish!
  416. end
  417. def generate_keys
  418. return unless local? && private_key.blank? && public_key.blank?
  419. keypair = OpenSSL::PKey::RSA.new(2048)
  420. self.private_key = keypair.to_pem
  421. self.public_key = keypair.public_key.to_pem
  422. end
  423. def normalize_domain
  424. return if local?
  425. super
  426. end
  427. def emojifiable_text
  428. [note, display_name, fields.map(&:value)].join(' ')
  429. end
  430. def clean_feed_manager
  431. reblog_key = FeedManager.instance.key(:home, id, 'reblogs')
  432. reblogged_id_set = Redis.current.zrange(reblog_key, 0, -1)
  433. Redis.current.pipelined do
  434. Redis.current.del(FeedManager.instance.key(:home, id))
  435. Redis.current.del(reblog_key)
  436. reblogged_id_set.each do |reblogged_id|
  437. reblog_set_key = FeedManager.instance.key(:home, id, "reblogs:#{reblogged_id}")
  438. Redis.current.del(reblog_set_key)
  439. end
  440. end
  441. end
  442. end