From e4a627f5296fb60e99da9f95d34dcb2c9c9cd370 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Gaya?= <sebastien.gaya@gmail.com>
Date: Wed, 27 Oct 2021 18:45:47 +0200
Subject: [PATCH] async attachments

---
 app/models/communication/website/imported/page.rb | 7 ++++++-
 app/models/communication/website/imported/post.rb | 7 ++++++-
 2 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/app/models/communication/website/imported/page.rb b/app/models/communication/website/imported/page.rb
index 9c989f3db..0fd79f270 100644
--- a/app/models/communication/website/imported/page.rb
+++ b/app/models/communication/website/imported/page.rb
@@ -49,6 +49,7 @@ class Communication::Website::Imported::Page < ApplicationRecord
              optional: true
 
   before_validation :sync
+  after_save :sync_attachments
 
   default_scope { order(:path) }
 
@@ -92,8 +93,11 @@ class Communication::Website::Imported::Page < ApplicationRecord
     page.text = Wordpress.clean_html content.to_s
     page.published = true
     page.save
+  end
+
+  def sync_attachments
     if featured_medium.present?
-      unless featured_medium.file.attached?
+      unless featured_medium.file.attached? && featured_medium.file.blob.persisted?
         featured_medium.load_remote_file!
         featured_medium.save
       end
@@ -118,4 +122,5 @@ class Communication::Website::Imported::Page < ApplicationRecord
     end
     page.update(text: rich_text_with_attachments(page.text.to_s))
   end
+  handle_asynchronously :sync_attachments, queue: 'default'
 end
diff --git a/app/models/communication/website/imported/post.rb b/app/models/communication/website/imported/post.rb
index c53af2a76..90b9cfcff 100644
--- a/app/models/communication/website/imported/post.rb
+++ b/app/models/communication/website/imported/post.rb
@@ -48,6 +48,7 @@ class Communication::Website::Imported::Post < ApplicationRecord
              optional: true
 
   before_validation :sync
+  after_save :sync_attachments
 
   default_scope { order(path: :desc) }
 
@@ -94,8 +95,11 @@ class Communication::Website::Imported::Post < ApplicationRecord
     post.published_at = published_at if published_at
     post.published = true
     post.save
+  end
+
+  def sync_attachments
     if featured_medium.present?
-      unless featured_medium.file.attached?
+      unless featured_medium.file.attached? && featured_medium.file.blob.persisted?
         featured_medium.load_remote_file!
         featured_medium.save
       end
@@ -120,4 +124,5 @@ class Communication::Website::Imported::Post < ApplicationRecord
     end
     post.update(text: rich_text_with_attachments(post.text.to_s))
   end
+  handle_asynchronously :sync_attachments, queue: 'default'
 end
-- 
GitLab