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.
 
 
 
 

480 lines
14 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. #
  47. class Account < ApplicationRecord
  48. USERNAME_RE = /[a-z0-9_]+([a-z0-9_\.]+[a-z0-9_]+)?/i
  49. MENTION_RE = /(?<=^|[^\/[:word:]])@((#{USERNAME_RE})(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  50. include AccountAvatar
  51. include AccountFinderConcern
  52. include AccountHeader
  53. include AccountInteractions
  54. include Attachmentable
  55. include Paginable
  56. include AccountCounters
  57. enum protocol: [:ostatus, :activitypub]
  58. # Local users
  59. has_one :user, inverse_of: :account
  60. validates :username, presence: true
  61. # Remote user validations
  62. validates :username, uniqueness: { scope: :domain, case_sensitive: true }, if: -> { !local? && will_save_change_to_username? }
  63. validates :username, format: { with: /\A#{USERNAME_RE}\z/i }, if: -> { !local? && will_save_change_to_username? }
  64. # Local user validations
  65. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, length: { maximum: 30 }, if: -> { local? && will_save_change_to_username? }
  66. validates_with UniqueUsernameValidator, if: -> { local? && will_save_change_to_username? }
  67. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? }
  68. validates :display_name, length: { maximum: 30 }, if: -> { local? && will_save_change_to_display_name? }
  69. validates :note, length: { maximum: 160 }, if: -> { local? && will_save_change_to_note? }
  70. validates :fields, length: { maximum: 4 }, if: -> { local? && will_save_change_to_fields? }
  71. # Timelines
  72. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  73. has_many :statuses, inverse_of: :account, dependent: :destroy
  74. has_many :favourites, inverse_of: :account, dependent: :destroy
  75. has_many :mentions, inverse_of: :account, dependent: :destroy
  76. has_many :notifications, inverse_of: :account, dependent: :destroy
  77. # Pinned statuses
  78. has_many :status_pins, inverse_of: :account, dependent: :destroy
  79. has_many :pinned_statuses, -> { reorder('status_pins.created_at DESC') }, through: :status_pins, class_name: 'Status', source: :status
  80. # Endorsements
  81. has_many :account_pins, inverse_of: :account, dependent: :destroy
  82. has_many :endorsed_accounts, through: :account_pins, class_name: 'Account', source: :target_account
  83. # Media
  84. has_many :media_attachments, dependent: :destroy
  85. # PuSH subscriptions
  86. has_many :subscriptions, dependent: :destroy
  87. # Report relationships
  88. has_many :reports
  89. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  90. has_many :report_notes, dependent: :destroy
  91. has_many :custom_filters, inverse_of: :account, dependent: :destroy
  92. # Moderation notes
  93. has_many :account_moderation_notes, dependent: :destroy
  94. has_many :targeted_moderation_notes, class_name: 'AccountModerationNote', foreign_key: :target_account_id, dependent: :destroy
  95. # Lists
  96. has_many :list_accounts, inverse_of: :account, dependent: :destroy
  97. has_many :lists, through: :list_accounts
  98. # Account migrations
  99. belongs_to :moved_to_account, class_name: 'Account', optional: true
  100. scope :remote, -> { where.not(domain: nil) }
  101. scope :local, -> { where(domain: nil) }
  102. scope :expiring, ->(time) { remote.where.not(subscription_expires_at: nil).where('subscription_expires_at < ?', time) }
  103. scope :partitioned, -> { order(Arel.sql('row_number() over (partition by domain)')) }
  104. scope :silenced, -> { where(silenced: true) }
  105. scope :suspended, -> { where(suspended: true) }
  106. scope :without_suspended, -> { where(suspended: false) }
  107. scope :recent, -> { reorder(id: :desc) }
  108. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  109. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  110. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  111. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  112. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  113. scope :searchable, -> { where(suspended: false).where(moved_to_account_id: nil) }
  114. delegate :email,
  115. :unconfirmed_email,
  116. :current_sign_in_ip,
  117. :current_sign_in_at,
  118. :confirmed?,
  119. :admin?,
  120. :moderator?,
  121. :staff?,
  122. :locale,
  123. :hides_network?,
  124. to: :user,
  125. prefix: true,
  126. allow_nil: true
  127. delegate :chosen_languages, to: :user, prefix: false, allow_nil: true
  128. def local?
  129. domain.nil?
  130. end
  131. def moved?
  132. moved_to_account_id.present?
  133. end
  134. def bot?
  135. %w(Application Service).include? actor_type
  136. end
  137. alias bot bot?
  138. def bot=(val)
  139. self.actor_type = ActiveModel::Type::Boolean.new.cast(val) ? 'Service' : 'Person'
  140. end
  141. def acct
  142. local? ? username : "#{username}@#{domain}"
  143. end
  144. def local_username_and_domain
  145. "#{username}@#{Rails.configuration.x.local_domain}"
  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 possibly_stale?
  154. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  155. end
  156. def refresh!
  157. return if local?
  158. ResolveAccountService.new.call(acct)
  159. end
  160. def suspend!
  161. transaction do
  162. user&.disable! if local?
  163. update!(suspended: true)
  164. end
  165. end
  166. def unsuspend!
  167. transaction do
  168. user&.enable! if local?
  169. update!(suspended: false)
  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 fields
  182. (self[:fields] || []).map { |f| Field.new(self, f) }
  183. end
  184. def fields_attributes=(attributes)
  185. fields = []
  186. old_fields = self[:fields] || []
  187. if attributes.is_a?(Hash)
  188. attributes.each_value do |attr|
  189. next if attr[:name].blank?
  190. previous = old_fields.find { |item| item['value'] == attr[:value] }
  191. if previous && previous['verified_at'].present?
  192. attr[:verified_at] = previous['verified_at']
  193. end
  194. fields << attr
  195. end
  196. end
  197. self[:fields] = fields
  198. end
  199. DEFAULT_FIELDS_SIZE = 4
  200. def build_fields
  201. return if fields.size >= DEFAULT_FIELDS_SIZE
  202. tmp = self[:fields] || []
  203. (DEFAULT_FIELDS_SIZE - tmp.size).times do
  204. tmp << { name: '', value: '' }
  205. end
  206. self.fields = tmp
  207. end
  208. def magic_key
  209. modulus, exponent = [keypair.public_key.n, keypair.public_key.e].map do |component|
  210. result = []
  211. until component.zero?
  212. result << [component % 256].pack('C')
  213. component >>= 8
  214. end
  215. result.reverse.join
  216. end
  217. (['RSA'] + [modulus, exponent].map { |n| Base64.urlsafe_encode64(n) }).join('.')
  218. end
  219. def subscription(webhook_url)
  220. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  221. end
  222. def save_with_optional_media!
  223. save!
  224. rescue ActiveRecord::RecordInvalid
  225. self.avatar = nil
  226. self.header = nil
  227. self[:avatar_remote_url] = ''
  228. self[:header_remote_url] = ''
  229. save!
  230. end
  231. def object_type
  232. :person
  233. end
  234. def to_param
  235. username
  236. end
  237. def excluded_from_timeline_account_ids
  238. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  239. end
  240. def excluded_from_timeline_domains
  241. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  242. end
  243. def preferred_inbox_url
  244. shared_inbox_url.presence || inbox_url
  245. end
  246. class Field < ActiveModelSerializers::Model
  247. attributes :name, :value, :verified_at, :account, :errors
  248. def initialize(account, attributes)
  249. @account = account
  250. @attributes = attributes
  251. @name = attributes['name'].strip[0, string_limit]
  252. @value = attributes['value'].strip[0, string_limit]
  253. @verified_at = attributes['verified_at']&.to_datetime
  254. @errors = {}
  255. end
  256. def verified?
  257. verified_at.present?
  258. end
  259. def value_for_verification
  260. @value_for_verification ||= begin
  261. if account.local?
  262. value
  263. else
  264. ActionController::Base.helpers.strip_tags(value)
  265. end
  266. end
  267. end
  268. def verifiable?
  269. value_for_verification.present? && value_for_verification.start_with?('http://', 'https://')
  270. end
  271. def mark_verified!
  272. @verified_at = Time.now.utc
  273. @attributes['verified_at'] = @verified_at
  274. end
  275. def to_h
  276. { name: @name, value: @value, verified_at: @verified_at }
  277. end
  278. private
  279. def string_limit
  280. if account.local?
  281. 255
  282. else
  283. 2047
  284. end
  285. end
  286. end
  287. class << self
  288. def readonly_attributes
  289. super - %w(statuses_count following_count followers_count)
  290. end
  291. def domains
  292. reorder(nil).pluck(Arel.sql('distinct accounts.domain'))
  293. end
  294. def inboxes
  295. urls = reorder(nil).where(protocol: :activitypub).pluck(Arel.sql("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)"))
  296. DeliveryFailureTracker.filter(urls)
  297. end
  298. def search_for(terms, limit = 10)
  299. textsearch, query = generate_query_for_search(terms)
  300. sql = <<-SQL.squish
  301. SELECT
  302. accounts.*,
  303. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  304. FROM accounts
  305. WHERE #{query} @@ #{textsearch}
  306. AND accounts.suspended = false
  307. AND accounts.moved_to_account_id IS NULL
  308. ORDER BY rank DESC
  309. LIMIT ?
  310. SQL
  311. records = find_by_sql([sql, limit])
  312. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  313. records
  314. end
  315. def advanced_search_for(terms, account, limit = 10, following = false)
  316. textsearch, query = generate_query_for_search(terms)
  317. if following
  318. sql = <<-SQL.squish
  319. WITH first_degree AS (
  320. SELECT target_account_id
  321. FROM follows
  322. WHERE account_id = ?
  323. )
  324. SELECT
  325. accounts.*,
  326. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  327. FROM accounts
  328. 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 = ?)
  329. WHERE accounts.id IN (SELECT * FROM first_degree)
  330. AND #{query} @@ #{textsearch}
  331. AND accounts.suspended = false
  332. AND accounts.moved_to_account_id IS NULL
  333. GROUP BY accounts.id
  334. ORDER BY rank DESC
  335. LIMIT ?
  336. SQL
  337. records = find_by_sql([sql, account.id, account.id, account.id, limit])
  338. else
  339. sql = <<-SQL.squish
  340. SELECT
  341. accounts.*,
  342. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  343. FROM accounts
  344. 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 = ?)
  345. WHERE #{query} @@ #{textsearch}
  346. AND accounts.suspended = false
  347. AND accounts.moved_to_account_id IS NULL
  348. GROUP BY accounts.id
  349. ORDER BY rank DESC
  350. LIMIT ?
  351. SQL
  352. records = find_by_sql([sql, account.id, account.id, limit])
  353. end
  354. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  355. records
  356. end
  357. private
  358. def generate_query_for_search(terms)
  359. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  360. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  361. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  362. [textsearch, query]
  363. end
  364. end
  365. def emojis
  366. @emojis ||= CustomEmoji.from_text(emojifiable_text, domain)
  367. end
  368. before_create :generate_keys
  369. before_validation :normalize_domain
  370. before_validation :prepare_contents, if: :local?
  371. private
  372. def prepare_contents
  373. display_name&.strip!
  374. note&.strip!
  375. end
  376. def generate_keys
  377. return unless local? && !Rails.env.test?
  378. keypair = OpenSSL::PKey::RSA.new(2048)
  379. self.private_key = keypair.to_pem
  380. self.public_key = keypair.public_key.to_pem
  381. end
  382. def normalize_domain
  383. return if local?
  384. self.domain = TagManager.instance.normalize_domain(domain)
  385. end
  386. def emojifiable_text
  387. [note, display_name, fields.map(&:value)].join(' ')
  388. end
  389. end