2022-11-17 21:05:09 +11:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2023-01-19 02:20:52 +11:00
|
|
|
require 'csv'
|
|
|
|
|
2022-11-17 21:05:09 +11:00
|
|
|
# A non-activerecord helper class for csv upload
|
|
|
|
class Admin::Import
|
|
|
|
include ActiveModel::Model
|
|
|
|
|
|
|
|
ROWS_PROCESSING_LIMIT = 20_000
|
|
|
|
|
|
|
|
attr_accessor :data
|
|
|
|
|
|
|
|
validates :data, presence: true
|
|
|
|
validate :validate_data
|
|
|
|
|
|
|
|
def data_file_name
|
|
|
|
data.original_filename
|
|
|
|
end
|
|
|
|
|
2023-01-19 02:20:52 +11:00
|
|
|
def csv_rows
|
|
|
|
csv_data.rewind
|
|
|
|
|
|
|
|
csv_data.take(ROWS_PROCESSING_LIMIT + 1)
|
|
|
|
end
|
|
|
|
|
2022-11-17 21:05:09 +11:00
|
|
|
private
|
|
|
|
|
2023-01-19 02:20:52 +11:00
|
|
|
def csv_data
|
|
|
|
return @csv_data if defined?(@csv_data)
|
|
|
|
|
|
|
|
csv_converter = lambda do |field, field_info|
|
|
|
|
case field_info.header
|
2024-03-26 20:30:07 +11:00
|
|
|
when '#domain'
|
|
|
|
field&.downcase&.strip
|
|
|
|
when '#public_comment'
|
2023-01-19 02:20:52 +11:00
|
|
|
field&.strip
|
|
|
|
when '#severity'
|
2024-03-26 20:30:07 +11:00
|
|
|
field&.downcase&.strip&.to_sym
|
2023-01-19 02:20:52 +11:00
|
|
|
when '#reject_media', '#reject_reports', '#obfuscate'
|
2024-03-26 20:30:07 +11:00
|
|
|
ActiveModel::Type::Boolean.new.cast(field&.downcase)
|
2023-01-19 02:20:52 +11:00
|
|
|
else
|
|
|
|
field
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
@csv_data = CSV.open(data.path, encoding: 'UTF-8', skip_blanks: true, headers: true, converters: csv_converter)
|
|
|
|
@csv_data.take(1) # Ensure the headers are read
|
|
|
|
@csv_data = CSV.open(data.path, encoding: 'UTF-8', skip_blanks: true, headers: ['#domain'], converters: csv_converter) unless @csv_data.headers&.first == '#domain'
|
|
|
|
@csv_data
|
|
|
|
end
|
2022-11-17 21:05:09 +11:00
|
|
|
|
2023-01-19 02:20:52 +11:00
|
|
|
def csv_row_count
|
|
|
|
return @csv_row_count if defined?(@csv_row_count)
|
2022-11-17 21:05:09 +11:00
|
|
|
|
2023-01-19 02:20:52 +11:00
|
|
|
csv_data.rewind
|
|
|
|
@csv_row_count = csv_data.take(ROWS_PROCESSING_LIMIT + 2).count
|
|
|
|
end
|
2022-11-17 21:05:09 +11:00
|
|
|
|
2023-01-19 02:20:52 +11:00
|
|
|
def validate_data
|
|
|
|
return if data.nil?
|
2023-02-20 16:58:28 +11:00
|
|
|
|
2023-01-19 02:20:52 +11:00
|
|
|
errors.add(:data, I18n.t('imports.errors.over_rows_processing_limit', count: ROWS_PROCESSING_LIMIT)) if csv_row_count > ROWS_PROCESSING_LIMIT
|
2022-11-17 21:05:09 +11:00
|
|
|
rescue CSV::MalformedCSVError => e
|
|
|
|
errors.add(:data, I18n.t('imports.errors.invalid_csv_file', error: e.message))
|
|
|
|
end
|
|
|
|
end
|