The code powering m.abunchtell.com https://m.abunchtell.com
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

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