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.
 
 
 
 

287 lines
9.8 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. scope :remote, -> { where.not(domain: nil) }
  81. scope :local, -> { where(domain: nil) }
  82. scope :without_followers, -> { where(followers_count: 0) }
  83. scope :with_followers, -> { where('followers_count > 0') }
  84. scope :expiring, ->(time) { remote.where.not(subscription_expires_at: nil).where('subscription_expires_at < ?', time) }
  85. scope :partitioned, -> { order('row_number() over (partition by domain)') }
  86. scope :silenced, -> { where(silenced: true) }
  87. scope :suspended, -> { where(suspended: true) }
  88. scope :recent, -> { reorder(id: :desc) }
  89. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  90. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  91. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  92. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  93. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  94. delegate :email,
  95. :current_sign_in_ip,
  96. :current_sign_in_at,
  97. :confirmed?,
  98. :admin?,
  99. :locale,
  100. to: :user,
  101. prefix: true,
  102. allow_nil: true
  103. delegate :filtered_languages, to: :user, prefix: false, allow_nil: true
  104. def local?
  105. domain.nil?
  106. end
  107. def acct
  108. local? ? username : "#{username}@#{domain}"
  109. end
  110. def local_username_and_domain
  111. "#{username}@#{Rails.configuration.x.local_domain}"
  112. end
  113. def to_webfinger_s
  114. "acct:#{local_username_and_domain}"
  115. end
  116. def subscribed?
  117. subscription_expires_at.present?
  118. end
  119. def keypair
  120. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  121. end
  122. def subscription(webhook_url)
  123. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  124. end
  125. def save_with_optional_media!
  126. save!
  127. rescue ActiveRecord::RecordInvalid
  128. self.avatar = nil
  129. self.header = nil
  130. self[:avatar_remote_url] = ''
  131. self[:header_remote_url] = ''
  132. save!
  133. end
  134. def object_type
  135. :person
  136. end
  137. def to_param
  138. username
  139. end
  140. def excluded_from_timeline_account_ids
  141. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  142. end
  143. def excluded_from_timeline_domains
  144. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  145. end
  146. class << self
  147. def readonly_attributes
  148. super - %w(statuses_count following_count followers_count)
  149. end
  150. def domains
  151. reorder(nil).pluck('distinct accounts.domain')
  152. end
  153. def inboxes
  154. reorder(nil).where(protocol: :activitypub).pluck("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)")
  155. end
  156. def triadic_closures(account, limit: 5, offset: 0)
  157. sql = <<-SQL.squish
  158. WITH first_degree AS (
  159. SELECT target_account_id
  160. FROM follows
  161. WHERE account_id = :account_id
  162. )
  163. SELECT accounts.*
  164. FROM follows
  165. INNER JOIN accounts ON follows.target_account_id = accounts.id
  166. WHERE
  167. account_id IN (SELECT * FROM first_degree)
  168. AND target_account_id NOT IN (SELECT * FROM first_degree)
  169. AND target_account_id NOT IN (:excluded_account_ids)
  170. AND accounts.suspended = false
  171. GROUP BY target_account_id, accounts.id
  172. ORDER BY count(account_id) DESC
  173. OFFSET :offset
  174. LIMIT :limit
  175. SQL
  176. excluded_account_ids = account.excluded_from_timeline_account_ids + [account.id]
  177. find_by_sql(
  178. [sql, { account_id: account.id, excluded_account_ids: excluded_account_ids, limit: limit, offset: offset }]
  179. )
  180. end
  181. def search_for(terms, limit = 10)
  182. textsearch, query = generate_query_for_search(terms)
  183. sql = <<-SQL.squish
  184. SELECT
  185. accounts.*,
  186. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  187. FROM accounts
  188. WHERE #{query} @@ #{textsearch}
  189. AND accounts.suspended = false
  190. ORDER BY rank DESC
  191. LIMIT ?
  192. SQL
  193. find_by_sql([sql, limit])
  194. end
  195. def advanced_search_for(terms, account, limit = 10)
  196. textsearch, query = generate_query_for_search(terms)
  197. sql = <<-SQL.squish
  198. SELECT
  199. accounts.*,
  200. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  201. FROM accounts
  202. 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 = ?)
  203. WHERE #{query} @@ #{textsearch}
  204. AND accounts.suspended = false
  205. GROUP BY accounts.id
  206. ORDER BY rank DESC
  207. LIMIT ?
  208. SQL
  209. find_by_sql([sql, account.id, account.id, limit])
  210. end
  211. private
  212. def generate_query_for_search(terms)
  213. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  214. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  215. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  216. [textsearch, query]
  217. end
  218. end
  219. before_create :generate_keys
  220. before_validation :normalize_domain
  221. before_validation :prepare_contents, if: :local?
  222. private
  223. def prepare_contents
  224. display_name&.strip!
  225. note&.strip!
  226. end
  227. def generate_keys
  228. return unless local?
  229. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 512 : 2048)
  230. self.private_key = keypair.to_pem
  231. self.public_key = keypair.public_key.to_pem
  232. end
  233. def normalize_domain
  234. return if local?
  235. self.domain = TagManager.instance.normalize_domain(domain)
  236. end
  237. end