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.
 
 
 
 

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