import_validator.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # frozen_string_literal: true
  2. require 'csv'
  3. class ImportValidator < ActiveModel::Validator
  4. KNOWN_HEADERS = [
  5. 'Account address',
  6. '#domain',
  7. '#uri',
  8. ].freeze
  9. def validate(import)
  10. return if import.type.blank? || import.data.blank?
  11. # We parse because newlines could be part of individual rows. This
  12. # runs on create so we should be reading the local file here before
  13. # it is uploaded to object storage or moved anywhere...
  14. csv_data = CSV.parse(import.data.queued_for_write[:original].read)
  15. row_count = csv_data.size
  16. row_count -= 1 if KNOWN_HEADERS.include?(csv_data.first&.first)
  17. import.errors.add(:data, I18n.t('imports.errors.over_rows_processing_limit', count: ImportService::ROWS_PROCESSING_LIMIT)) if row_count > ImportService::ROWS_PROCESSING_LIMIT
  18. case import.type
  19. when 'following'
  20. validate_following_import(import, row_count)
  21. end
  22. rescue CSV::MalformedCSVError
  23. import.errors.add(:data, :malformed)
  24. end
  25. private
  26. def validate_following_import(import, row_count)
  27. base_limit = FollowLimitValidator.limit_for_account(import.account)
  28. limit = begin
  29. if import.overwrite?
  30. base_limit
  31. else
  32. base_limit - import.account.following_count
  33. end
  34. end
  35. import.errors.add(:data, I18n.t('users.follow_limit_reached', limit: base_limit)) if row_count > limit
  36. end
  37. end