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.

463 lines
14 KiB

Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 years ago
Fix Account model deprecation warnings (#3689) ``` DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:61) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:62) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:63) ``` Here's PR describing changes to Dirty API https://github.com/rails/rails/pull/25337
7 years ago
Fix Account model deprecation warnings (#3689) ``` DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:61) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:62) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:63) ``` Here's PR describing changes to Dirty API https://github.com/rails/rails/pull/25337
7 years ago
8 years ago
8 years ago
8 years ago
Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 years ago
8 years ago
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: accounts
  5. #
  6. # id :bigint(8) not null, primary key
  7. # username :string default(""), not null
  8. # domain :string
  9. # secret :string default(""), not null
  10. # private_key :text
  11. # public_key :text default(""), not null
  12. # remote_url :string default(""), not null
  13. # salmon_url :string default(""), not null
  14. # hub_url :string default(""), not null
  15. # created_at :datetime not null
  16. # updated_at :datetime not null
  17. # note :text default(""), not null
  18. # display_name :string default(""), not null
  19. # uri :string default(""), not null
  20. # url :string
  21. # avatar_file_name :string
  22. # avatar_content_type :string
  23. # avatar_file_size :integer
  24. # avatar_updated_at :datetime
  25. # header_file_name :string
  26. # header_content_type :string
  27. # header_file_size :integer
  28. # header_updated_at :datetime
  29. # avatar_remote_url :string
  30. # subscription_expires_at :datetime
  31. # silenced :boolean default(FALSE), not null
  32. # suspended :boolean default(FALSE), not null
  33. # locked :boolean default(FALSE), not null
  34. # header_remote_url :string default(""), not null
  35. # statuses_count :integer default(0), not null
  36. # followers_count :integer default(0), not null
  37. # following_count :integer default(0), not null
  38. # last_webfingered_at :datetime
  39. # inbox_url :string default(""), not null
  40. # outbox_url :string default(""), not null
  41. # shared_inbox_url :string default(""), not null
  42. # followers_url :string default(""), not null
  43. # protocol :integer default("ostatus"), not null
  44. # memorial :boolean default(FALSE), not null
  45. # moved_to_account_id :bigint(8)
  46. # featured_collection_url :string
  47. # fields :jsonb
  48. # actor_type :string
  49. #
  50. class Account < ApplicationRecord
  51. USERNAME_RE = /[a-z0-9_]+([a-z0-9_\.]+[a-z0-9_]+)?/i
  52. MENTION_RE = /(?<=^|[^\/[:word:]])@((#{USERNAME_RE})(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  53. include AccountAvatar
  54. include AccountFinderConcern
  55. include AccountHeader
  56. include AccountInteractions
  57. include Attachmentable
  58. include Paginable
  59. MAX_NOTE_LENGTH = 500
  60. enum protocol: [:ostatus, :activitypub]
  61. # Local users
  62. has_one :user, inverse_of: :account
  63. validates :username, presence: true
  64. # Remote user validations
  65. validates :username, uniqueness: { scope: :domain, case_sensitive: true }, if: -> { !local? && will_save_change_to_username? }
  66. # Local user validations
  67. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, length: { maximum: 30 }, if: -> { local? && will_save_change_to_username? }
  68. validates_with UniqueUsernameValidator, if: -> { local? && will_save_change_to_username? }
  69. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? }
  70. validates :display_name, length: { maximum: 30 }, if: -> { local? && will_save_change_to_display_name? }
  71. validate :note_length_does_not_exceed_length_limit, if: -> { local? && will_save_change_to_note? }
  72. validates :fields, length: { maximum: 4 }, if: -> { local? && will_save_change_to_fields? }
  73. # Timelines
  74. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  75. has_many :statuses, inverse_of: :account, dependent: :destroy
  76. has_many :favourites, inverse_of: :account, dependent: :destroy
  77. has_many :bookmarks, inverse_of: :account, dependent: :destroy
  78. has_many :mentions, inverse_of: :account, dependent: :destroy
  79. has_many :notifications, inverse_of: :account, dependent: :destroy
  80. # Pinned statuses
  81. has_many :status_pins, inverse_of: :account, dependent: :destroy
  82. has_many :pinned_statuses, -> { reorder('status_pins.created_at DESC') }, through: :status_pins, class_name: 'Status', source: :status
  83. # Media
  84. has_many :media_attachments, dependent: :destroy
  85. # PuSH subscriptions
  86. has_many :subscriptions, dependent: :destroy
  87. # Report relationships
  88. has_many :reports
  89. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  90. has_many :report_notes, dependent: :destroy
  91. # Moderation notes
  92. has_many :account_moderation_notes, dependent: :destroy
  93. has_many :targeted_moderation_notes, class_name: 'AccountModerationNote', foreign_key: :target_account_id, dependent: :destroy
  94. # Lists
  95. has_many :list_accounts, inverse_of: :account, dependent: :destroy
  96. has_many :lists, through: :list_accounts
  97. # Account migrations
  98. belongs_to :moved_to_account, class_name: 'Account', optional: true
  99. scope :remote, -> { where.not(domain: nil) }
  100. scope :local, -> { where(domain: nil) }
  101. scope :without_followers, -> { where(followers_count: 0) }
  102. scope :with_followers, -> { where('followers_count > 0') }
  103. scope :expiring, ->(time) { remote.where.not(subscription_expires_at: nil).where('subscription_expires_at < ?', time) }
  104. scope :partitioned, -> { order(Arel.sql('row_number() over (partition by domain)')) }
  105. scope :silenced, -> { where(silenced: true) }
  106. scope :suspended, -> { where(suspended: true) }
  107. scope :without_suspended, -> { where(suspended: false) }
  108. scope :recent, -> { reorder(id: :desc) }
  109. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  110. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  111. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  112. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  113. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  114. delegate :email,
  115. :unconfirmed_email,
  116. :current_sign_in_ip,
  117. :current_sign_in_at,
  118. :confirmed?,
  119. :admin?,
  120. :moderator?,
  121. :staff?,
  122. :locale,
  123. :hides_network?,
  124. to: :user,
  125. prefix: true,
  126. allow_nil: true
  127. delegate :chosen_languages, to: :user, prefix: false, allow_nil: true
  128. def local?
  129. domain.nil?
  130. end
  131. def moved?
  132. moved_to_account_id.present?
  133. end
  134. def bot?
  135. %w(Application Service).include? actor_type
  136. end
  137. alias bot bot?
  138. def bot=(val)
  139. self.actor_type = ActiveModel::Type::Boolean.new.cast(val) ? 'Service' : 'Person'
  140. end
  141. def acct
  142. local? ? username : "#{username}@#{domain}"
  143. end
  144. def local_username_and_domain
  145. "#{username}@#{Rails.configuration.x.local_domain}"
  146. end
  147. def to_webfinger_s
  148. "acct:#{local_username_and_domain}"
  149. end
  150. def subscribed?
  151. subscription_expires_at.present?
  152. end
  153. def possibly_stale?
  154. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  155. end
  156. def refresh!
  157. return if local?
  158. ResolveAccountService.new.call(acct)
  159. end
  160. def unsuspend!
  161. transaction do
  162. user&.enable! if local?
  163. update!(suspended: false)
  164. end
  165. end
  166. def memorialize!
  167. transaction do
  168. user&.disable! if local?
  169. update!(memorial: true)
  170. end
  171. end
  172. def keypair
  173. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  174. end
  175. def fields
  176. (self[:fields] || []).map { |f| Field.new(self, f) }
  177. end
  178. def fields_attributes=(attributes)
  179. fields = []
  180. if attributes.is_a?(Hash)
  181. attributes.each_value do |attr|
  182. next if attr[:name].blank?
  183. fields << attr
  184. end
  185. end
  186. self[:fields] = fields
  187. end
  188. def build_fields
  189. return if fields.size >= 4
  190. raw_fields = self[:fields] || []
  191. add_fields = 4 - raw_fields.size
  192. add_fields.times { raw_fields << { name: '', value: '' } }
  193. self.fields = raw_fields
  194. end
  195. def magic_key
  196. modulus, exponent = [keypair.public_key.n, keypair.public_key.e].map do |component|
  197. result = []
  198. until component.zero?
  199. result << [component % 256].pack('C')
  200. component >>= 8
  201. end
  202. result.reverse.join
  203. end
  204. (['RSA'] + [modulus, exponent].map { |n| Base64.urlsafe_encode64(n) }).join('.')
  205. end
  206. def subscription(webhook_url)
  207. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  208. end
  209. def save_with_optional_media!
  210. save!
  211. rescue ActiveRecord::RecordInvalid
  212. self.avatar = nil
  213. self.header = nil
  214. self[:avatar_remote_url] = ''
  215. self[:header_remote_url] = ''
  216. save!
  217. end
  218. def object_type
  219. :person
  220. end
  221. def to_param
  222. username
  223. end
  224. def excluded_from_timeline_account_ids
  225. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  226. end
  227. def excluded_from_timeline_domains
  228. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  229. end
  230. def preferred_inbox_url
  231. shared_inbox_url.presence || inbox_url
  232. end
  233. class Field < ActiveModelSerializers::Model
  234. attributes :name, :value, :account, :errors
  235. def initialize(account, attr)
  236. @account = account
  237. @name = attr['name'].strip[0, 255]
  238. @value = attr['value'].strip[0, 255]
  239. @errors = {}
  240. end
  241. def to_h
  242. { name: @name, value: @value }
  243. end
  244. end
  245. class << self
  246. def readonly_attributes
  247. super - %w(statuses_count following_count followers_count)
  248. end
  249. def domains
  250. reorder(nil).pluck(Arel.sql('distinct accounts.domain'))
  251. end
  252. def inboxes
  253. urls = reorder(nil).where(protocol: :activitypub).pluck(Arel.sql("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)"))
  254. DeliveryFailureTracker.filter(urls)
  255. end
  256. def triadic_closures(account, limit: 5, offset: 0)
  257. sql = <<-SQL.squish
  258. WITH first_degree AS (
  259. SELECT target_account_id
  260. FROM follows
  261. WHERE account_id = :account_id
  262. )
  263. SELECT accounts.*
  264. FROM follows
  265. INNER JOIN accounts ON follows.target_account_id = accounts.id
  266. WHERE
  267. account_id IN (SELECT * FROM first_degree)
  268. AND target_account_id NOT IN (SELECT * FROM first_degree)
  269. AND target_account_id NOT IN (:excluded_account_ids)
  270. AND accounts.suspended = false
  271. GROUP BY target_account_id, accounts.id
  272. ORDER BY count(account_id) DESC
  273. OFFSET :offset
  274. LIMIT :limit
  275. SQL
  276. excluded_account_ids = account.excluded_from_timeline_account_ids + [account.id]
  277. find_by_sql(
  278. [sql, { account_id: account.id, excluded_account_ids: excluded_account_ids, limit: limit, offset: offset }]
  279. )
  280. end
  281. def search_for(terms, limit = 10)
  282. textsearch, query = generate_query_for_search(terms)
  283. sql = <<-SQL.squish
  284. SELECT
  285. accounts.*,
  286. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  287. FROM accounts
  288. WHERE #{query} @@ #{textsearch}
  289. AND accounts.suspended = false
  290. AND accounts.moved_to_account_id IS NULL
  291. ORDER BY rank DESC
  292. LIMIT ?
  293. SQL
  294. find_by_sql([sql, limit])
  295. end
  296. def advanced_search_for(terms, account, limit = 10, following = false)
  297. textsearch, query = generate_query_for_search(terms)
  298. if following
  299. sql = <<-SQL.squish
  300. WITH first_degree AS (
  301. SELECT target_account_id
  302. FROM follows
  303. WHERE account_id = ?
  304. )
  305. SELECT
  306. accounts.*,
  307. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  308. FROM accounts
  309. 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 = ?)
  310. WHERE accounts.id IN (SELECT * FROM first_degree)
  311. AND #{query} @@ #{textsearch}
  312. AND accounts.suspended = false
  313. AND accounts.moved_to_account_id IS NULL
  314. GROUP BY accounts.id
  315. ORDER BY rank DESC
  316. LIMIT ?
  317. SQL
  318. find_by_sql([sql, account.id, account.id, account.id, limit])
  319. else
  320. sql = <<-SQL.squish
  321. SELECT
  322. accounts.*,
  323. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  324. FROM accounts
  325. 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 = ?)
  326. WHERE #{query} @@ #{textsearch}
  327. AND accounts.suspended = false
  328. AND accounts.moved_to_account_id IS NULL
  329. GROUP BY accounts.id
  330. ORDER BY rank DESC
  331. LIMIT ?
  332. SQL
  333. find_by_sql([sql, account.id, account.id, limit])
  334. end
  335. end
  336. private
  337. def generate_query_for_search(terms)
  338. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  339. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  340. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  341. [textsearch, query]
  342. end
  343. end
  344. def emojis
  345. @emojis ||= CustomEmoji.from_text(emojifiable_text, domain)
  346. end
  347. before_create :generate_keys
  348. before_validation :normalize_domain
  349. before_validation :prepare_contents, if: :local?
  350. private
  351. def prepare_contents
  352. display_name&.strip!
  353. note&.strip!
  354. end
  355. def generate_keys
  356. return unless local? && !Rails.env.test?
  357. keypair = OpenSSL::PKey::RSA.new(2048)
  358. self.private_key = keypair.to_pem
  359. self.public_key = keypair.public_key.to_pem
  360. end
  361. YAML_START = "---\r\n"
  362. YAML_END = "\r\n...\r\n"
  363. def note_length_does_not_exceed_length_limit
  364. note_without_metadata = note
  365. if note.start_with? YAML_START
  366. idx = note.index YAML_END
  367. unless idx.nil?
  368. note_without_metadata = note[(idx + YAML_END.length) .. -1]
  369. end
  370. end
  371. if note_without_metadata.mb_chars.grapheme_length > MAX_NOTE_LENGTH
  372. errors.add(:note, "can't be longer than 500 graphemes")
  373. end
  374. end
  375. def normalize_domain
  376. return if local?
  377. self.domain = TagManager.instance.normalize_domain(domain)
  378. end
  379. def emojifiable_text
  380. [note, display_name, fields.map(&:value)].join(' ')
  381. end
  382. end