DEV: Add a CSV importer for restoring deleted users ()

This is an importer I wrote to restore some users that were
accidentally deleted for being purged as old staged users or old
unactivated users.

It reads from CSV files exported from a discourse sql backup.
This commit is contained in:
Blake Erickson 2021-02-19 13:46:54 -07:00 committed by GitHub
parent da8b0818ef
commit dbcda617b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,96 @@
# frozen_string_literal: true
require "csv"
require File.expand_path(File.dirname(__FILE__) + "/base.rb")
# Edit the constants and initialize method for your import data.
class ImportScripts::CsvRestoreStagedUsers < ImportScripts::Base
CSV_FILE_PATH = ENV['CSV_USER_FILE']
CSV_CUSTOM_FIELDS = ENV['CSV_CUSTOM_FIELDS']
CSV_EMAILS = ENV['CSV_EMAILS']
BATCH_SIZE ||= 1000
def initialize
super
@imported_users = load_csv(CSV_FILE_PATH)
@imported_emails = load_csv(CSV_EMAILS)
@imported_custom_fields = load_csv(CSV_CUSTOM_FIELDS)
@skip_updates = true
end
def execute
puts "", "Importing from CSV file..."
import_users
puts "", "Done"
end
def load_csv(path)
CSV.parse(File.read(path), headers: true)
end
def username_for(name)
result = name.downcase.gsub(/[^a-z0-9\-\_]/, '')
if result.blank?
result = Digest::SHA1.hexdigest(name)[0...10]
end
result
end
def get_email(id)
email = nil
@imported_emails.each do |e|
if e["user_id"] == id
email = e["email"]
end
end
email
end
def get_custom_fields(id)
custom_fields = {}
@imported_custom_fields.each do |cf|
if cf["user_id"] == id
custom_fields[cf["name"]] = cf["value"]
end
end
custom_fields
end
def import_users
puts '', "Importing users"
users = []
@imported_users.each do |u|
email = get_email(u['id'])
custom_fields = get_custom_fields(u['id'])
u['email'] = email
u['custom_fields'] = custom_fields
users << u
end
users.uniq!
create_users(users) do |u|
{
id: u['id'],
username: u['username'],
email: u['email'],
created_at: u['created_at'],
staged: u['staged'],
custom_fields: u['custom_fields'],
}
end
end
end
if __FILE__ == $0
ImportScripts::CsvRestoreStagedUsers.new.perform
end