From 2b006c0429e25d25b9cae6bf95fe9d98f3f8b55d Mon Sep 17 00:00:00 2001
From: Vinoth Kannan <vinothkannan@vinkas.com>
Date: Wed, 26 Dec 2018 23:22:07 +0530
Subject: [PATCH] FEATURE: Invalidate broken images cache on Rebuild HTML
 action

---
 app/controllers/posts_controller.rb    | 2 +-
 app/models/post.rb                     | 5 +++++
 spec/requests/posts_controller_spec.rb | 9 +++++++++
 3 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb
index e4e0ccf7611..6820ed87de9 100644
--- a/app/controllers/posts_controller.rb
+++ b/app/controllers/posts_controller.rb
@@ -513,7 +513,7 @@ class PostsController < ApplicationController
     guardian.ensure_can_rebake!
 
     post = find_post_from_params
-    post.rebake!(invalidate_oneboxes: true)
+    post.rebake!(invalidate_oneboxes: true, invalidate_broken_images: true)
 
     render body: nil
   end
diff --git a/app/models/post.rb b/app/models/post.rb
index 61af4c4b363..a923d1da05b 100644
--- a/app/models/post.rb
+++ b/app/models/post.rb
@@ -549,6 +549,11 @@ class Post < ActiveRecord::Base
 
     update_columns(cooked: new_cooked, baked_at: Time.new, baked_version: BAKED_VERSION)
 
+    if opts.fetch(:invalidate_broken_images, false)
+      custom_fields.delete(BROKEN_IMAGES)
+      save_custom_fields
+    end
+
     # Extracts urls from the body
     TopicLink.extract_from(self)
     QuotedPost.extract_from(self)
diff --git a/spec/requests/posts_controller_spec.rb b/spec/requests/posts_controller_spec.rb
index e3e6490547e..8290e1b4451 100644
--- a/spec/requests/posts_controller_spec.rb
+++ b/spec/requests/posts_controller_spec.rb
@@ -661,6 +661,15 @@ describe PostsController do
         put "/posts/#{post.id}/rebake.json"
         expect(response.status).to eq(200)
       end
+
+      it "will invalidate broken images cache" do
+        sign_in(Fabricate(:moderator))
+        post.custom_fields[Post::BROKEN_IMAGES] = ["https://example.com/image.jpg"].to_json
+        post.save_custom_fields
+        put "/posts/#{post.id}/rebake.json"
+        post.reload
+        expect(post.custom_fields[Post::BROKEN_IMAGES]).to be_nil
+      end
     end
   end