export_domain_blocks_controller.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # frozen_string_literal: true
  2. require 'csv'
  3. module Admin
  4. class ExportDomainBlocksController < BaseController
  5. include Admin::ExportControllerConcern
  6. before_action :set_dummy_import!, only: [:new]
  7. def new
  8. authorize :domain_block, :create?
  9. end
  10. def export
  11. authorize :instance, :index?
  12. send_export_file
  13. end
  14. def import
  15. authorize :domain_block, :create?
  16. @import = Admin::Import.new(import_params)
  17. return render :new unless @import.validate
  18. @global_private_comment = I18n.t('admin.export_domain_blocks.import.private_comment_template', source: @import.data_file_name, date: I18n.l(Time.now.utc))
  19. @form = Form::DomainBlockBatch.new
  20. @domain_blocks = @import.csv_rows.filter_map do |row|
  21. domain = row['#domain'].strip
  22. next if DomainBlock.rule_for(domain).present?
  23. domain_block = DomainBlock.new(domain: domain,
  24. severity: row.fetch('#severity', :suspend),
  25. reject_media: row.fetch('#reject_media', false),
  26. reject_reports: row.fetch('#reject_reports', false),
  27. private_comment: @global_private_comment,
  28. public_comment: row['#public_comment'],
  29. obfuscate: row.fetch('#obfuscate', false))
  30. if domain_block.invalid?
  31. flash.now[:alert] = I18n.t('admin.export_domain_blocks.invalid_domain_block', error: domain_block.errors.full_messages.join(', '))
  32. next
  33. end
  34. domain_block
  35. rescue ArgumentError => e
  36. flash.now[:alert] = I18n.t('admin.export_domain_blocks.invalid_domain_block', error: e.message)
  37. next
  38. end
  39. @warning_domains = instances_from_imported_blocks.pluck(:domain)
  40. rescue ActionController::ParameterMissing
  41. flash.now[:alert] = I18n.t('admin.export_domain_blocks.no_file')
  42. set_dummy_import!
  43. render :new
  44. end
  45. private
  46. def instances_from_imported_blocks
  47. Instance.with_domain_follows(@domain_blocks.map(&:domain))
  48. end
  49. def export_filename
  50. 'domain_blocks.csv'
  51. end
  52. def export_headers
  53. %w(#domain #severity #reject_media #reject_reports #public_comment #obfuscate)
  54. end
  55. def export_data
  56. CSV.generate(headers: export_headers, write_headers: true) do |content|
  57. DomainBlock.with_limitations.order(id: :asc).each do |instance|
  58. content << [instance.domain, instance.severity, instance.reject_media, instance.reject_reports, instance.public_comment, instance.obfuscate]
  59. end
  60. end
  61. end
  62. end
  63. end