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.
 
 
 
 

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