import_validator.rb 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. end
  23. private
  24. def validate_following_import(import, row_count)
  25. base_limit = FollowLimitValidator.limit_for_account(import.account)
  26. limit = begin
  27. if import.overwrite?
  28. base_limit
  29. else
  30. base_limit - import.account.following_count
  31. end
  32. end
  33. import.errors.add(:data, I18n.t('users.follow_limit_reached', limit: base_limit)) if row_count > limit
  34. end
  35. end