import.rb 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. # frozen_string_literal: true
  2. require 'csv'
  3. # A non-ActiveRecord helper class for CSV uploads.
  4. # Handles saving contents to database.
  5. class Form::Import
  6. include ActiveModel::Model
  7. MODES = %i(merge overwrite).freeze
  8. FILE_SIZE_LIMIT = 20.megabytes
  9. ROWS_PROCESSING_LIMIT = 20_000
  10. EXPECTED_HEADERS_BY_TYPE = {
  11. following: ['Account address', 'Show boosts', 'Notify on new posts', 'Languages'],
  12. blocking: ['Account address'],
  13. muting: ['Account address', 'Hide notifications'],
  14. domain_blocking: ['#domain'],
  15. bookmarks: ['#uri'],
  16. lists: ['List name', 'Account address'],
  17. }.freeze
  18. KNOWN_FIRST_HEADERS = EXPECTED_HEADERS_BY_TYPE.values.map(&:first).uniq.freeze
  19. ATTRIBUTE_BY_HEADER = {
  20. 'Account address' => 'acct',
  21. 'Show boosts' => 'show_reblogs',
  22. 'Notify on new posts' => 'notify',
  23. 'Languages' => 'languages',
  24. 'Hide notifications' => 'hide_notifications',
  25. '#domain' => 'domain',
  26. '#uri' => 'uri',
  27. 'List name' => 'list_name',
  28. }.freeze
  29. class EmptyFileError < StandardError; end
  30. attr_accessor :current_account, :data, :type, :overwrite, :bulk_import
  31. validates :type, presence: true
  32. validates :data, presence: true
  33. validate :validate_data
  34. def guessed_type
  35. if csv_headers_match?('Hide notifications') || file_name_matches?('mutes') || file_name_matches?('muted_accounts')
  36. :muting
  37. elsif csv_headers_match?('Show boosts') || csv_headers_match?('Notify on new posts') || csv_headers_match?('Languages') || file_name_matches?('follows') || file_name_matches?('following_accounts')
  38. :following
  39. elsif file_name_matches?('blocks') || file_name_matches?('blocked_accounts')
  40. :blocking
  41. elsif file_name_matches?('domain_blocks') || file_name_matches?('blocked_domains')
  42. :domain_blocking
  43. elsif file_name_matches?('bookmarks')
  44. :bookmarks
  45. elsif file_name_matches?('lists')
  46. :lists
  47. end
  48. end
  49. # Whether the uploaded CSV file seems to correspond to a different import type than the one selected
  50. def likely_mismatched?
  51. guessed_type.present? && guessed_type != type.to_sym
  52. end
  53. def save
  54. return false unless valid?
  55. ApplicationRecord.transaction do
  56. now = Time.now.utc
  57. @bulk_import = current_account.bulk_imports.create(type: type, overwrite: overwrite || false, state: :unconfirmed, original_filename: data.original_filename, likely_mismatched: likely_mismatched?)
  58. nb_items = BulkImportRow.insert_all(parsed_rows.map { |row| { bulk_import_id: bulk_import.id, data: row, created_at: now, updated_at: now } }).length
  59. @bulk_import.update(total_items: nb_items)
  60. end
  61. end
  62. def mode
  63. overwrite ? :overwrite : :merge
  64. end
  65. def mode=(str)
  66. self.overwrite = str.to_sym == :overwrite
  67. end
  68. private
  69. def file_name_matches?(string)
  70. data.original_filename&.start_with?(string)
  71. end
  72. def csv_headers_match?(string)
  73. csv_data.headers.include?(string)
  74. end
  75. def default_csv_headers
  76. case type.to_sym
  77. when :following, :blocking, :muting
  78. ['Account address']
  79. when :domain_blocking
  80. ['#domain']
  81. when :bookmarks
  82. ['#uri']
  83. when :lists
  84. ['List name', 'Account address']
  85. end
  86. end
  87. def csv_data
  88. return @csv_data if defined?(@csv_data)
  89. csv_converter = lambda do |field, field_info|
  90. case field_info.header
  91. when 'Show boosts', 'Notify on new posts', 'Hide notifications'
  92. ActiveModel::Type::Boolean.new.cast(field&.downcase)
  93. when 'Languages'
  94. field&.split(',')&.map(&:strip)&.presence
  95. when 'Account address'
  96. field.strip.gsub(/\A@/, '')
  97. when '#domain'
  98. field&.strip&.downcase
  99. when '#uri', 'List name'
  100. field.strip
  101. else
  102. field
  103. end
  104. end
  105. @csv_data = CSV.open(data.path, encoding: 'UTF-8', skip_blanks: true, headers: true, converters: csv_converter)
  106. @csv_data.take(1) # Ensure the headers are read
  107. raise EmptyFileError if @csv_data.headers == true
  108. @csv_data = CSV.open(data.path, encoding: 'UTF-8', skip_blanks: true, headers: default_csv_headers, converters: csv_converter) unless KNOWN_FIRST_HEADERS.include?(@csv_data.headers&.first)
  109. @csv_data
  110. end
  111. def csv_row_count
  112. return @csv_row_count if defined?(@csv_row_count)
  113. csv_data.rewind
  114. @csv_row_count = csv_data.take(ROWS_PROCESSING_LIMIT + 2).count
  115. end
  116. def parsed_rows
  117. csv_data.rewind
  118. expected_headers = EXPECTED_HEADERS_BY_TYPE[type.to_sym]
  119. csv_data.take(ROWS_PROCESSING_LIMIT + 1).map do |row|
  120. row.to_h.slice(*expected_headers).transform_keys { |key| ATTRIBUTE_BY_HEADER[key] }
  121. end
  122. end
  123. def validate_data
  124. return if data.nil?
  125. return errors.add(:data, I18n.t('imports.errors.too_large')) if data.size > FILE_SIZE_LIMIT
  126. return errors.add(:data, I18n.t('imports.errors.incompatible_type')) unless default_csv_headers.all? { |header| csv_data.headers.include?(header) }
  127. errors.add(:data, I18n.t('imports.errors.over_rows_processing_limit', count: ROWS_PROCESSING_LIMIT)) if csv_row_count > ROWS_PROCESSING_LIMIT
  128. if type.to_sym == :following
  129. base_limit = FollowLimitValidator.limit_for_account(current_account)
  130. limit = base_limit
  131. limit -= current_account.following_count unless overwrite
  132. errors.add(:data, I18n.t('users.follow_limit_reached', limit: base_limit)) if csv_row_count > limit
  133. end
  134. rescue CSV::MalformedCSVError => e
  135. errors.add(:data, I18n.t('imports.errors.invalid_csv_file', error: e.message))
  136. rescue EmptyFileError
  137. errors.add(:data, I18n.t('imports.errors.empty'))
  138. end
  139. end