report_service.rb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # frozen_string_literal: true
  2. class ReportService < BaseService
  3. include Payloadable
  4. def call(source_account, target_account, options = {})
  5. @source_account = source_account
  6. @target_account = target_account
  7. @status_ids = options.delete(:status_ids).presence || []
  8. @comment = options.delete(:comment).presence || ''
  9. @category = options.delete(:category).presence || 'other'
  10. @rule_ids = options.delete(:rule_ids).presence
  11. @options = options
  12. raise ActiveRecord::RecordNotFound if @target_account.suspended?
  13. create_report!
  14. notify_staff!
  15. forward_to_origin! if forward?
  16. @report
  17. end
  18. private
  19. def create_report!
  20. @report = @source_account.reports.create!(
  21. target_account: @target_account,
  22. status_ids: reported_status_ids,
  23. comment: @comment,
  24. uri: @options[:uri],
  25. forwarded: forward?,
  26. category: @category,
  27. rule_ids: @rule_ids
  28. )
  29. end
  30. def notify_staff!
  31. return if @report.unresolved_siblings?
  32. User.those_who_can(:manage_reports).includes(:account).each do |u|
  33. LocalNotificationWorker.perform_async(u.account_id, @report.id, 'Report', 'admin.report')
  34. AdminMailer.new_report(u.account, @report).deliver_later if u.allows_report_emails?
  35. end
  36. end
  37. def forward_to_origin!
  38. ActivityPub::DeliveryWorker.perform_async(
  39. payload,
  40. some_local_account.id,
  41. @target_account.inbox_url
  42. )
  43. end
  44. def forward?
  45. !@target_account.local? && ActiveModel::Type::Boolean.new.cast(@options[:forward])
  46. end
  47. def reported_status_ids
  48. return AccountStatusesFilter.new(@target_account, @source_account).results.with_discarded.find(Array(@status_ids)).pluck(:id) if @source_account.local?
  49. # If the account making reports is remote, it is likely anonymized so we have to relax the requirements for attaching statuses.
  50. domain = @source_account.domain.to_s.downcase
  51. has_followers = @target_account.followers.where(Account.arel_table[:domain].lower.eq(domain)).exists?
  52. visibility = has_followers ? %i(public unlisted private) : %i(public unlisted)
  53. scope = @target_account.statuses.with_discarded
  54. scope.merge!(scope.where(visibility: visibility).or(scope.where('EXISTS (SELECT 1 FROM mentions m JOIN accounts a ON m.account_id = a.id WHERE lower(a.domain) = ?)', domain)))
  55. # Allow missing posts to not drop reports that include e.g. a deleted post
  56. scope.where(id: Array(@status_ids)).pluck(:id)
  57. end
  58. def payload
  59. Oj.dump(serialize_payload(@report, ActivityPub::FlagSerializer, account: some_local_account))
  60. end
  61. def some_local_account
  62. @some_local_account ||= Account.representative
  63. end
  64. end