account.rb 16 KB

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