account.rb 15 KB

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