foalfetch/app/controllers/images_controller.rb

40 lines
1,013 B
Ruby
Raw Normal View History

2024-04-04 10:21:23 +02:00
# frozen_string_literal: true
require 'open-uri'
# Handles proxying images from the FiMFiction CDN and caching them locally, in case they disappear.
class ImagesController < ApplicationController
2024-04-04 10:21:23 +02:00
# noinspection RubyMismatchedArgumentType
def show
url = params[:url]
parsed = URI.parse(url)
if parsed.host != 'cdn-img.fimfiction.net'
render nothing: true, status: :bad_request
return
end
ext = File.extname(url)
hash = Digest::SHA256.hexdigest(url)
path = Rails.root.join('public', 'cached-images', hash + ext)
2024-04-04 10:21:23 +02:00
our_url = "/cached-images/#{hash}#{ext}"
content_type = nil
if File.exist? path
content_type = Marcel::MimeType.for Pathname.new(path)
else
content_type, body = fetch_image uri
File.binwrite path, body
end
send_file path, disposition: :inline, content_type: content_type
end
private
def fetch_image(uri)
response = Net::HTTP.get_response(uri)
[response['Content-Type'], response.body]
end
end