FIX: Fallback to gzip compression if brotli isn't supported (#7895)

FIX: Fallback to gzip compression if brotli isn’t supported (#7895)

diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 241871c..9b5337e 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -58,6 +58,10 @@ module ApplicationHelper
     request.env["HTTP_ACCEPT_ENCODING"] =~ /br/
   end
 
+  def is_gzip_req?
+    request.env["HTTP_ACCEPT_ENCODING"] =~ /gzip/
+  end
+
   def script_asset_path(script)
     path = asset_path("#{script}.js")
 
@@ -77,6 +81,8 @@ module ApplicationHelper
 
       if is_brotli_req?
         path = path.gsub(/\.([^.]+)$/, '.br.\1')
+      elsif is_gzip_req?
+        path = path.gsub(/\.([^.]+)$/, '.gz.\1')
       end
 
     elsif GlobalSetting.cdn_url&.start_with?("https") && is_brotli_req?
diff --git a/spec/helpers/application_helper_spec.rb b/spec/helpers/application_helper_spec.rb
index 25e7543..20af731 100644
--- a/spec/helpers/application_helper_spec.rb
+++ b/spec/helpers/application_helper_spec.rb
@@ -54,6 +54,12 @@ describe ApplicationHelper do
         expect(link).to eq("<link rel='preload' href='https://s3cdn.com/assets/application.js' as='script'/>\n<script src='https://s3cdn.com/assets/application.js'></script>")
       end
 
+      it "can fall back to gzip compression" do
+        helper.request.env["HTTP_ACCEPT_ENCODING"] = 'gzip'
+        link = helper.preload_script('application')
+        expect(link).to eq("<link rel='preload' href='https://s3cdn.com/assets/application.gz.js' as='script'/>\n<script src='https://s3cdn.com/assets/application.gz.js'></script>")
+      end
+
       it "gives s3 cdn even if asset host is set" do
         set_cdn_url "https://awesome.com"
         link = helper.preload_script('application')
diff --git a/spec/requests/static_controller_spec.rb b/spec/requests/static_controller_spec.rb
index 8e4e10d..6fcb784 100644
--- a/spec/requests/static_controller_spec.rb
+++ b/spec/requests/static_controller_spec.rb
@@ -120,6 +120,28 @@ describe StaticController do
     end
   end
 
+  context '#cdn_asset' do
+    let (:site) { RailsMultisite::ConnectionManagement.current_db }
+
+    it 'can serve assets' do
+      begin
+        assets_path = Rails.root.join("public/assets")
+
+        FileUtils.mkdir_p(assets_path)
+
+        file_path = assets_path.join("test.js.br")
+        File.write(file_path, 'fake brotli file')
+
+        get "/cdn_asset/#{site}/test.js.br"
+
+        expect(response.status).to eq(200)
+        expect(response.headers["Cache-Control"]).to match(/public/)
+      ensure
+        File.delete(file_path)
+      end
+    end
+  end
+
   context '#show' do
     before do
       post = create_post

GitHub sha: eff1c19e

1 Like