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.
 
 
 
 

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