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.
 
 
 
 

547 regels
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 subscription(webhook_url)
  263. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  264. end
  265. def save_with_optional_media!
  266. save!
  267. rescue ActiveRecord::RecordInvalid
  268. self.avatar = nil
  269. self.header = nil
  270. save!
  271. end
  272. def object_type
  273. :person
  274. end
  275. def to_param
  276. username
  277. end
  278. def excluded_from_timeline_account_ids
  279. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  280. end
  281. def excluded_from_timeline_domains
  282. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  283. end
  284. def preferred_inbox_url
  285. shared_inbox_url.presence || inbox_url
  286. end
  287. class Field < ActiveModelSerializers::Model
  288. attributes :name, :value, :verified_at, :account, :errors
  289. def initialize(account, attributes)
  290. @account = account
  291. @attributes = attributes
  292. @name = attributes['name'].strip[0, string_limit]
  293. @value = attributes['value'].strip[0, string_limit]
  294. @verified_at = attributes['verified_at']&.to_datetime
  295. @errors = {}
  296. end
  297. def verified?
  298. verified_at.present?
  299. end
  300. def value_for_verification
  301. @value_for_verification ||= begin
  302. if account.local?
  303. value
  304. else
  305. ActionController::Base.helpers.strip_tags(value)
  306. end
  307. end
  308. end
  309. def verifiable?
  310. value_for_verification.present? && value_for_verification.start_with?('http://', 'https://')
  311. end
  312. def mark_verified!
  313. @verified_at = Time.now.utc
  314. @attributes['verified_at'] = @verified_at
  315. end
  316. def to_h
  317. { name: @name, value: @value, verified_at: @verified_at }
  318. end
  319. private
  320. def string_limit
  321. if account.local?
  322. 255
  323. else
  324. 2047
  325. end
  326. end
  327. end
  328. class << self
  329. def readonly_attributes
  330. super - %w(statuses_count following_count followers_count)
  331. end
  332. def domains
  333. reorder(nil).pluck(Arel.sql('distinct accounts.domain'))
  334. end
  335. def inboxes
  336. urls = reorder(nil).where(protocol: :activitypub).pluck(Arel.sql("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)"))
  337. DeliveryFailureTracker.filter(urls)
  338. end
  339. def search_for(terms, limit = 10, offset = 0)
  340. textsearch, query = generate_query_for_search(terms)
  341. sql = <<-SQL.squish
  342. SELECT
  343. accounts.*,
  344. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  345. FROM accounts
  346. WHERE #{query} @@ #{textsearch}
  347. AND accounts.suspended_at IS NULL
  348. AND accounts.moved_to_account_id IS NULL
  349. ORDER BY rank DESC
  350. LIMIT ? OFFSET ?
  351. SQL
  352. records = find_by_sql([sql, limit, offset])
  353. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  354. records
  355. end
  356. def advanced_search_for(terms, account, limit = 10, following = false, offset = 0)
  357. textsearch, query = generate_query_for_search(terms)
  358. if following
  359. sql = <<-SQL.squish
  360. WITH first_degree AS (
  361. SELECT target_account_id
  362. FROM follows
  363. WHERE account_id = ?
  364. UNION ALL
  365. SELECT ?
  366. )
  367. SELECT
  368. accounts.*,
  369. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  370. FROM accounts
  371. LEFT OUTER JOIN follows AS f ON (accounts.id = f.account_id AND f.target_account_id = ?)
  372. WHERE accounts.id IN (SELECT * FROM first_degree)
  373. AND #{query} @@ #{textsearch}
  374. AND accounts.suspended_at IS NULL
  375. AND accounts.moved_to_account_id IS NULL
  376. GROUP BY accounts.id
  377. ORDER BY rank DESC
  378. LIMIT ? OFFSET ?
  379. SQL
  380. records = find_by_sql([sql, account.id, account.id, account.id, limit, offset])
  381. else
  382. sql = <<-SQL.squish
  383. SELECT
  384. accounts.*,
  385. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  386. FROM accounts
  387. 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 = ?)
  388. WHERE #{query} @@ #{textsearch}
  389. AND accounts.suspended_at IS NULL
  390. AND accounts.moved_to_account_id IS NULL
  391. GROUP BY accounts.id
  392. ORDER BY rank DESC
  393. LIMIT ? OFFSET ?
  394. SQL
  395. records = find_by_sql([sql, account.id, account.id, limit, offset])
  396. end
  397. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  398. records
  399. end
  400. private
  401. def generate_query_for_search(terms)
  402. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  403. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  404. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  405. [textsearch, query]
  406. end
  407. end
  408. def emojis
  409. @emojis ||= CustomEmoji.from_text(emojifiable_text, domain)
  410. end
  411. before_create :generate_keys
  412. before_validation :prepare_contents, if: :local?
  413. before_validation :prepare_username, on: :create
  414. before_destroy :clean_feed_manager
  415. private
  416. def prepare_contents
  417. display_name&.strip!
  418. note&.strip!
  419. end
  420. def prepare_username
  421. username&.squish!
  422. end
  423. def generate_keys
  424. return unless local? && private_key.blank? && public_key.blank?
  425. keypair = OpenSSL::PKey::RSA.new(2048)
  426. self.private_key = keypair.to_pem
  427. self.public_key = keypair.public_key.to_pem
  428. end
  429. def normalize_domain
  430. return if local?
  431. super
  432. end
  433. def emojifiable_text
  434. [note, display_name, fields.map(&:name), fields.map(&:value)].join(' ')
  435. end
  436. def clean_feed_manager
  437. reblog_key = FeedManager.instance.key(:home, id, 'reblogs')
  438. reblogged_id_set = Redis.current.zrange(reblog_key, 0, -1)
  439. Redis.current.pipelined do
  440. Redis.current.del(FeedManager.instance.key(:home, id))
  441. Redis.current.del(reblog_key)
  442. reblogged_id_set.each do |reblogged_id|
  443. reblog_set_key = FeedManager.instance.key(:home, id, "reblogs:#{reblogged_id}")
  444. Redis.current.del(reblog_set_key)
  445. end
  446. end
  447. end
  448. end