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.
 
 
 
 

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