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.

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