|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'csv' |
| 4 | + |
| 5 | +class ImportService < BaseService |
| 6 | + ROWS_PROCESSING_LIMIT = 20_000 |
| 7 | + |
| 8 | + def call(import) |
| 9 | + @import = import |
| 10 | + @account = @import.account |
| 11 | + @data = CSV.new(import_data).reject(&:blank?) |
| 12 | + |
| 13 | + case @import.type |
| 14 | + when 'following' |
| 15 | + import_follows! |
| 16 | + when 'blocking' |
| 17 | + import_blocks! |
| 18 | + when 'muting' |
| 19 | + import_mutes! |
| 20 | + when 'domain_blocking' |
| 21 | + import_domain_blocks! |
| 22 | + end |
| 23 | + end |
| 24 | + |
| 25 | + private |
| 26 | + |
| 27 | + def import_follows! |
| 28 | + import_relationships!('follow', 'unfollow', @account.following, follow_limit) |
| 29 | + end |
| 30 | + |
| 31 | + def import_blocks! |
| 32 | + import_relationships!('block', 'unblock', @account.blocking, ROWS_PROCESSING_LIMIT) |
| 33 | + end |
| 34 | + |
| 35 | + def import_mutes! |
| 36 | + import_relationships!('mute', 'unmute', @account.muting, ROWS_PROCESSING_LIMIT) |
| 37 | + end |
| 38 | + |
| 39 | + def import_domain_blocks! |
| 40 | + items = @data.take(ROWS_PROCESSING_LIMIT).map { |row| row.first.strip } |
| 41 | + |
| 42 | + if @import.overwrite? |
| 43 | + presence_hash = items.each_with_object({}) { |id, mapping| mapping[id] = true } |
| 44 | + |
| 45 | + @account.domain_blocks.find_each do |domain_block| |
| 46 | + if presence_hash[domain_block.domain] |
| 47 | + items.delete(domain_block.domain) |
| 48 | + else |
| 49 | + @account.unblock_domain!(domain_block.domain) |
| 50 | + end |
| 51 | + end |
| 52 | + end |
| 53 | + |
| 54 | + items.each do |domain| |
| 55 | + @account.block_domain!(domain) |
| 56 | + end |
| 57 | + |
| 58 | + AfterAccountDomainBlockWorker.push_bulk(items) do |domain| |
| 59 | + [@account.id, domain] |
| 60 | + end |
| 61 | + end |
| 62 | + |
| 63 | + def import_relationships!(action, undo_action, overwrite_scope, limit) |
| 64 | + items = @data.take(limit).map { |row| row.first.strip } |
| 65 | + |
| 66 | + if @import.overwrite? |
| 67 | + presence_hash = items.each_with_object({}) { |id, mapping| mapping[id] = true } |
| 68 | + |
| 69 | + overwrite_scope.find_each do |target_account| |
| 70 | + if presence_hash[target_account.acct] |
| 71 | + items.delete(target_account.acct) |
| 72 | + else |
| 73 | + Import::RelationshipWorker.perform_async(@account.id, target_account.acct, undo_action) |
| 74 | + end |
| 75 | + end |
| 76 | + end |
| 77 | + |
| 78 | + Import::RelationshipWorker.push_bulk(items) do |acct| |
| 79 | + [@account.id, acct, action] |
| 80 | + end |
| 81 | + end |
| 82 | + |
| 83 | + def import_data |
| 84 | + Paperclip.io_adapters.for(@import.data).read |
| 85 | + end |
| 86 | + |
| 87 | + def follow_limit |
| 88 | + FollowLimitValidator.limit_for_account(@account) |
| 89 | + end |
| 90 | +end |
0 commit comments