Class: ImportExport::Importer

Inherits:
ImportScripts::Base
  • Object
show all
Defined in:
lib/import_export/importer.rb

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Importer

Returns a new instance of Importer.



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/import_export/importer.rb', line 7

def initialize(data)
  @users = data[:users]
  @groups = data[:groups]
  @categories = data[:categories]
  @topics = data[:topics]
  @translation_overrides = data[:translation_overrides]

  # To support legacy `category_export` script
  if data[:category].present?
    @categories = [] if @categories.blank?
    @categories << data[:category]
  end
end

Instance Method Details

#category_levelsObject



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/import_export/importer.rb', line 207

def category_levels
  @levels ||=
    begin
      levels = {}

      # Incomplete backups may lack definitions for some parent categories
      # which would cause an infinite loop below.
      parent_ids = @categories.map { |category| category[:parent_category_id] }.uniq
      category_ids = @categories.map { |category| category[:id] }.uniq
      (parent_ids - category_ids).each { |id| levels[id] = 0 }

      loop do
        changed = false

        @categories.each do |category|
          if !levels[category[:id]]
            if !category[:parent_category_id]
              levels[category[:id]] = 1
            elsif levels[category[:parent_category_id]]
              levels[category[:id]] = levels[category[:parent_category_id]] + 1
            end

            changed = true
          end
        end

        break if !changed
      end

      levels
    end
end

#fix_permissionsObject



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/import_export/importer.rb', line 240

def fix_permissions
  categories_by_id = @categories.to_h { |category| [category[:id], category] }

  @categories.each do |category|
    if category[:permissions_params].blank?
      category[:permissions_params] = { "everyone" => CategoryGroup.permission_types[:full] }
    end
  end

  max_level = category_levels.values.max
  max_level.times do
    @categories.each do |category|
      parent_category = categories_by_id[category[:parent_category_id]]
      if !parent_category || !parent_category[:permissions_params] ||
           parent_category[:permissions_params][:everyone]
        next
      end

      parent_groups = parent_category[:permissions_params].map(&:first)
      child_groups = category[:permissions_params].map(&:first)

      only_subcategory_groups = child_groups - parent_groups
      if only_subcategory_groups.present?
        parent_category[:permissions_params].merge!(
          category[:permissions_params].slice(*only_subcategory_groups),
        )
      end
    end
  end
end

#import_categoriesObject



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/import_export/importer.rb', line 79

def import_categories
  return if @categories.blank?

  puts "Importing categories..."

  import_ids = @categories.collect { |c| "#{c[:id]}#{import_source}" }
  existing_categories =
    CategoryCustomField
      .where("name = 'import_id' AND value IN (?)", import_ids)
      .select(:category_id, :value)
      .to_a
  existing_category_ids = existing_categories.pluck(:value)

  levels = category_levels
  max_level = levels.values.max
  if SiteSetting.max_category_nesting < max_level
    puts "Setting max_category_nesting to #{max_level}..."
    SiteSetting.max_category_nesting = max_level
  end

  fix_permissions

  @categories.reject! { |c| existing_category_ids.include? c[:id].to_s }
  @categories.sort_by! { |c| levels[c[:id]] || 0 }

  @categories.each do |cat_attrs|
    begin
      id = cat_attrs.delete(:id)
      permissions = cat_attrs.delete(:permissions_params)

      category = Category.new(cat_attrs)
      category.parent_category_id =
        new_category_id(cat_attrs[:parent_category_id]) if cat_attrs[
        :parent_category_id
      ].present?
      category.user_id = new_user_id(cat_attrs[:user_id])
      import_id = "#{id}#{import_source}"
      category.custom_fields["import_id"] = import_id
      category.permissions = permissions
      category.save!
      existing_categories << { category_id: category.id, value: import_id }

      if cat_attrs[:description].present?
        post = category.topic.ordered_posts.first
        post.raw = cat_attrs[:description]
        post.skip_validation = true
        post.save!
        post.rebake!
      end
    rescue => e
      puts "Failed to import category (ID = #{id}, name = #{cat_attrs[:name]}): #{e.message}"
    end
  end

  self
end

#import_groupsObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/import_export/importer.rb', line 57

def import_groups
  return if @groups.blank?

  puts "Importing groups..."

  @groups.each do |group_data|
    g = group_data.dup
    user_ids = g.delete(:user_ids)
    external_id = g.delete(:id)
    new_group = Group.find_by_name(g[:name]) || Group.create!(g)
    user_ids.each do |external_user_id|
      begin
        new_group.add(User.find(new_user_id(external_user_id)))
      rescue StandardError
        ActiveRecord::RecordNotUnique
      end
    end
  end

  self
end

#import_sourceObject



203
204
205
# File 'lib/import_export/importer.rb', line 203

def import_source
  @_import_source ||= "#{ENV["IMPORT_SOURCE"] || ""}"
end

#import_topicsObject



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/import_export/importer.rb', line 136

def import_topics
  return if @topics.blank?

  puts "Importing topics...", ""

  @topics.each do |t|
    puts ""
    print t[:title]

    first_post_attrs =
      t[:posts].first.merge(t.slice(*(TopicExporter::TOPIC_ATTRS - %i[id category_id])))

    first_post_attrs[:user_id] = new_user_id(first_post_attrs[:user_id])
    first_post_attrs[:category] = new_category_id(t[:category_id])

    import_id = "#{first_post_attrs[:id]}#{import_source}"
    first_post = PostCustomField.where(name: "import_id", value: import_id).first&.post

    first_post = create_post(first_post_attrs, import_id) unless first_post

    topic_id = first_post.topic_id

    t[:posts].each_with_index do |post_data, i|
      next if i == 0
      print "."
      post_import_id = "#{post_data[:id]}#{import_source}"
      existing = PostCustomField.where(name: "import_id", value: post_import_id).first&.post
      unless existing
        # see ImportScripts::Base
        create_post(
          post_data.merge(topic_id: topic_id, user_id: new_user_id(post_data[:user_id])),
          post_import_id,
        )
      end
    end
  end

  puts ""

  self
end

#import_translation_overridesObject



178
179
180
181
182
183
184
185
186
187
188
# File 'lib/import_export/importer.rb', line 178

def import_translation_overrides
  return if @translation_overrides.blank?

  puts "Importing translation overrides..."

  @translation_overrides.each do |tu|
    TranslationOverride.upsert!(tu[:locale], tu[:translation_key], tu[:value])
  end

  TranslationOverride.reload_all_overrides!
end

#import_usersObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/import_export/importer.rb', line 35

def import_users
  return if @users.blank?

  puts "Importing users..."

  @users.each do |u|
    import_id = "#{u[:id]}#{import_source}"
    existing = User.with_email(u[:email]).first

    if existing
      if existing.custom_fields["import_id"] != import_id
        existing.custom_fields["import_id"] = import_id
        existing.save!
      end
    else
      u = create_user(u, import_id) # see ImportScripts::Base
    end
  end

  self
end

#new_category_id(external_category_id) ⇒ Object



196
197
198
199
200
201
# File 'lib/import_export/importer.rb', line 196

def new_category_id(external_category_id)
  CategoryCustomField
    .where(name: "import_id", value: "#{external_category_id}#{import_source}")
    .first
    &.category_id
end

#new_user_id(external_user_id) ⇒ Object



190
191
192
193
194
# File 'lib/import_export/importer.rb', line 190

def new_user_id(external_user_id)
  ucf =
    UserCustomField.where(name: "import_id", value: "#{external_user_id}#{import_source}").first
  ucf ? ucf.user_id : Discourse::SYSTEM_USER_ID
end

#performObject



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/import_export/importer.rb', line 21

def perform
  RateLimiter.disable

  import_users
  import_groups
  import_categories
  import_topics
  import_translation_overrides

  self
ensure
  RateLimiter.enable
end