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.

572 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 :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)) }
  105. scope :tagged_with, ->(tag) { joins(:accounts_tags).where(accounts_tags: { tag_id: tag }) }
  106. 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')) }
  107. 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')) }
  108. scope :popular, -> { order('account_stats.followers_count desc') }
  109. scope :by_domain_and_subdomains, ->(domain) { where(domain: domain).or(where(arel_table[:domain].matches('%.' + domain))) }
  110. scope :not_excluded_by_account, ->(account) { where.not(id: account.excluded_from_timeline_account_ids) }
  111. scope :not_domain_blocked_by_account, ->(account) { where(arel_table[:domain].eq(nil).or(arel_table[:domain].not_in(account.excluded_from_timeline_domains))) }
  112. delegate :email,
  113. :unconfirmed_email,
  114. :current_sign_in_ip,
  115. :current_sign_in_at,
  116. :confirmed?,
  117. :approved?,
  118. :pending?,
  119. :disabled?,
  120. :unconfirmed_or_pending?,
  121. :role,
  122. :admin?,
  123. :moderator?,
  124. :staff?,
  125. :locale,
  126. :hides_network?,
  127. :shows_application?,
  128. to: :user,
  129. prefix: true,
  130. allow_nil: true
  131. delegate :chosen_languages, to: :user, prefix: false, allow_nil: true
  132. update_index('accounts#account', :self)
  133. def local?
  134. domain.nil?
  135. end
  136. def moved?
  137. moved_to_account_id.present?
  138. end
  139. def bot?
  140. %w(Application Service).include? actor_type
  141. end
  142. def instance_actor?
  143. id == -99
  144. end
  145. alias bot bot?
  146. def bot=(val)
  147. self.actor_type = ActiveModel::Type::Boolean.new.cast(val) ? 'Service' : 'Person'
  148. end
  149. def group?
  150. actor_type == 'Group'
  151. end
  152. alias group group?
  153. def acct
  154. local? ? username : "#{username}@#{domain}"
  155. end
  156. def pretty_acct
  157. local? ? username : "#{username}@#{Addressable::IDNA.to_unicode(domain)}"
  158. end
  159. def local_username_and_domain
  160. "#{username}@#{Rails.configuration.x.local_domain}"
  161. end
  162. def local_followers_count
  163. Follow.where(target_account_id: id).count
  164. end
  165. def to_webfinger_s
  166. "acct:#{local_username_and_domain}"
  167. end
  168. def searchable?
  169. !(suspended? || moved?)
  170. end
  171. def possibly_stale?
  172. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  173. end
  174. def trust_level
  175. self[:trust_level] || 0
  176. end
  177. def refresh!
  178. ResolveAccountService.new.call(acct) unless local?
  179. end
  180. def silenced?
  181. silenced_at.present?
  182. end
  183. def silence!(date = Time.now.utc)
  184. update!(silenced_at: date)
  185. end
  186. def unsilence!
  187. update!(silenced_at: nil)
  188. end
  189. def suspended?
  190. suspended_at.present? && !instance_actor?
  191. end
  192. def suspended_permanently?
  193. suspended? && deletion_request.nil?
  194. end
  195. def suspended_temporarily?
  196. suspended? && deletion_request.present?
  197. end
  198. def suspend!(date: Time.now.utc, origin: :local)
  199. transaction do
  200. create_deletion_request!
  201. update!(suspended_at: date, suspension_origin: origin)
  202. end
  203. end
  204. def unsuspend!
  205. transaction do
  206. deletion_request&.destroy!
  207. update!(suspended_at: nil, suspension_origin: nil)
  208. end
  209. end
  210. def sensitized?
  211. sensitized_at.present?
  212. end
  213. def sensitize!(date = Time.now.utc)
  214. update!(sensitized_at: date)
  215. end
  216. def unsensitize!
  217. update!(sensitized_at: nil)
  218. end
  219. def memorialize!
  220. update!(memorial: true)
  221. end
  222. def sign?
  223. true
  224. end
  225. def keypair
  226. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  227. end
  228. def tags_as_strings=(tag_names)
  229. hashtags_map = Tag.find_or_create_by_names(tag_names).index_by(&:name)
  230. # Remove hashtags that are to be deleted
  231. tags.each do |tag|
  232. if hashtags_map.key?(tag.name)
  233. hashtags_map.delete(tag.name)
  234. else
  235. transaction do
  236. tags.delete(tag)
  237. tag.decrement_count!(:accounts_count)
  238. end
  239. end
  240. end
  241. # Add hashtags that were so far missing
  242. hashtags_map.each_value do |tag|
  243. transaction do
  244. tags << tag
  245. tag.increment_count!(:accounts_count)
  246. end
  247. end
  248. end
  249. def also_known_as
  250. self[:also_known_as] || []
  251. end
  252. def fields
  253. (self[:fields] || []).map { |f| Field.new(self, f) }
  254. end
  255. def fields_attributes=(attributes)
  256. fields = []
  257. old_fields = self[:fields] || []
  258. old_fields = [] if old_fields.is_a?(Hash)
  259. if attributes.is_a?(Hash)
  260. attributes.each_value do |attr|
  261. next if attr[:name].blank?
  262. previous = old_fields.find { |item| item['value'] == attr[:value] }
  263. if previous && previous['verified_at'].present?
  264. attr[:verified_at] = previous['verified_at']
  265. end
  266. fields << attr
  267. end
  268. end
  269. self[:fields] = fields
  270. end
  271. DEFAULT_FIELDS_SIZE = 4
  272. def build_fields
  273. return if fields.size >= DEFAULT_FIELDS_SIZE
  274. tmp = self[:fields] || []
  275. tmp = [] if tmp.is_a?(Hash)
  276. (DEFAULT_FIELDS_SIZE - tmp.size).times do
  277. tmp << { name: '', value: '' }
  278. end
  279. self.fields = tmp
  280. end
  281. def save_with_optional_media!
  282. save!
  283. rescue ActiveRecord::RecordInvalid
  284. self.avatar = nil
  285. self.header = nil
  286. save!
  287. end
  288. def hides_followers?
  289. hide_collections? || user_hides_network?
  290. end
  291. def hides_following?
  292. hide_collections? || user_hides_network?
  293. end
  294. def object_type
  295. :person
  296. end
  297. def to_param
  298. username
  299. end
  300. def excluded_from_timeline_account_ids
  301. 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) }
  302. end
  303. def excluded_from_timeline_domains
  304. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  305. end
  306. def preferred_inbox_url
  307. shared_inbox_url.presence || inbox_url
  308. end
  309. def synchronization_uri_prefix
  310. return 'local' if local?
  311. @synchronization_uri_prefix ||= uri[/http(s?):\/\/[^\/]+\//]
  312. end
  313. class Field < ActiveModelSerializers::Model
  314. attributes :name, :value, :verified_at, :account
  315. def initialize(account, attributes)
  316. @original_field = attributes
  317. string_limit = account.local? ? 255 : 2047
  318. super(
  319. account: account,
  320. name: attributes['name'].strip[0, string_limit],
  321. value: attributes['value'].strip[0, string_limit],
  322. verified_at: attributes['verified_at']&.to_datetime,
  323. )
  324. end
  325. def verified?
  326. verified_at.present?
  327. end
  328. def value_for_verification
  329. @value_for_verification ||= begin
  330. if account.local?
  331. value
  332. else
  333. ActionController::Base.helpers.strip_tags(value)
  334. end
  335. end
  336. end
  337. def verifiable?
  338. value_for_verification.present? && value_for_verification.start_with?('http://', 'https://')
  339. end
  340. def mark_verified!
  341. self.verified_at = Time.now.utc
  342. @original_field['verified_at'] = verified_at
  343. end
  344. def to_h
  345. { name: name, value: value, verified_at: verified_at }
  346. end
  347. end
  348. class << self
  349. def readonly_attributes
  350. super - %w(statuses_count following_count followers_count)
  351. end
  352. def inboxes
  353. 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"))
  354. DeliveryFailureTracker.without_unavailable(urls)
  355. end
  356. def search_for(terms, limit = 10, offset = 0)
  357. textsearch, query = generate_query_for_search(terms)
  358. sql = <<-SQL.squish
  359. SELECT
  360. accounts.*,
  361. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  362. FROM accounts
  363. WHERE #{query} @@ #{textsearch}
  364. AND accounts.suspended_at IS NULL
  365. AND accounts.moved_to_account_id IS NULL
  366. ORDER BY rank DESC
  367. LIMIT ? OFFSET ?
  368. SQL
  369. records = find_by_sql([sql, limit, offset])
  370. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  371. records
  372. end
  373. def advanced_search_for(terms, account, limit = 10, following = false, offset = 0)
  374. textsearch, query = generate_query_for_search(terms)
  375. if following
  376. sql = <<-SQL.squish
  377. WITH first_degree AS (
  378. SELECT target_account_id
  379. FROM follows
  380. WHERE account_id = ?
  381. UNION ALL
  382. SELECT ?
  383. )
  384. SELECT
  385. accounts.*,
  386. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  387. FROM accounts
  388. LEFT OUTER JOIN follows AS f ON (accounts.id = f.account_id AND f.target_account_id = ?)
  389. WHERE accounts.id IN (SELECT * FROM first_degree)
  390. AND #{query} @@ #{textsearch}
  391. AND accounts.suspended_at IS NULL
  392. AND accounts.moved_to_account_id IS NULL
  393. GROUP BY accounts.id
  394. ORDER BY rank DESC
  395. LIMIT ? OFFSET ?
  396. SQL
  397. records = find_by_sql([sql, account.id, account.id, account.id, limit, offset])
  398. else
  399. sql = <<-SQL.squish
  400. SELECT
  401. accounts.*,
  402. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  403. FROM accounts
  404. 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 = ?)
  405. WHERE #{query} @@ #{textsearch}
  406. AND accounts.suspended_at IS NULL
  407. AND accounts.moved_to_account_id IS NULL
  408. GROUP BY accounts.id
  409. ORDER BY rank DESC
  410. LIMIT ? OFFSET ?
  411. SQL
  412. records = find_by_sql([sql, account.id, account.id, limit, offset])
  413. end
  414. ActiveRecord::Associations::Preloader.new.preload(records, :account_stat)
  415. records
  416. end
  417. def from_text(text)
  418. return [] if text.blank?
  419. text.scan(MENTION_RE).map { |match| match.first.split('@', 2) }.uniq.filter_map do |(username, domain)|
  420. domain = begin
  421. if TagManager.instance.local_domain?(domain)
  422. nil
  423. else
  424. TagManager.instance.normalize_domain(domain)
  425. end
  426. end
  427. EntityCache.instance.mention(username, domain)
  428. end
  429. end
  430. private
  431. def generate_query_for_search(terms)
  432. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  433. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  434. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  435. [textsearch, query]
  436. end
  437. end
  438. def emojis
  439. @emojis ||= CustomEmoji.from_text(emojifiable_text, domain)
  440. end
  441. before_create :generate_keys
  442. before_validation :prepare_contents, if: :local?
  443. before_validation :prepare_username, on: :create
  444. before_destroy :clean_feed_manager
  445. private
  446. def prepare_contents
  447. display_name&.strip!
  448. note&.strip!
  449. end
  450. def prepare_username
  451. username&.squish!
  452. end
  453. def generate_keys
  454. return unless local? && private_key.blank? && public_key.blank?
  455. keypair = OpenSSL::PKey::RSA.new(2048)
  456. self.private_key = keypair.to_pem
  457. self.public_key = keypair.public_key.to_pem
  458. end
  459. def normalize_domain
  460. return if local?
  461. super
  462. end
  463. def emojifiable_text
  464. [note, display_name, fields.map(&:name), fields.map(&:value)].join(' ')
  465. end
  466. def clean_feed_manager
  467. FeedManager.instance.clean_feeds!(:home, [id])
  468. end
  469. end