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.

581 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. # private_key :text
  10. # public_key :text default(""), not null
  11. # created_at :datetime not null
  12. # updated_at :datetime not null
  13. # note :text default(""), not null
  14. # display_name :string default(""), not null
  15. # uri :string default(""), not null
  16. # url :string
  17. # avatar_file_name :string
  18. # avatar_content_type :string
  19. # avatar_file_size :integer
  20. # avatar_updated_at :datetime
  21. # header_file_name :string
  22. # header_content_type :string
  23. # header_file_size :integer
  24. # header_updated_at :datetime
  25. # avatar_remote_url :string
  26. # locked :boolean default(FALSE), not null
  27. # header_remote_url :string default(""), not null
  28. # last_webfingered_at :datetime
  29. # inbox_url :string default(""), not null
  30. # outbox_url :string default(""), not null
  31. # shared_inbox_url :string default(""), not null
  32. # followers_url :string default(""), not null
  33. # protocol :integer default("ostatus"), not null
  34. # memorial :boolean default(FALSE), not null
  35. # moved_to_account_id :bigint(8)
  36. # featured_collection_url :string
  37. # fields :jsonb
  38. # actor_type :string
  39. # discoverable :boolean
  40. # also_known_as :string is an Array
  41. # silenced_at :datetime
  42. # suspended_at :datetime
  43. # trust_level :integer
  44. # hide_collections :boolean
  45. # avatar_storage_schema_version :integer
  46. # header_storage_schema_version :integer
  47. # devices_url :string
  48. # suspension_origin :integer
  49. # sensitized_at :datetime
  50. #
  51. class Account < ApplicationRecord
  52. self.ignored_columns = %w(
  53. subscription_expires_at
  54. secret
  55. remote_url
  56. salmon_url
  57. hub_url
  58. )
  59. USERNAME_RE = /[a-z0-9_]+([a-z0-9_\.-]+[a-z0-9_]+)?/i
  60. MENTION_RE = /(?<=^|[^\/[:word:]])@((#{USERNAME_RE})(?:@[[:word:]\.\-]+[a-z0-9]+)?)/i
  61. include AccountAssociations
  62. include AccountAvatar
  63. include AccountFinderConcern
  64. include AccountHeader
  65. include AccountInteractions
  66. include Attachmentable
  67. include Paginable
  68. include AccountCounters
  69. include DomainNormalizable
  70. include DomainMaterializable
  71. include AccountMerging
  72. TRUST_LEVELS = {
  73. untrusted: 0,
  74. trusted: 1,
  75. }.freeze
  76. enum protocol: [:ostatus, :activitypub]
  77. enum suspension_origin: [:local, :remote], _prefix: true
  78. validates :username, presence: true
  79. validates_with UniqueUsernameValidator, if: -> { will_save_change_to_username? }
  80. # Remote user validations
  81. validates :username, format: { with: /\A#{USERNAME_RE}\z/i }, if: -> { !local? && will_save_change_to_username? }
  82. # Local user validations
  83. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, length: { maximum: 30 }, if: -> { local? && will_save_change_to_username? && actor_type != 'Application' }
  84. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? }
  85. validates :display_name, length: { maximum: 30 }, if: -> { local? && will_save_change_to_display_name? }
  86. validates :note, note_length: { maximum: 500 }, if: -> { local? && will_save_change_to_note? }
  87. validates :fields, length: { maximum: 4 }, if: -> { local? && will_save_change_to_fields? }
  88. scope :remote, -> { where.not(domain: nil) }
  89. scope :local, -> { where(domain: nil) }
  90. scope :partitioned, -> { order(Arel.sql('row_number() over (partition by domain)')) }
  91. scope :silenced, -> { where.not(silenced_at: nil) }
  92. scope :suspended, -> { where.not(suspended_at: nil) }
  93. scope :sensitized, -> { where.not(sensitized_at: nil) }
  94. scope :without_suspended, -> { where(suspended_at: nil) }
  95. scope :without_silenced, -> { where(silenced_at: nil) }
  96. scope :without_instance_actor, -> { where.not(id: -99) }
  97. scope :recent, -> { reorder(id: :desc) }
  98. scope :bots, -> { where(actor_type: %w(Application Service)) }
  99. scope :groups, -> { where(actor_type: 'Group') }
  100. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  101. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  102. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  103. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  104. scope :searchable, -> { without_suspended.where(moved_to_account_id: nil) }
  105. scope :discoverable, -> { searchable.without_silenced.where(discoverable: true).left_outer_joins(:account_stat) }
  106. scope :followable_by, ->(account) { joins(arel_table.join(Follow.arel_table, Arel::Nodes::OuterJoin).on(arel_table[:id].eq(Follow.arel_table[:target_account_id]).and(Follow.arel_table[:account_id].eq(account.id))).join_sources).where(Follow.arel_table[:id].eq(nil)).joins(arel_table.join(FollowRequest.arel_table, Arel::Nodes::OuterJoin).on(arel_table[:id].eq(FollowRequest.arel_table[:target_account_id]).and(FollowRequest.arel_table[:account_id].eq(account.id))).join_sources).where(FollowRequest.arel_table[:id].eq(nil)) }
  107. 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')) }
  108. 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')) }
  109. scope :popular, -> { order('account_stats.followers_count desc') }
  110. scope :by_domain_and_subdomains, ->(domain) { where(domain: domain).or(where(arel_table[:domain].matches('%.' + domain))) }
  111. scope :not_excluded_by_account, ->(account) { where.not(id: account.excluded_from_timeline_account_ids) }
  112. scope :not_domain_blocked_by_account, ->(account) { where(arel_table[:domain].eq(nil).or(arel_table[:domain].not_in(account.excluded_from_timeline_domains))) }
  113. delegate :email,
  114. :unconfirmed_email,
  115. :current_sign_in_ip,
  116. :current_sign_in_at,
  117. :confirmed?,
  118. :approved?,
  119. :pending?,
  120. :disabled?,
  121. :unconfirmed_or_pending?,
  122. :role,
  123. :admin?,
  124. :moderator?,
  125. :staff?,
  126. :locale,
  127. :hides_network?,
  128. :shows_application?,
  129. to: :user,
  130. prefix: true,
  131. allow_nil: true
  132. delegate :chosen_languages, to: :user, prefix: false, allow_nil: true
  133. update_index('accounts#account', :self)
  134. def local?
  135. domain.nil?
  136. end
  137. def moved?
  138. moved_to_account_id.present?
  139. end
  140. def bot?
  141. %w(Application Service).include? actor_type
  142. end
  143. def instance_actor?
  144. id == -99
  145. end
  146. alias bot bot?
  147. def bot=(val)
  148. self.actor_type = ActiveModel::Type::Boolean.new.cast(val) ? 'Service' : 'Person'
  149. end
  150. def group?
  151. actor_type == 'Group'
  152. end
  153. alias group group?
  154. def acct
  155. local? ? username : "#{username}@#{domain}"
  156. end
  157. def pretty_acct
  158. local? ? username : "#{username}@#{Addressable::IDNA.to_unicode(domain)}"
  159. end
  160. def local_username_and_domain
  161. "#{username}@#{Rails.configuration.x.local_domain}"
  162. end
  163. def local_followers_count
  164. Follow.where(target_account_id: id).count
  165. end
  166. def to_webfinger_s
  167. "acct:#{local_username_and_domain}"
  168. end
  169. def searchable?
  170. !(suspended? || moved?)
  171. end
  172. def possibly_stale?
  173. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  174. end
  175. def trust_level
  176. self[:trust_level] || 0
  177. end
  178. def refresh!
  179. ResolveAccountService.new.call(acct) unless local?
  180. end
  181. def silenced?
  182. silenced_at.present?
  183. end
  184. def silence!(date = Time.now.utc)
  185. update!(silenced_at: date)
  186. end
  187. def unsilence!
  188. update!(silenced_at: nil)
  189. end
  190. def suspended?
  191. suspended_at.present? && !instance_actor?
  192. end
  193. def suspended_permanently?
  194. suspended? && deletion_request.nil?
  195. end
  196. def suspended_temporarily?
  197. suspended? && deletion_request.present?
  198. end
  199. def suspend!(date: Time.now.utc, origin: :local)
  200. transaction do
  201. create_deletion_request!
  202. update!(suspended_at: date, suspension_origin: origin)
  203. create_canonical_email_block!
  204. end
  205. end
  206. def unsuspend!
  207. transaction do
  208. deletion_request&.destroy!
  209. update!(suspended_at: nil, suspension_origin: nil)
  210. destroy_canonical_email_block!
  211. end
  212. end
  213. def sensitized?
  214. sensitized_at.present?
  215. end
  216. def sensitize!(date = Time.now.utc)
  217. update!(sensitized_at: date)
  218. end
  219. def unsensitize!
  220. update!(sensitized_at: nil)
  221. end
  222. def memorialize!
  223. update!(memorial: true)
  224. end
  225. def sign?
  226. true
  227. end
  228. def keypair
  229. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  230. end
  231. def tags_as_strings=(tag_names)
  232. hashtags_map = Tag.find_or_create_by_names(tag_names).index_by(&:name)
  233. # Remove hashtags that are to be deleted
  234. tags.each do |tag|
  235. if hashtags_map.key?(tag.name)
  236. hashtags_map.delete(tag.name)
  237. else
  238. tags.delete(tag)
  239. end
  240. end
  241. # Add hashtags that were so far missing
  242. hashtags_map.each_value do |tag|
  243. tags << tag
  244. end
  245. end
  246. def also_known_as
  247. self[:also_known_as] || []
  248. end
  249. def fields
  250. (self[:fields] || []).map { |f| Field.new(self, f) }
  251. end
  252. def fields_attributes=(attributes)
  253. fields = []
  254. old_fields = self[:fields] || []
  255. old_fields = [] if old_fields.is_a?(Hash)
  256. if attributes.is_a?(Hash)
  257. attributes.each_value do |attr|
  258. next if attr[:name].blank?
  259. previous = old_fields.find { |item| item['value'] == attr[:value] }
  260. if previous && previous['verified_at'].present?
  261. attr[:verified_at] = previous['verified_at']
  262. end
  263. fields << attr
  264. end
  265. end
  266. self[:fields] = fields
  267. end
  268. DEFAULT_FIELDS_SIZE = 4
  269. def build_fields
  270. return if fields.size >= DEFAULT_FIELDS_SIZE
  271. tmp = self[:fields] || []
  272. tmp = [] if tmp.is_a?(Hash)
  273. (DEFAULT_FIELDS_SIZE - tmp.size).times do
  274. tmp << { name: '', value: '' }
  275. end
  276. self.fields = tmp
  277. end
  278. def save_with_optional_media!
  279. save!
  280. rescue ActiveRecord::RecordInvalid
  281. self.avatar = nil
  282. self.header = nil
  283. save!
  284. end
  285. def hides_followers?
  286. hide_collections? || user_hides_network?
  287. end
  288. def hides_following?
  289. hide_collections? || user_hides_network?
  290. end
  291. def object_type
  292. :person
  293. end
  294. def to_param
  295. username
  296. end
  297. def excluded_from_timeline_account_ids
  298. Rails.cache.fetch("exclude_account_ids_for:#{id}") { block_relationships.pluck(:target_account_id) + blocked_by_relationships.pluck(:account_id) + mute_relationships.pluck(:target_account_id) }
  299. end
  300. def excluded_from_timeline_domains
  301. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  302. end
  303. def preferred_inbox_url
  304. shared_inbox_url.presence || inbox_url
  305. end
  306. def synchronization_uri_prefix
  307. return 'local' if local?
  308. @synchronization_uri_prefix ||= uri[/http(s?):\/\/[^\/]+\//]
  309. end
  310. class Field < ActiveModelSerializers::Model
  311. attributes :name, :value, :verified_at, :account
  312. def initialize(account, attributes)
  313. @original_field = attributes
  314. string_limit = account.local? ? 255 : 2047
  315. super(
  316. account: account,
  317. name: attributes['name'].strip[0, string_limit],
  318. value: attributes['value'].strip[0, string_limit],
  319. verified_at: attributes['verified_at']&.to_datetime,
  320. )
  321. end
  322. def verified?
  323. verified_at.present?
  324. end
  325. def value_for_verification
  326. @value_for_verification ||= begin
  327. if account.local?
  328. value
  329. else
  330. ActionController::Base.helpers.strip_tags(value)
  331. end
  332. end
  333. end
  334. def verifiable?
  335. value_for_verification.present? && value_for_verification.start_with?('http://', 'https://')
  336. end
  337. def mark_verified!
  338. self.verified_at = Time.now.utc
  339. @original_field['verified_at'] = verified_at
  340. end
  341. def to_h
  342. { name: name, value: value, verified_at: verified_at }
  343. end
  344. end
  345. class << self
  346. def readonly_attributes
  347. super - %w(statuses_count following_count followers_count)
  348. end
  349. def inboxes
  350. 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"))
  351. DeliveryFailureTracker.without_unavailable(urls)
  352. end
  353. def search_for(terms, limit = 10, offset = 0)
  354. textsearch, query = generate_query_for_search(terms)
  355. sql = <<-SQL.squish
  356. SELECT
  357. accounts.*,
  358. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  359. FROM accounts
  360. WHERE #{query} @@ #{textsearch}
  361. AND accounts.suspended_at IS NULL
  362. AND accounts.moved_to_account_id IS NULL
  363. ORDER BY rank DESC
  364. LIMIT ? OFFSET ?
  365. SQL
  366. records = find_by_sql([sql, limit, offset])
  367. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  368. records
  369. end
  370. def advanced_search_for(terms, account, limit = 10, following = false, offset = 0)
  371. textsearch, query = generate_query_for_search(terms)
  372. if following
  373. sql = <<-SQL.squish
  374. WITH first_degree AS (
  375. SELECT target_account_id
  376. FROM follows
  377. WHERE account_id = ?
  378. UNION ALL
  379. SELECT ?
  380. )
  381. SELECT
  382. accounts.*,
  383. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  384. FROM accounts
  385. LEFT OUTER JOIN follows AS f ON (accounts.id = f.account_id AND f.target_account_id = ?)
  386. WHERE accounts.id IN (SELECT * FROM first_degree)
  387. AND #{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, account.id, limit, offset])
  395. else
  396. sql = <<-SQL.squish
  397. SELECT
  398. accounts.*,
  399. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  400. FROM accounts
  401. 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 = ?)
  402. WHERE #{query} @@ #{textsearch}
  403. AND accounts.suspended_at IS NULL
  404. AND accounts.moved_to_account_id IS NULL
  405. GROUP BY accounts.id
  406. ORDER BY rank DESC
  407. LIMIT ? OFFSET ?
  408. SQL
  409. records = find_by_sql([sql, account.id, account.id, limit, offset])
  410. end
  411. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  412. records
  413. end
  414. def from_text(text)
  415. return [] if text.blank?
  416. text.scan(MENTION_RE).map { |match| match.first.split('@', 2) }.uniq.filter_map do |(username, domain)|
  417. domain = begin
  418. if TagManager.instance.local_domain?(domain)
  419. nil
  420. else
  421. TagManager.instance.normalize_domain(domain)
  422. end
  423. end
  424. EntityCache.instance.mention(username, domain)
  425. end
  426. end
  427. private
  428. def generate_query_for_search(terms)
  429. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  430. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  431. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  432. [textsearch, query]
  433. end
  434. end
  435. def emojis
  436. @emojis ||= CustomEmoji.from_text(emojifiable_text, domain)
  437. end
  438. before_create :generate_keys
  439. before_validation :prepare_contents, if: :local?
  440. before_validation :prepare_username, on: :create
  441. before_destroy :clean_feed_manager
  442. private
  443. def prepare_contents
  444. display_name&.strip!
  445. note&.strip!
  446. end
  447. def prepare_username
  448. username&.squish!
  449. end
  450. def generate_keys
  451. return unless local? && private_key.blank? && public_key.blank?
  452. keypair = OpenSSL::PKey::RSA.new(2048)
  453. self.private_key = keypair.to_pem
  454. self.public_key = keypair.public_key.to_pem
  455. end
  456. def normalize_domain
  457. return if local?
  458. super
  459. end
  460. def emojifiable_text
  461. [note, display_name, fields.map(&:name), fields.map(&:value)].join(' ')
  462. end
  463. def clean_feed_manager
  464. FeedManager.instance.clean_feeds!(:home, [id])
  465. end
  466. def create_canonical_email_block!
  467. return unless local? && user_email.present?
  468. CanonicalEmailBlock.create(reference_account: self, email: user_email)
  469. end
  470. def destroy_canonical_email_block!
  471. return unless local?
  472. CanonicalEmailBlock.where(reference_account: self).delete_all
  473. end
  474. end