The code powering m.abunchtell.com https://m.abunchtell.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

549 lines
16 KiB

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