The code powering m.abunchtell.com https://m.abunchtell.com
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

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