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.
 
 
 
 

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