Improve restore from tombstone script by not having to loop through all posts.

This commit is contained in:
Guo Xiang Tan 2016-09-21 18:01:59 +08:00
parent b62b6ba12c
commit 1d4451db5d

View file

@ -409,32 +409,38 @@ def recover_from_tombstone
public_path = Rails.root.join("public") public_path = Rails.root.join("public")
Post.find_each do |post| Dir.glob("#{File.join(public_path, 'uploads', 'tombstone', '**', '*.*')}").each do |path|
doc = Nokogiri::HTML::fragment(post.raw) filename = File.basename(path)
doc.css("img[src]").each do |img| Post.where("raw LIKE ?", "%#{filename}%").each do |post|
url = img["src"] doc = Nokogiri::HTML::fragment(post.raw)
next unless url =~ /^\/uploads\// doc.css("img[src]").each do |img|
url = img["src"]
upload = Upload.find_by(url: url) next unless url =~ /^\/uploads\//
if !upload && url upload = Upload.find_by(url: url)
tombstone_path = File.join(public_path, 'uploads', 'tombstone', url.gsub(/^\/uploads\//, ""))
if File.exists?(tombstone_path) if !upload && url
File.open(tombstone_path) do |file| printf "Restoring #{url}..."
new_upload = Upload.create_for(Discourse::SYSTEM_USER_ID, file, File.basename(url), File.size(file))
if new_upload.persisted? tombstone_path = File.join(public_path, 'uploads', 'tombstone', url.gsub(/^\/uploads\//, ""))
putc "."
DbHelper.remap(url, new_upload.url) if File.exists?(tombstone_path)
else File.open(tombstone_path) do |file|
puts "Failed to create upload for #{url}: #{new_upload.errors.full_messages}." new_upload = Upload.create_for(Discourse::SYSTEM_USER_ID, file, File.basename(url), File.size(file))
if new_upload.persisted?
printf "Restored into #{new_upload.url}\n"
DbHelper.remap(url, new_upload.url)
else
puts "Failed to create upload for #{url}: #{new_upload.errors.full_messages}."
end
end end
else
puts "Failed to find file (#{tombstone_path}) in tombstone."
end end
else
puts "Failed to find file (#{tombstone_path}) in tombstone."
end end
end end
end end