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