diff --git a/Gemfile b/Gemfile index e829a60..868ef54 100644 --- a/Gemfile +++ b/Gemfile @@ -25,6 +25,9 @@ gem 'model-msearch' gem 'puma', '~> 5.0' gem 'sidekiq' +# Other stuff +gem 'marcel' + # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: %i[ mingw mswin x64_mingw jruby ] diff --git a/Gemfile.lock b/Gemfile.lock index b1af439..6588638 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -306,6 +306,7 @@ DEPENDENCIES elasticsearch-model fancy_searchable! kaminari + marcel model-msearch pg (~> 1.1) puma (~> 5.0) diff --git a/app/controllers/images_controller.rb b/app/controllers/images_controller.rb index 32e22b2..308f772 100644 --- a/app/controllers/images_controller.rb +++ b/app/controllers/images_controller.rb @@ -17,17 +17,23 @@ class ImagesController < ApplicationController hash = Digest::SHA256.hexdigest(url) path = Rails.root.join('public', 'cached-images', hash + ext) our_url = "/cached-images/#{hash}#{ext}" + content_type = nil if File.exist? path - redirect_to our_url - return + content_type = Marcel::MimeType.for Pathname.new(path) + else + content_type, body = fetch_image uri + File.binwrite path, body end - File.binwrite( - path, - Net::HTTP.get(parsed) - ) + send_file path, disposition: :inline, content_type: content_type + end - redirect_to our_url + private + + def fetch_image(uri) + response = Net::HTTP.get_response(uri) + + [response['Content-Type'], response.body] end end