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.
 
 
 
 

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