mirror of
https://github.com/discourse/discourse.git
synced 2025-04-23 03:44:26 +08:00
DEV: Add a CSV importer for restoring deleted users (#12147)
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:
parent
da8b0818ef
commit
dbcda617b3
96
script/import_scripts/csv_restore_staged_users.rb
Executable file
96
script/import_scripts/csv_restore_staged_users.rb
Executable file
@ -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
|
Loading…
x
Reference in New Issue
Block a user