FIX: Rebake lightbox and use short upload urls in `migrate_to_s3`.

FIX: Rebake lightbox and use short upload urls in migrate_to_s3.

diff --git a/lib/tasks/uploads.rake b/lib/tasks/uploads.rake
index 12d16ff..2a384b8 100644
--- a/lib/tasks/uploads.rake
+++ b/lib/tasks/uploads.rake
@@ -357,6 +357,27 @@ def migrate_to_s3
       DbHelper.remap(from, to, anchor_left: true)
     end
 
+    from = "src=\"/uploads/#{db}/original/(\\dX/(?:[a-f0-9]/)*[a-f0-9]{40}[a-z0-9\\.]*)"
+    to = "src=\"#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1"
+
+    DbHelper.regexp_replace(from, to)
+
+    from = "src='/uploads/#{db}/original/(\\dX/(?:[a-f0-9]/)*[a-f0-9]{40}[a-z0-9\\.]*)"
+    to = "src='#{SiteSetting.Upload.s3_base_url}/#{prefix}\\1"
+
+    DbHelper.regexp_replace(from, to)
+
+    Post.where("raw LIKE '%![](/uploads/default/original/%)%'").each do |post|
+      regexp = /!\[\](\/uploads\/#{db}\/original\/(\dX\/(?:[a-f0-9]\/)*[a-f0-9]{40}[a-z0-9\.]*))/
+
+      post.raw.scan(regexp).each do |upload_url, _|
+        upload = Upload.get_from_url(upload_url)
+        post.raw = post.raw.gsub("![](#{upload_url})", "![](#{upload.short_url})")
+      end
+
+      post.save!(validate: false)
+    end
+
     if Discourse.asset_host.present?
       # Uploads that were on local CDN will now be on S3 CDN
       from = "#{Discourse.asset_host}/uploads/#{db}/original/"
@@ -379,10 +400,16 @@ def migrate_to_s3
       DbHelper.remap(from, to)
     end
 
+    puts "Removing old optimized images..."
+
     OptimizedImage
       .joins("LEFT JOIN uploads u ON optimized_images.upload_id = u.id")
       .where("u.id IS NOT NULL AND u.url LIKE '//%' AND optimized_images.url NOT LIKE '//%'")
       .destroy_all
+
+    puts "Rebaking posts with lightboxes..."
+
+    Post.where("cooked LIKE '%class=\"lightbox\"%'").find_each(&:rebake!)
   end
 
   puts "Done!"

GitHub sha: 2d34be24

Wouldn’t that do the replace even when the dry_run flag is set?

Ditto ^^

Ditto ^^

Ditto ^^

Ditto ^^ (for OptimizedImage which I missed in a previous commit)

Followed up in FIX: Dry run broken for `uploads:migrate_to_s3`.

1 Like

Thanks for catching this @ZogStriP

2 Likes