The code powering m.abunchtell.com https://m.abunchtell.com
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

508 satır
15 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. # last_webfingered_at :datetime
  36. # inbox_url :string default(""), not null
  37. # outbox_url :string default(""), not null
  38. # shared_inbox_url :string default(""), not null
  39. # followers_url :string default(""), not null
  40. # protocol :integer default("ostatus"), not null
  41. # memorial :boolean default(FALSE), not null
  42. # moved_to_account_id :bigint(8)
  43. # featured_collection_url :string
  44. # fields :jsonb
  45. # actor_type :string
  46. # discoverable :boolean
  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. MIN_FOLLOWERS_DISCOVERY = 10
  52. include AccountAssociations
  53. include AccountAvatar
  54. include AccountFinderConcern
  55. include AccountHeader
  56. include AccountInteractions
  57. include Attachmentable
  58. include Paginable
  59. include AccountCounters
  60. include DomainNormalizable
  61. enum protocol: [:ostatus, :activitypub]
  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. scope :remote, -> { where.not(domain: nil) }
  74. scope :local, -> { where(domain: nil) }
  75. scope :expiring, ->(time) { remote.where.not(subscription_expires_at: nil).where('subscription_expires_at < ?', time) }
  76. scope :partitioned, -> { order(Arel.sql('row_number() over (partition by domain)')) }
  77. scope :silenced, -> { where(silenced: true) }
  78. scope :suspended, -> { where(suspended: true) }
  79. scope :without_suspended, -> { where(suspended: false) }
  80. scope :recent, -> { reorder(id: :desc) }
  81. scope :bots, -> { where(actor_type: %w(Application Service)) }
  82. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  83. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  84. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  85. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  86. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  87. scope :searchable, -> { where(suspended: false).where(moved_to_account_id: nil) }
  88. scope :discoverable, -> { searchable.where(silenced: false).where(discoverable: true).joins(:account_stat).where(AccountStat.arel_table[:followers_count].gteq(MIN_FOLLOWERS_DISCOVERY)).by_recent_status }
  89. scope :tagged_with, ->(tag) { joins(:accounts_tags).where(accounts_tags: { tag_id: tag }) }
  90. scope :by_recent_status, -> { order(Arel.sql('(case when account_stats.last_status_at is null then 1 else 0 end) asc, account_stats.last_status_at desc')) }
  91. scope :popular, -> { order('account_stats.followers_count desc') }
  92. delegate :email,
  93. :unconfirmed_email,
  94. :current_sign_in_ip,
  95. :current_sign_in_at,
  96. :confirmed?,
  97. :admin?,
  98. :moderator?,
  99. :staff?,
  100. :locale,
  101. :hides_network?,
  102. to: :user,
  103. prefix: true,
  104. allow_nil: true
  105. delegate :chosen_languages, to: :user, prefix: false, allow_nil: true
  106. def local?
  107. domain.nil?
  108. end
  109. def moved?
  110. moved_to_account_id.present?
  111. end
  112. def bot?
  113. %w(Application Service).include? actor_type
  114. end
  115. alias bot bot?
  116. def bot=(val)
  117. self.actor_type = ActiveModel::Type::Boolean.new.cast(val) ? 'Service' : 'Person'
  118. end
  119. def acct
  120. local? ? username : "#{username}@#{domain}"
  121. end
  122. def local_username_and_domain
  123. "#{username}@#{Rails.configuration.x.local_domain}"
  124. end
  125. def local_followers_count
  126. Follow.where(target_account_id: id).count
  127. end
  128. def to_webfinger_s
  129. "acct:#{local_username_and_domain}"
  130. end
  131. def subscribed?
  132. subscription_expires_at.present?
  133. end
  134. def possibly_stale?
  135. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  136. end
  137. def refresh!
  138. return if local?
  139. ResolveAccountService.new.call(acct)
  140. end
  141. def silence!
  142. update!(silenced: true)
  143. end
  144. def unsilence!
  145. update!(silenced: false)
  146. end
  147. def suspend!
  148. transaction do
  149. user&.disable! if local?
  150. update!(suspended: true)
  151. end
  152. end
  153. def unsuspend!
  154. transaction do
  155. user&.enable! if local?
  156. update!(suspended: false)
  157. end
  158. end
  159. def memorialize!
  160. transaction do
  161. user&.disable! if local?
  162. update!(memorial: true)
  163. end
  164. end
  165. def keypair
  166. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  167. end
  168. def tags_as_strings=(tag_names)
  169. tag_names.map! { |name| name.mb_chars.downcase.to_s }
  170. tag_names.uniq!
  171. # Existing hashtags
  172. hashtags_map = Tag.where(name: tag_names).each_with_object({}) { |tag, h| h[tag.name] = tag }
  173. # Initialize not yet existing hashtags
  174. tag_names.each do |name|
  175. next if hashtags_map.key?(name)
  176. hashtags_map[name] = Tag.new(name: name)
  177. end
  178. # Remove hashtags that are to be deleted
  179. tags.each do |tag|
  180. if hashtags_map.key?(tag.name)
  181. hashtags_map.delete(tag.name)
  182. else
  183. transaction do
  184. tags.delete(tag)
  185. tag.decrement_count!(:accounts_count)
  186. end
  187. end
  188. end
  189. # Add hashtags that were so far missing
  190. hashtags_map.each_value do |tag|
  191. transaction do
  192. tags << tag
  193. tag.increment_count!(:accounts_count)
  194. end
  195. end
  196. end
  197. def fields
  198. (self[:fields] || []).map { |f| Field.new(self, f) }
  199. end
  200. def fields_attributes=(attributes)
  201. fields = []
  202. old_fields = self[:fields] || []
  203. if attributes.is_a?(Hash)
  204. attributes.each_value do |attr|
  205. next if attr[:name].blank?
  206. previous = old_fields.find { |item| item['value'] == attr[:value] }
  207. if previous && previous['verified_at'].present?
  208. attr[:verified_at] = previous['verified_at']
  209. end
  210. fields << attr
  211. end
  212. end
  213. self[:fields] = fields
  214. end
  215. DEFAULT_FIELDS_SIZE = 4
  216. def build_fields
  217. return if fields.size >= DEFAULT_FIELDS_SIZE
  218. tmp = self[:fields] || []
  219. (DEFAULT_FIELDS_SIZE - tmp.size).times do
  220. tmp << { name: '', value: '' }
  221. end
  222. self.fields = tmp
  223. end
  224. def magic_key
  225. modulus, exponent = [keypair.public_key.n, keypair.public_key.e].map do |component|
  226. result = []
  227. until component.zero?
  228. result << [component % 256].pack('C')
  229. component >>= 8
  230. end
  231. result.reverse.join
  232. end
  233. (['RSA'] + [modulus, exponent].map { |n| Base64.urlsafe_encode64(n) }).join('.')
  234. end
  235. def subscription(webhook_url)
  236. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  237. end
  238. def save_with_optional_media!
  239. save!
  240. rescue ActiveRecord::RecordInvalid
  241. self.avatar = nil
  242. self.header = nil
  243. self[:avatar_remote_url] = ''
  244. self[:header_remote_url] = ''
  245. save!
  246. end
  247. def object_type
  248. :person
  249. end
  250. def to_param
  251. username
  252. end
  253. def excluded_from_timeline_account_ids
  254. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  255. end
  256. def excluded_from_timeline_domains
  257. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  258. end
  259. def preferred_inbox_url
  260. shared_inbox_url.presence || inbox_url
  261. end
  262. class Field < ActiveModelSerializers::Model
  263. attributes :name, :value, :verified_at, :account, :errors
  264. def initialize(account, attributes)
  265. @account = account
  266. @attributes = attributes
  267. @name = attributes['name'].strip[0, string_limit]
  268. @value = attributes['value'].strip[0, string_limit]
  269. @verified_at = attributes['verified_at']&.to_datetime
  270. @errors = {}
  271. end
  272. def verified?
  273. verified_at.present?
  274. end
  275. def value_for_verification
  276. @value_for_verification ||= begin
  277. if account.local?
  278. value
  279. else
  280. ActionController::Base.helpers.strip_tags(value)
  281. end
  282. end
  283. end
  284. def verifiable?
  285. value_for_verification.present? && value_for_verification.start_with?('http://', 'https://')
  286. end
  287. def mark_verified!
  288. @verified_at = Time.now.utc
  289. @attributes['verified_at'] = @verified_at
  290. end
  291. def to_h
  292. { name: @name, value: @value, verified_at: @verified_at }
  293. end
  294. private
  295. def string_limit
  296. if account.local?
  297. 255
  298. else
  299. 2047
  300. end
  301. end
  302. end
  303. class << self
  304. def readonly_attributes
  305. super - %w(statuses_count following_count followers_count)
  306. end
  307. def domains
  308. reorder(nil).pluck(Arel.sql('distinct accounts.domain'))
  309. end
  310. def inboxes
  311. urls = reorder(nil).where(protocol: :activitypub).pluck(Arel.sql("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)"))
  312. DeliveryFailureTracker.filter(urls)
  313. end
  314. def search_for(terms, limit = 10)
  315. textsearch, query = generate_query_for_search(terms)
  316. sql = <<-SQL.squish
  317. SELECT
  318. accounts.*,
  319. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  320. FROM accounts
  321. WHERE #{query} @@ #{textsearch}
  322. AND accounts.suspended = false
  323. AND accounts.moved_to_account_id IS NULL
  324. ORDER BY rank DESC
  325. LIMIT ?
  326. SQL
  327. records = find_by_sql([sql, limit])
  328. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  329. records
  330. end
  331. def advanced_search_for(terms, account, limit = 10, following = false)
  332. textsearch, query = generate_query_for_search(terms)
  333. if following
  334. sql = <<-SQL.squish
  335. WITH first_degree AS (
  336. SELECT target_account_id
  337. FROM follows
  338. WHERE account_id = ?
  339. )
  340. SELECT
  341. accounts.*,
  342. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  343. FROM accounts
  344. 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 = ?)
  345. WHERE accounts.id IN (SELECT * FROM first_degree)
  346. AND #{query} @@ #{textsearch}
  347. AND accounts.suspended = false
  348. AND accounts.moved_to_account_id IS NULL
  349. GROUP BY accounts.id
  350. ORDER BY rank DESC
  351. LIMIT ?
  352. SQL
  353. records = find_by_sql([sql, account.id, account.id, account.id, limit])
  354. else
  355. sql = <<-SQL.squish
  356. SELECT
  357. accounts.*,
  358. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  359. FROM accounts
  360. 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 = ?)
  361. WHERE #{query} @@ #{textsearch}
  362. AND accounts.suspended = false
  363. AND accounts.moved_to_account_id IS NULL
  364. GROUP BY accounts.id
  365. ORDER BY rank DESC
  366. LIMIT ?
  367. SQL
  368. records = find_by_sql([sql, account.id, account.id, limit])
  369. end
  370. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  371. records
  372. end
  373. private
  374. def generate_query_for_search(terms)
  375. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  376. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  377. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  378. [textsearch, query]
  379. end
  380. end
  381. def emojis
  382. @emojis ||= CustomEmoji.from_text(emojifiable_text, domain)
  383. end
  384. before_create :generate_keys
  385. before_validation :prepare_contents, if: :local?
  386. before_destroy :clean_feed_manager
  387. private
  388. def prepare_contents
  389. display_name&.strip!
  390. note&.strip!
  391. end
  392. def generate_keys
  393. return unless local? && !Rails.env.test?
  394. keypair = OpenSSL::PKey::RSA.new(2048)
  395. self.private_key = keypair.to_pem
  396. self.public_key = keypair.public_key.to_pem
  397. end
  398. def normalize_domain
  399. return if local?
  400. super
  401. end
  402. def emojifiable_text
  403. [note, display_name, fields.map(&:value)].join(' ')
  404. end
  405. def clean_feed_manager
  406. reblog_key = FeedManager.instance.key(:home, id, 'reblogs')
  407. reblogged_id_set = Redis.current.zrange(reblog_key, 0, -1)
  408. Redis.current.pipelined do
  409. Redis.current.del(FeedManager.instance.key(:home, id))
  410. Redis.current.del(reblog_key)
  411. reblogged_id_set.each do |reblogged_id|
  412. reblog_set_key = FeedManager.instance.key(:home, id, "reblogs:#{reblogged_id}")
  413. Redis.current.del(reblog_set_key)
  414. end
  415. end
  416. end
  417. end