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.

571 lines
17 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
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
Add follower synchronization mechanism (#14510) * Add support for followers synchronization on the receiving end Check the `collectionSynchronization` attribute on `Create` and `Announce` activities and synchronize followers from provided collection if possible. * Add tests for followers synchronization on the receiving end * Add support for follower synchronization on the sender's end * Add tests for the sending end * Switch from AS attributes to HTTP header Replace the custom `collectionSynchronization` ActivityStreams attribute by an HTTP header (`X-AS-Collection-Synchronization`) with the same syntax as the `Signature` header and the following fields: - `collectionId` to specify which collection to synchronize - `digest` for the SHA256 hex-digest of the list of followers known on the receiving instance (where “receiving instance” is determined by accounts sharing the same host name for their ActivityPub actor `id`) - `url` of a collection that should be fetched by the instance actor Internally, move away from the webfinger-based `domain` attribute and use account `uri` prefix to group accounts. * Add environment variable to disable followers synchronization Since the whole mechanism relies on some new preconditions that, in some extremely rare cases, might not be met, add an environment variable (DISABLE_FOLLOWERS_SYNCHRONIZATION) to disable the mechanism altogether and avoid followers being incorrectly removed. The current conditions are: 1. all managed accounts' actor `id` and inbox URL have the same URI scheme and netloc. 2. all accounts whose actor `id` or inbox URL share the same URI scheme and netloc as a managed account must be managed by the same Mastodon instance as well. As far as Mastodon is concerned, breaking those preconditions require extensive configuration changes in the reverse proxy and might also cause other issues. Therefore, this environment variable provides a way out for people with highly unusual configurations, and can be safely ignored for the overwhelming majority of Mastodon administrators. * Only set follower synchronization header on non-public statuses This is to avoid unnecessary computations and allow Follow-related activities to be handled by the usual codepath instead of going through the synchronization mechanism (otherwise, any Follow/Undo/Accept activity would trigger the synchronization mechanism even if processing the activity itself would be enough to re-introduce synchronization) * Change how ActivityPub::SynchronizeFollowersService handles follow requests If the remote lists a local follower which we only know has sent a follow request, consider the follow request as accepted instead of sending an Undo. * Integrate review feeback - rename X-AS-Collection-Synchronization to Collection-Synchronization - various minor refactoring and code style changes * Only select required fields when computing followers_hash * Use actor URI rather than webfinger domain in synchronization endpoint * Change hash computation to be a XOR of individual hashes Makes it much easier to be memory-efficient, and avoid sorting discrepancy issues. * Marginally improve followers_hash computation speed * Further improve hash computation performances by using pluck_each
3 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. # locked :boolean default(FALSE), not null
  31. # header_remote_url :string default(""), not null
  32. # last_webfingered_at :datetime
  33. # inbox_url :string default(""), not null
  34. # outbox_url :string default(""), not null
  35. # shared_inbox_url :string default(""), not null
  36. # followers_url :string default(""), not null
  37. # protocol :integer default("ostatus"), not null
  38. # memorial :boolean default(FALSE), not null
  39. # moved_to_account_id :bigint(8)
  40. # featured_collection_url :string
  41. # fields :jsonb
  42. # actor_type :string
  43. # discoverable :boolean
  44. # also_known_as :string is an Array
  45. # silenced_at :datetime
  46. # suspended_at :datetime
  47. # trust_level :integer
  48. # hide_collections :boolean
  49. # avatar_storage_schema_version :integer
  50. # header_storage_schema_version :integer
  51. # devices_url :string
  52. # sensitized_at :datetime
  53. # suspension_origin :integer
  54. #
  55. class Account < ApplicationRecord
  56. self.ignored_columns = %w(subscription_expires_at)
  57. USERNAME_RE = /[a-z0-9_]+([a-z0-9_\.-]+[a-z0-9_]+)?/i
  58. MENTION_RE = /(?<=^|[^\/[:word:]])@((#{USERNAME_RE})(?:@[[:word:]\.\-]+[a-z0-9]+)?)/i
  59. include AccountAssociations
  60. include AccountAvatar
  61. include AccountFinderConcern
  62. include AccountHeader
  63. include AccountInteractions
  64. include Attachmentable
  65. include Paginable
  66. include AccountCounters
  67. include DomainNormalizable
  68. include DomainMaterializable
  69. include AccountMerging
  70. TRUST_LEVELS = {
  71. untrusted: 0,
  72. trusted: 1,
  73. }.freeze
  74. enum protocol: [:ostatus, :activitypub]
  75. enum suspension_origin: [:local, :remote], _prefix: true
  76. validates :username, presence: true
  77. validates_with UniqueUsernameValidator, if: -> { will_save_change_to_username? }
  78. # Remote user validations
  79. validates :username, format: { with: /\A#{USERNAME_RE}\z/i }, if: -> { !local? && will_save_change_to_username? }
  80. # Local user validations
  81. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, length: { maximum: 30 }, if: -> { local? && will_save_change_to_username? && actor_type != 'Application' }
  82. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? }
  83. validates :display_name, length: { maximum: 30 }, if: -> { local? && will_save_change_to_display_name? }
  84. validates :note, note_length: { maximum: 500 }, if: -> { local? && will_save_change_to_note? }
  85. validates :fields, length: { maximum: 4 }, if: -> { local? && will_save_change_to_fields? }
  86. scope :remote, -> { where.not(domain: nil) }
  87. scope :local, -> { where(domain: nil) }
  88. scope :partitioned, -> { order(Arel.sql('row_number() over (partition by domain)')) }
  89. scope :silenced, -> { where.not(silenced_at: nil) }
  90. scope :suspended, -> { where.not(suspended_at: nil) }
  91. scope :sensitized, -> { where.not(sensitized_at: nil) }
  92. scope :without_suspended, -> { where(suspended_at: nil) }
  93. scope :without_silenced, -> { where(silenced_at: nil) }
  94. scope :without_instance_actor, -> { where.not(id: -99) }
  95. scope :recent, -> { reorder(id: :desc) }
  96. scope :bots, -> { where(actor_type: %w(Application Service)) }
  97. scope :groups, -> { where(actor_type: 'Group') }
  98. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  99. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  100. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  101. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  102. scope :searchable, -> { without_suspended.where(moved_to_account_id: nil) }
  103. scope :discoverable, -> { searchable.without_silenced.where(discoverable: true).left_outer_joins(:account_stat) }
  104. scope :tagged_with, ->(tag) { joins(:accounts_tags).where(accounts_tags: { tag_id: tag }) }
  105. 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, accounts.id desc')) }
  106. scope :by_recent_sign_in, -> { order(Arel.sql('(case when users.current_sign_in_at is null then 1 else 0 end) asc, users.current_sign_in_at desc, accounts.id desc')) }
  107. scope :popular, -> { order('account_stats.followers_count desc') }
  108. scope :by_domain_and_subdomains, ->(domain) { where(domain: domain).or(where(arel_table[:domain].matches('%.' + domain))) }
  109. scope :not_excluded_by_account, ->(account) { where.not(id: account.excluded_from_timeline_account_ids) }
  110. scope :not_domain_blocked_by_account, ->(account) { where(arel_table[:domain].eq(nil).or(arel_table[:domain].not_in(account.excluded_from_timeline_domains))) }
  111. delegate :email,
  112. :unconfirmed_email,
  113. :current_sign_in_ip,
  114. :current_sign_in_at,
  115. :confirmed?,
  116. :approved?,
  117. :pending?,
  118. :disabled?,
  119. :unconfirmed_or_pending?,
  120. :role,
  121. :admin?,
  122. :moderator?,
  123. :staff?,
  124. :locale,
  125. :hides_network?,
  126. :shows_application?,
  127. to: :user,
  128. prefix: true,
  129. allow_nil: true
  130. delegate :chosen_languages, to: :user, prefix: false, allow_nil: true
  131. update_index('accounts#account', :self)
  132. def local?
  133. domain.nil?
  134. end
  135. def moved?
  136. moved_to_account_id.present?
  137. end
  138. def bot?
  139. %w(Application Service).include? actor_type
  140. end
  141. def instance_actor?
  142. id == -99
  143. end
  144. alias bot bot?
  145. def bot=(val)
  146. self.actor_type = ActiveModel::Type::Boolean.new.cast(val) ? 'Service' : 'Person'
  147. end
  148. def group?
  149. actor_type == 'Group'
  150. end
  151. alias group group?
  152. def acct
  153. local? ? username : "#{username}@#{domain}"
  154. end
  155. def pretty_acct
  156. local? ? username : "#{username}@#{Addressable::IDNA.to_unicode(domain)}"
  157. end
  158. def local_username_and_domain
  159. "#{username}@#{Rails.configuration.x.local_domain}"
  160. end
  161. def local_followers_count
  162. Follow.where(target_account_id: id).count
  163. end
  164. def to_webfinger_s
  165. "acct:#{local_username_and_domain}"
  166. end
  167. def searchable?
  168. !(suspended? || moved?)
  169. end
  170. def possibly_stale?
  171. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  172. end
  173. def trust_level
  174. self[:trust_level] || 0
  175. end
  176. def refresh!
  177. ResolveAccountService.new.call(acct) unless local?
  178. end
  179. def silenced?
  180. silenced_at.present?
  181. end
  182. def silence!(date = Time.now.utc)
  183. update!(silenced_at: date)
  184. end
  185. def unsilence!
  186. update!(silenced_at: nil)
  187. end
  188. def suspended?
  189. suspended_at.present? && !instance_actor?
  190. end
  191. def suspended_permanently?
  192. suspended? && deletion_request.nil?
  193. end
  194. def suspended_temporarily?
  195. suspended? && deletion_request.present?
  196. end
  197. def suspend!(date: Time.now.utc, origin: :local)
  198. transaction do
  199. create_deletion_request!
  200. update!(suspended_at: date, suspension_origin: origin)
  201. end
  202. end
  203. def unsuspend!
  204. transaction do
  205. deletion_request&.destroy!
  206. update!(suspended_at: nil, suspension_origin: nil)
  207. end
  208. end
  209. def sensitized?
  210. sensitized_at.present?
  211. end
  212. def sensitize!(date = Time.now.utc)
  213. update!(sensitized_at: date)
  214. end
  215. def unsensitize!
  216. update!(sensitized_at: nil)
  217. end
  218. def memorialize!
  219. update!(memorial: true)
  220. end
  221. def sign?
  222. true
  223. end
  224. def keypair
  225. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  226. end
  227. def tags_as_strings=(tag_names)
  228. hashtags_map = Tag.find_or_create_by_names(tag_names).index_by(&:name)
  229. # Remove hashtags that are to be deleted
  230. tags.each do |tag|
  231. if hashtags_map.key?(tag.name)
  232. hashtags_map.delete(tag.name)
  233. else
  234. transaction do
  235. tags.delete(tag)
  236. tag.decrement_count!(:accounts_count)
  237. end
  238. end
  239. end
  240. # Add hashtags that were so far missing
  241. hashtags_map.each_value do |tag|
  242. transaction do
  243. tags << tag
  244. tag.increment_count!(:accounts_count)
  245. end
  246. end
  247. end
  248. def also_known_as
  249. self[:also_known_as] || []
  250. end
  251. def fields
  252. (self[:fields] || []).map { |f| Field.new(self, f) }
  253. end
  254. def fields_attributes=(attributes)
  255. fields = []
  256. old_fields = self[:fields] || []
  257. old_fields = [] if old_fields.is_a?(Hash)
  258. if attributes.is_a?(Hash)
  259. attributes.each_value do |attr|
  260. next if attr[:name].blank?
  261. previous = old_fields.find { |item| item['value'] == attr[:value] }
  262. if previous && previous['verified_at'].present?
  263. attr[:verified_at] = previous['verified_at']
  264. end
  265. fields << attr
  266. end
  267. end
  268. self[:fields] = fields
  269. end
  270. DEFAULT_FIELDS_SIZE = 4
  271. def build_fields
  272. return if fields.size >= DEFAULT_FIELDS_SIZE
  273. tmp = self[:fields] || []
  274. tmp = [] if tmp.is_a?(Hash)
  275. (DEFAULT_FIELDS_SIZE - tmp.size).times do
  276. tmp << { name: '', value: '' }
  277. end
  278. self.fields = tmp
  279. end
  280. def save_with_optional_media!
  281. save!
  282. rescue ActiveRecord::RecordInvalid
  283. self.avatar = nil
  284. self.header = nil
  285. save!
  286. end
  287. def hides_followers?
  288. hide_collections? || user_hides_network?
  289. end
  290. def hides_following?
  291. hide_collections? || user_hides_network?
  292. end
  293. def object_type
  294. :person
  295. end
  296. def to_param
  297. username
  298. end
  299. def excluded_from_timeline_account_ids
  300. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  301. end
  302. def excluded_from_timeline_domains
  303. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  304. end
  305. def preferred_inbox_url
  306. shared_inbox_url.presence || inbox_url
  307. end
  308. def synchronization_uri_prefix
  309. return 'local' if local?
  310. @synchronization_uri_prefix ||= uri[/http(s?):\/\/[^\/]+\//]
  311. end
  312. class Field < ActiveModelSerializers::Model
  313. attributes :name, :value, :verified_at, :account
  314. def initialize(account, attributes)
  315. @original_field = attributes
  316. string_limit = account.local? ? 255 : 2047
  317. super(
  318. account: account,
  319. name: attributes['name'].strip[0, string_limit],
  320. value: attributes['value'].strip[0, string_limit],
  321. verified_at: attributes['verified_at']&.to_datetime,
  322. )
  323. end
  324. def verified?
  325. verified_at.present?
  326. end
  327. def value_for_verification
  328. @value_for_verification ||= begin
  329. if account.local?
  330. value
  331. else
  332. ActionController::Base.helpers.strip_tags(value)
  333. end
  334. end
  335. end
  336. def verifiable?
  337. value_for_verification.present? && value_for_verification.start_with?('http://', 'https://')
  338. end
  339. def mark_verified!
  340. self.verified_at = Time.now.utc
  341. @original_field['verified_at'] = verified_at
  342. end
  343. def to_h
  344. { name: name, value: value, verified_at: verified_at }
  345. end
  346. end
  347. class << self
  348. def readonly_attributes
  349. super - %w(statuses_count following_count followers_count)
  350. end
  351. def inboxes
  352. urls = reorder(nil).where(protocol: :activitypub).group(:preferred_inbox_url).pluck(Arel.sql("coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url) AS preferred_inbox_url"))
  353. DeliveryFailureTracker.without_unavailable(urls)
  354. end
  355. def search_for(terms, limit = 10, offset = 0)
  356. textsearch, query = generate_query_for_search(terms)
  357. sql = <<-SQL.squish
  358. SELECT
  359. accounts.*,
  360. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  361. FROM accounts
  362. WHERE #{query} @@ #{textsearch}
  363. AND accounts.suspended_at IS NULL
  364. AND accounts.moved_to_account_id IS NULL
  365. ORDER BY rank DESC
  366. LIMIT ? OFFSET ?
  367. SQL
  368. records = find_by_sql([sql, limit, offset])
  369. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  370. records
  371. end
  372. def advanced_search_for(terms, account, limit = 10, following = false, offset = 0)
  373. textsearch, query = generate_query_for_search(terms)
  374. if following
  375. sql = <<-SQL.squish
  376. WITH first_degree AS (
  377. SELECT target_account_id
  378. FROM follows
  379. WHERE account_id = ?
  380. UNION ALL
  381. SELECT ?
  382. )
  383. SELECT
  384. accounts.*,
  385. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  386. FROM accounts
  387. LEFT OUTER JOIN follows AS f ON (accounts.id = f.account_id AND f.target_account_id = ?)
  388. WHERE accounts.id IN (SELECT * FROM first_degree)
  389. AND #{query} @@ #{textsearch}
  390. AND accounts.suspended_at IS NULL
  391. AND accounts.moved_to_account_id IS NULL
  392. GROUP BY accounts.id
  393. ORDER BY rank DESC
  394. LIMIT ? OFFSET ?
  395. SQL
  396. records = find_by_sql([sql, account.id, account.id, account.id, limit, offset])
  397. else
  398. sql = <<-SQL.squish
  399. SELECT
  400. accounts.*,
  401. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  402. FROM accounts
  403. 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 = ?)
  404. WHERE #{query} @@ #{textsearch}
  405. AND accounts.suspended_at IS NULL
  406. AND accounts.moved_to_account_id IS NULL
  407. GROUP BY accounts.id
  408. ORDER BY rank DESC
  409. LIMIT ? OFFSET ?
  410. SQL
  411. records = find_by_sql([sql, account.id, account.id, limit, offset])
  412. end
  413. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  414. records
  415. end
  416. def from_text(text)
  417. return [] if text.blank?
  418. text.scan(MENTION_RE).map { |match| match.first.split('@', 2) }.uniq.filter_map do |(username, domain)|
  419. domain = begin
  420. if TagManager.instance.local_domain?(domain)
  421. nil
  422. else
  423. TagManager.instance.normalize_domain(domain)
  424. end
  425. end
  426. EntityCache.instance.mention(username, domain)
  427. end
  428. end
  429. private
  430. def generate_query_for_search(terms)
  431. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  432. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  433. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  434. [textsearch, query]
  435. end
  436. end
  437. def emojis
  438. @emojis ||= CustomEmoji.from_text(emojifiable_text, domain)
  439. end
  440. before_create :generate_keys
  441. before_validation :prepare_contents, if: :local?
  442. before_validation :prepare_username, on: :create
  443. before_destroy :clean_feed_manager
  444. private
  445. def prepare_contents
  446. display_name&.strip!
  447. note&.strip!
  448. end
  449. def prepare_username
  450. username&.squish!
  451. end
  452. def generate_keys
  453. return unless local? && private_key.blank? && public_key.blank?
  454. keypair = OpenSSL::PKey::RSA.new(2048)
  455. self.private_key = keypair.to_pem
  456. self.public_key = keypair.public_key.to_pem
  457. end
  458. def normalize_domain
  459. return if local?
  460. super
  461. end
  462. def emojifiable_text
  463. [note, display_name, fields.map(&:name), fields.map(&:value)].join(' ')
  464. end
  465. def clean_feed_manager
  466. FeedManager.instance.clean_feeds!(:home, [id])
  467. end
  468. end