Files
btrc-hub/backend/app/controllers/preview_controller.rb
2026-05-26 05:52:09 +09:00

48 lines
1.5 KiB
Ruby

class PreviewController < ApplicationController
def title
# TODO: # 既知サイトなら決まったフォーマットで title 取得するやぅに.
return head :unauthorized unless current_user
url = params[:url]
return render_bad_request('URL は必須です.', field: :url) unless url.present?
unless url.start_with?(/http(s)?:\/\//)
url = 'http://' + url
end
html = URI.open(url, open_timeout: 5, read_timeout: 5).read
doc = Nokogiri::HTML.parse(html)
title = doc.at('title')&.text&.strip
render json: { title: title }
rescue => e
render_bad_request(e.message, field: :url)
end
def thumbnail
# TODO: 既知ドメインであれば指定のアドレスからサムネールを取得するやぅにする.
return head :unauthorized unless current_user
url = params[:url]
return render_bad_request('URL は必須です.', field: :url) if url.blank?
unless url.start_with?(/http(s)?:\/\//)
url = 'http://' + url
end
path = Rails.root.join('tmp', "thumb_#{ SecureRandom.hex }.png")
system("node #{ Rails.root }/lib/screenshot.js #{ Shellwords.escape(url) } #{ path }")
if File.exist?(path)
image = MiniMagick::Image.open(path)
image.resize '180x180'
File.delete(path) rescue nil
send_file image.path, type: 'image/png', disposition: 'inline'
else
render_error(:internal_server_error, 'サムネールを生成できませんでした.',
code: :thumbnail_generation_failed)
end
end
end