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.
 
 
 
 

323 lines
11 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: accounts
  5. #
  6. # id :integer 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. #
  46. class Account < ApplicationRecord
  47. MENTION_RE = /(?<=^|[^\/[:word:]])@(([a-z0-9_]+)(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  48. include AccountAvatar
  49. include AccountFinderConcern
  50. include AccountHeader
  51. include AccountInteractions
  52. include Attachmentable
  53. include Remotable
  54. include Paginable
  55. enum protocol: [:ostatus, :activitypub]
  56. # Local users
  57. has_one :user, inverse_of: :account
  58. validates :username, presence: true
  59. # Remote user validations
  60. validates :username, uniqueness: { scope: :domain, case_sensitive: true }, if: -> { !local? && will_save_change_to_username? }
  61. # Local user validations
  62. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, uniqueness: { scope: :domain, case_sensitive: false }, length: { maximum: 30 }, if: -> { local? && will_save_change_to_username? }
  63. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? }
  64. validates :display_name, length: { maximum: 30 }, if: -> { local? && will_save_change_to_display_name? }
  65. validates :note, length: { maximum: 160 }, if: -> { local? && will_save_change_to_note? }
  66. # Timelines
  67. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  68. has_many :statuses, inverse_of: :account, dependent: :destroy
  69. has_many :favourites, inverse_of: :account, dependent: :destroy
  70. has_many :mentions, inverse_of: :account, dependent: :destroy
  71. has_many :notifications, inverse_of: :account, dependent: :destroy
  72. # Pinned statuses
  73. has_many :status_pins, inverse_of: :account, dependent: :destroy
  74. has_many :pinned_statuses, -> { reorder('status_pins.created_at DESC') }, through: :status_pins, class_name: 'Status', source: :status
  75. # Media
  76. has_many :media_attachments, dependent: :destroy
  77. # PuSH subscriptions
  78. has_many :subscriptions, dependent: :destroy
  79. # Report relationships
  80. has_many :reports
  81. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  82. # Moderation notes
  83. has_many :account_moderation_notes, dependent: :destroy
  84. has_many :targeted_moderation_notes, class_name: 'AccountModerationNote', foreign_key: :target_account_id, dependent: :destroy
  85. # Lists
  86. has_many :list_accounts, inverse_of: :account, dependent: :destroy
  87. has_many :lists, through: :list_accounts
  88. scope :remote, -> { where.not(domain: nil) }
  89. scope :local, -> { where(domain: nil) }
  90. scope :without_followers, -> { where(followers_count: 0) }
  91. scope :with_followers, -> { where('followers_count > 0') }
  92. scope :expiring, ->(time) { remote.where.not(subscription_expires_at: nil).where('subscription_expires_at < ?', time) }
  93. scope :partitioned, -> { order('row_number() over (partition by domain)') }
  94. scope :silenced, -> { where(silenced: true) }
  95. scope :suspended, -> { where(suspended: true) }
  96. scope :recent, -> { reorder(id: :desc) }
  97. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  98. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  99. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  100. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  101. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  102. delegate :email,
  103. :current_sign_in_ip,
  104. :current_sign_in_at,
  105. :confirmed?,
  106. :admin?,
  107. :moderator?,
  108. :staff?,
  109. :locale,
  110. to: :user,
  111. prefix: true,
  112. allow_nil: true
  113. delegate :filtered_languages, to: :user, prefix: false, allow_nil: true
  114. def local?
  115. domain.nil?
  116. end
  117. def acct
  118. local? ? username : "#{username}@#{domain}"
  119. end
  120. def local_username_and_domain
  121. "#{username}@#{Rails.configuration.x.local_domain}"
  122. end
  123. def to_webfinger_s
  124. "acct:#{local_username_and_domain}"
  125. end
  126. def subscribed?
  127. subscription_expires_at.present?
  128. end
  129. def possibly_stale?
  130. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  131. end
  132. def refresh!
  133. return if local?
  134. ResolveRemoteAccountService.new.call(acct)
  135. end
  136. def unsuspend!
  137. transaction do
  138. user&.enable! if local?
  139. update!(suspended: false)
  140. end
  141. end
  142. def memorialize!
  143. transaction do
  144. user&.disable! if local?
  145. update!(memorial: true)
  146. end
  147. end
  148. def keypair
  149. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  150. end
  151. def subscription(webhook_url)
  152. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  153. end
  154. def save_with_optional_media!
  155. save!
  156. rescue ActiveRecord::RecordInvalid
  157. self.avatar = nil
  158. self.header = nil
  159. self[:avatar_remote_url] = ''
  160. self[:header_remote_url] = ''
  161. save!
  162. end
  163. def object_type
  164. :person
  165. end
  166. def to_param
  167. username
  168. end
  169. def excluded_from_timeline_account_ids
  170. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  171. end
  172. def excluded_from_timeline_domains
  173. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  174. end
  175. class << self
  176. def readonly_attributes
  177. super - %w(statuses_count following_count followers_count)
  178. end
  179. def domains
  180. reorder(nil).pluck('distinct accounts.domain')
  181. end
  182. def inboxes
  183. urls = reorder(nil).where(protocol: :activitypub).pluck("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)")
  184. DeliveryFailureTracker.filter(urls)
  185. end
  186. def triadic_closures(account, limit: 5, offset: 0)
  187. sql = <<-SQL.squish
  188. WITH first_degree AS (
  189. SELECT target_account_id
  190. FROM follows
  191. WHERE account_id = :account_id
  192. )
  193. SELECT accounts.*
  194. FROM follows
  195. INNER JOIN accounts ON follows.target_account_id = accounts.id
  196. WHERE
  197. account_id IN (SELECT * FROM first_degree)
  198. AND target_account_id NOT IN (SELECT * FROM first_degree)
  199. AND target_account_id NOT IN (:excluded_account_ids)
  200. AND accounts.suspended = false
  201. GROUP BY target_account_id, accounts.id
  202. ORDER BY count(account_id) DESC
  203. OFFSET :offset
  204. LIMIT :limit
  205. SQL
  206. excluded_account_ids = account.excluded_from_timeline_account_ids + [account.id]
  207. find_by_sql(
  208. [sql, { account_id: account.id, excluded_account_ids: excluded_account_ids, limit: limit, offset: offset }]
  209. )
  210. end
  211. def search_for(terms, limit = 10)
  212. textsearch, query = generate_query_for_search(terms)
  213. sql = <<-SQL.squish
  214. SELECT
  215. accounts.*,
  216. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  217. FROM accounts
  218. WHERE #{query} @@ #{textsearch}
  219. AND accounts.suspended = false
  220. ORDER BY rank DESC
  221. LIMIT ?
  222. SQL
  223. find_by_sql([sql, limit])
  224. end
  225. def advanced_search_for(terms, account, limit = 10)
  226. textsearch, query = generate_query_for_search(terms)
  227. sql = <<-SQL.squish
  228. SELECT
  229. accounts.*,
  230. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  231. FROM accounts
  232. 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 = ?)
  233. WHERE #{query} @@ #{textsearch}
  234. AND accounts.suspended = false
  235. GROUP BY accounts.id
  236. ORDER BY rank DESC
  237. LIMIT ?
  238. SQL
  239. find_by_sql([sql, account.id, account.id, limit])
  240. end
  241. private
  242. def generate_query_for_search(terms)
  243. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  244. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  245. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  246. [textsearch, query]
  247. end
  248. end
  249. before_create :generate_keys
  250. before_validation :normalize_domain
  251. before_validation :prepare_contents, if: :local?
  252. private
  253. def prepare_contents
  254. display_name&.strip!
  255. note&.strip!
  256. end
  257. def generate_keys
  258. return unless local?
  259. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 512 : 2048)
  260. self.private_key = keypair.to_pem
  261. self.public_key = keypair.public_key.to_pem
  262. end
  263. def normalize_domain
  264. return if local?
  265. self.domain = TagManager.instance.normalize_domain(domain)
  266. end
  267. end