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.

542 lines
16 KiB

Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 years ago
Fix Account model deprecation warnings (#3689) ``` DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:61) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:62) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:63) ``` Here's PR describing changes to Dirty API https://github.com/rails/rails/pull/25337
7 years ago
Fix Account model deprecation warnings (#3689) ``` DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:61) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:62) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:63) ``` Here's PR describing changes to Dirty API https://github.com/rails/rails/pull/25337
7 years ago
8 years ago
8 years ago
Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 years ago
8 years ago
  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. # locked :boolean default(FALSE), not null
  32. # header_remote_url :string default(""), not null
  33. # last_webfingered_at :datetime
  34. # inbox_url :string default(""), not null
  35. # outbox_url :string default(""), not null
  36. # shared_inbox_url :string default(""), not null
  37. # followers_url :string default(""), not null
  38. # protocol :integer default("ostatus"), not null
  39. # memorial :boolean default(FALSE), not null
  40. # moved_to_account_id :bigint(8)
  41. # featured_collection_url :string
  42. # fields :jsonb
  43. # actor_type :string
  44. # discoverable :boolean
  45. # also_known_as :string is an Array
  46. # silenced_at :datetime
  47. # suspended_at :datetime
  48. #
  49. class Account < ApplicationRecord
  50. USERNAME_RE = /[a-z0-9_]+([a-z0-9_\.-]+[a-z0-9_]+)?/i
  51. MENTION_RE = /(?<=^|[^\/[:word:]])@((#{USERNAME_RE})(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  52. MIN_FOLLOWERS_DISCOVERY = 10
  53. include AccountAssociations
  54. include AccountAvatar
  55. include AccountFinderConcern
  56. include AccountHeader
  57. include AccountInteractions
  58. include Attachmentable
  59. include Paginable
  60. include AccountCounters
  61. include DomainNormalizable
  62. MAX_DISPLAY_NAME_LENGTH = (ENV['MAX_DISPLAY_NAME_CHARS'] || 30).to_i
  63. MAX_NOTE_LENGTH = (ENV['MAX_BIO_CHARS'] || 500).to_i
  64. MAX_FIELDS = (ENV['MAX_PROFILE_FIELDS'] || 4).to_i
  65. enum protocol: [:ostatus, :activitypub]
  66. validates :username, presence: true
  67. # Remote user validations
  68. validates :username, uniqueness: { scope: :domain, case_sensitive: true }, if: -> { !local? && will_save_change_to_username? }
  69. validates :username, format: { with: /\A#{USERNAME_RE}\z/i }, if: -> { !local? && will_save_change_to_username? }
  70. # Local user validations
  71. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, length: { maximum: 30 }, if: -> { local? && will_save_change_to_username? }
  72. validates_with UniqueUsernameValidator, if: -> { local? && will_save_change_to_username? }
  73. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? }
  74. validates :display_name, length: { maximum: MAX_DISPLAY_NAME_LENGTH }, if: -> { local? && will_save_change_to_display_name? }
  75. validates :note, note_length: { maximum: MAX_NOTE_LENGTH }, if: -> { local? && will_save_change_to_note? }
  76. validates :fields, length: { maximum: MAX_FIELDS }, if: -> { local? && will_save_change_to_fields? }
  77. scope :remote, -> { where.not(domain: nil) }
  78. scope :local, -> { where(domain: nil) }
  79. scope :expiring, ->(time) { remote.where.not(subscription_expires_at: nil).where('subscription_expires_at < ?', time) }
  80. scope :partitioned, -> { order(Arel.sql('row_number() over (partition by domain)')) }
  81. scope :silenced, -> { where.not(silenced_at: nil) }
  82. scope :suspended, -> { where.not(suspended_at: nil) }
  83. scope :without_suspended, -> { where(suspended_at: nil) }
  84. scope :without_silenced, -> { where(silenced_at: nil) }
  85. scope :recent, -> { reorder(id: :desc) }
  86. scope :bots, -> { where(actor_type: %w(Application Service)) }
  87. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  88. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  89. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  90. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  91. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  92. scope :searchable, -> { without_suspended.where(moved_to_account_id: nil) }
  93. scope :discoverable, -> { searchable.without_silenced.where(discoverable: true).joins(:account_stat).where(AccountStat.arel_table[:followers_count].gteq(MIN_FOLLOWERS_DISCOVERY)) }
  94. scope :tagged_with, ->(tag) { joins(:accounts_tags).where(accounts_tags: { tag_id: tag }) }
  95. 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')) }
  96. scope :popular, -> { order('account_stats.followers_count desc') }
  97. scope :by_domain_and_subdomains, ->(domain) { where(domain: domain).or(where(arel_table[:domain].matches('%.' + domain))) }
  98. delegate :email,
  99. :unconfirmed_email,
  100. :current_sign_in_ip,
  101. :current_sign_in_at,
  102. :confirmed?,
  103. :approved?,
  104. :pending?,
  105. :disabled?,
  106. :role,
  107. :admin?,
  108. :moderator?,
  109. :staff?,
  110. :locale,
  111. :hides_network?,
  112. :shows_application?,
  113. to: :user,
  114. prefix: true,
  115. allow_nil: true
  116. delegate :chosen_languages, to: :user, prefix: false, allow_nil: true
  117. def local?
  118. domain.nil?
  119. end
  120. def moved?
  121. moved_to_account_id.present?
  122. end
  123. def bot?
  124. %w(Application Service).include? actor_type
  125. end
  126. alias bot bot?
  127. def bot=(val)
  128. self.actor_type = ActiveModel::Type::Boolean.new.cast(val) ? 'Service' : 'Person'
  129. end
  130. def acct
  131. local? ? username : "#{username}@#{domain}"
  132. end
  133. def local_username_and_domain
  134. "#{username}@#{Rails.configuration.x.local_domain}"
  135. end
  136. def local_followers_count
  137. Follow.where(target_account_id: id).count
  138. end
  139. def to_webfinger_s
  140. "acct:#{local_username_and_domain}"
  141. end
  142. def subscribed?
  143. subscription_expires_at.present?
  144. end
  145. def possibly_stale?
  146. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  147. end
  148. def refresh!
  149. return if local?
  150. ResolveAccountService.new.call(acct)
  151. end
  152. def silenced?
  153. silenced_at.present?
  154. end
  155. def silence!(date = nil)
  156. date ||= Time.now.utc
  157. update!(silenced_at: date)
  158. end
  159. def unsilence!
  160. update!(silenced_at: nil)
  161. end
  162. def suspended?
  163. suspended_at.present?
  164. end
  165. def suspend!(date = nil)
  166. date ||= Time.now.utc
  167. transaction do
  168. user&.disable! if local?
  169. update!(suspended_at: date)
  170. end
  171. end
  172. def unsuspend!
  173. transaction do
  174. user&.enable! if local?
  175. update!(suspended_at: nil)
  176. end
  177. end
  178. def memorialize!
  179. transaction do
  180. user&.disable! if local?
  181. update!(memorial: true)
  182. end
  183. end
  184. def sign?
  185. true
  186. end
  187. def keypair
  188. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  189. end
  190. def tags_as_strings=(tag_names)
  191. tag_names.map! { |name| name.mb_chars.downcase.to_s }
  192. tag_names.uniq!
  193. # Existing hashtags
  194. hashtags_map = Tag.where(name: tag_names).each_with_object({}) { |tag, h| h[tag.name] = tag }
  195. # Initialize not yet existing hashtags
  196. tag_names.each do |name|
  197. next if hashtags_map.key?(name)
  198. hashtags_map[name] = Tag.new(name: name)
  199. end
  200. # Remove hashtags that are to be deleted
  201. tags.each do |tag|
  202. if hashtags_map.key?(tag.name)
  203. hashtags_map.delete(tag.name)
  204. else
  205. transaction do
  206. tags.delete(tag)
  207. tag.decrement_count!(:accounts_count)
  208. end
  209. end
  210. end
  211. # Add hashtags that were so far missing
  212. hashtags_map.each_value do |tag|
  213. transaction do
  214. tags << tag
  215. tag.increment_count!(:accounts_count)
  216. end
  217. end
  218. end
  219. def also_known_as
  220. self[:also_known_as] || []
  221. end
  222. def fields
  223. (self[:fields] || []).map { |f| Field.new(self, f) }
  224. end
  225. def fields_attributes=(attributes)
  226. fields = []
  227. old_fields = self[:fields] || []
  228. old_fields = [] if old_fields.is_a?(Hash)
  229. if attributes.is_a?(Hash)
  230. attributes.each_value do |attr|
  231. next if attr[:name].blank?
  232. previous = old_fields.find { |item| item['value'] == attr[:value] }
  233. if previous && previous['verified_at'].present?
  234. attr[:verified_at] = previous['verified_at']
  235. end
  236. fields << attr
  237. end
  238. end
  239. self[:fields] = fields
  240. end
  241. def build_fields
  242. return if fields.size >= MAX_FIELDS
  243. tmp = self[:fields] || []
  244. tmp = [] if tmp.is_a?(Hash)
  245. (MAX_FIELDS - tmp.size).times do
  246. tmp << { name: '', value: '' }
  247. end
  248. self.fields = tmp
  249. end
  250. def magic_key
  251. modulus, exponent = [keypair.public_key.n, keypair.public_key.e].map do |component|
  252. result = []
  253. until component.zero?
  254. result << [component % 256].pack('C')
  255. component >>= 8
  256. end
  257. result.reverse.join
  258. end
  259. (['RSA'] + [modulus, exponent].map { |n| Base64.urlsafe_encode64(n) }).join('.')
  260. end
  261. def subscription(webhook_url)
  262. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  263. end
  264. def save_with_optional_media!
  265. save!
  266. rescue ActiveRecord::RecordInvalid
  267. self.avatar = nil
  268. self.header = nil
  269. self[:avatar_remote_url] = ''
  270. self[:header_remote_url] = ''
  271. save!
  272. end
  273. def object_type
  274. :person
  275. end
  276. def to_param
  277. username
  278. end
  279. def excluded_from_timeline_account_ids
  280. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  281. end
  282. def excluded_from_timeline_domains
  283. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  284. end
  285. def preferred_inbox_url
  286. shared_inbox_url.presence || inbox_url
  287. end
  288. class Field < ActiveModelSerializers::Model
  289. attributes :name, :value, :verified_at, :account, :errors
  290. def initialize(account, attributes)
  291. @account = account
  292. @attributes = attributes
  293. @name = attributes['name'].strip[0, string_limit]
  294. @value = attributes['value'].strip[0, string_limit]
  295. @verified_at = attributes['verified_at']&.to_datetime
  296. @errors = {}
  297. end
  298. def verified?
  299. verified_at.present?
  300. end
  301. def value_for_verification
  302. @value_for_verification ||= begin
  303. if account.local?
  304. value
  305. else
  306. ActionController::Base.helpers.strip_tags(value)
  307. end
  308. end
  309. end
  310. def verifiable?
  311. value_for_verification.present? && value_for_verification.start_with?('http://', 'https://')
  312. end
  313. def mark_verified!
  314. @verified_at = Time.now.utc
  315. @attributes['verified_at'] = @verified_at
  316. end
  317. def to_h
  318. { name: @name, value: @value, verified_at: @verified_at }
  319. end
  320. private
  321. def string_limit
  322. if account.local?
  323. 255
  324. else
  325. 2047
  326. end
  327. end
  328. end
  329. class << self
  330. def readonly_attributes
  331. super - %w(statuses_count following_count followers_count)
  332. end
  333. def domains
  334. reorder(nil).pluck(Arel.sql('distinct accounts.domain'))
  335. end
  336. def inboxes
  337. urls = reorder(nil).where(protocol: :activitypub).pluck(Arel.sql("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)"))
  338. DeliveryFailureTracker.filter(urls)
  339. end
  340. def search_for(terms, limit = 10, offset = 0)
  341. textsearch, query = generate_query_for_search(terms)
  342. sql = <<-SQL.squish
  343. SELECT
  344. accounts.*,
  345. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  346. FROM accounts
  347. WHERE #{query} @@ #{textsearch}
  348. AND accounts.suspended_at IS NULL
  349. AND accounts.moved_to_account_id IS NULL
  350. ORDER BY rank DESC
  351. LIMIT ? OFFSET ?
  352. SQL
  353. records = find_by_sql([sql, limit, offset])
  354. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  355. records
  356. end
  357. def advanced_search_for(terms, account, limit = 10, following = false, offset = 0)
  358. textsearch, query = generate_query_for_search(terms)
  359. if following
  360. sql = <<-SQL.squish
  361. WITH first_degree AS (
  362. SELECT target_account_id
  363. FROM follows
  364. WHERE account_id = ?
  365. )
  366. SELECT
  367. accounts.*,
  368. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  369. FROM accounts
  370. 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 = ?)
  371. WHERE accounts.id IN (SELECT * FROM first_degree)
  372. AND #{query} @@ #{textsearch}
  373. AND accounts.suspended_at IS NULL
  374. AND accounts.moved_to_account_id IS NULL
  375. GROUP BY accounts.id
  376. ORDER BY rank DESC
  377. LIMIT ? OFFSET ?
  378. SQL
  379. records = find_by_sql([sql, account.id, account.id, account.id, limit, offset])
  380. else
  381. sql = <<-SQL.squish
  382. SELECT
  383. accounts.*,
  384. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  385. FROM accounts
  386. 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 = ?)
  387. WHERE #{query} @@ #{textsearch}
  388. AND accounts.suspended_at IS NULL
  389. AND accounts.moved_to_account_id IS NULL
  390. GROUP BY accounts.id
  391. ORDER BY rank DESC
  392. LIMIT ? OFFSET ?
  393. SQL
  394. records = find_by_sql([sql, account.id, account.id, limit, offset])
  395. end
  396. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  397. records
  398. end
  399. private
  400. def generate_query_for_search(terms)
  401. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  402. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  403. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  404. [textsearch, query]
  405. end
  406. end
  407. def emojis
  408. @emojis ||= CustomEmoji.from_text(emojifiable_text, domain)
  409. end
  410. before_create :generate_keys
  411. before_validation :prepare_contents, if: :local?
  412. before_validation :prepare_username, on: :create
  413. before_destroy :clean_feed_manager
  414. private
  415. def prepare_contents
  416. display_name&.strip!
  417. note&.strip!
  418. end
  419. def prepare_username
  420. username&.squish!
  421. end
  422. def generate_keys
  423. return unless local? && !Rails.env.test?
  424. keypair = OpenSSL::PKey::RSA.new(2048)
  425. self.private_key = keypair.to_pem
  426. self.public_key = keypair.public_key.to_pem
  427. end
  428. def normalize_domain
  429. return if local?
  430. super
  431. end
  432. def emojifiable_text
  433. [note, display_name, fields.map(&:value)].join(' ')
  434. end
  435. def clean_feed_manager
  436. reblog_key = FeedManager.instance.key(:home, id, 'reblogs')
  437. reblogged_id_set = Redis.current.zrange(reblog_key, 0, -1)
  438. Redis.current.pipelined do
  439. Redis.current.del(FeedManager.instance.key(:home, id))
  440. Redis.current.del(reblog_key)
  441. reblogged_id_set.each do |reblogged_id|
  442. reblog_set_key = FeedManager.instance.key(:home, id, "reblogs:#{reblogged_id}")
  443. Redis.current.del(reblog_set_key)
  444. end
  445. end
  446. end
  447. end