Reviewed-on: #402 Co-authored-by: miteruzo <miteruzo@naver.com> Co-committed-by: miteruzo <miteruzo@naver.com>
このコミットはPull リクエスト #402 でマージされました.
このコミットが含まれているのは:
@@ -0,0 +1,21 @@
|
||||
module Preview
|
||||
class HtmlMetadataExtractor
|
||||
IMAGE_SELECTORS = [
|
||||
'meta[property="og:image"]',
|
||||
'meta[name="twitter:image"]',
|
||||
'meta[name="thumbnail"]'
|
||||
].freeze
|
||||
|
||||
def self.extract(response)
|
||||
document = Nokogiri::HTML.parse(response.body)
|
||||
image_url = IMAGE_SELECTORS.filter_map {
|
||||
document.at_css(_1)&.[]('content')&.strip.presence
|
||||
}.first
|
||||
|
||||
{ title: document.at_css('title')&.text&.strip,
|
||||
image_url: image_url ? URI.join(response.url, image_url).to_s : nil }
|
||||
rescue URI::InvalidURIError
|
||||
{ title: document.at_css('title')&.text&.strip, image_url: nil }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,122 @@
|
||||
require 'net/http'
|
||||
require 'json'
|
||||
|
||||
module Preview
|
||||
class HttpFetcher
|
||||
class FetchFailed < StandardError; end
|
||||
class FetchTimeout < FetchFailed; end
|
||||
class ResponseTooLarge < FetchFailed; end
|
||||
|
||||
MAX_REDIRECTS = 5
|
||||
DEFAULT_MAX_BYTES = 5.megabytes
|
||||
|
||||
Response = Data.define(:body, :content_type, :url)
|
||||
|
||||
def self.fetch(raw_url, max_bytes: DEFAULT_MAX_BYTES, redirects: MAX_REDIRECTS)
|
||||
uri, addresses = UrlSafety.validate(raw_url)
|
||||
response = request(uri, addresses.first, max_bytes)
|
||||
|
||||
if response.is_a?(Net::HTTPRedirection)
|
||||
location = response['location']
|
||||
if redirects.zero?
|
||||
log_failure(:redirect_limit,
|
||||
url: uri.to_s,
|
||||
redirects:,
|
||||
location:,
|
||||
content_type: response['content-type'],
|
||||
content_length: response['content-length'])
|
||||
raise FetchFailed, 'redirect が多すぎます.'
|
||||
end
|
||||
|
||||
if location.blank?
|
||||
log_failure(:blank_redirect_location,
|
||||
url: uri.to_s,
|
||||
redirects:,
|
||||
content_type: response['content-type'],
|
||||
content_length: response['content-length'])
|
||||
raise FetchFailed, 'redirect 先が不正です.'
|
||||
end
|
||||
|
||||
redirect_url =
|
||||
begin
|
||||
URI.join(uri, location).to_s
|
||||
rescue URI::InvalidURIError => e
|
||||
log_failure(:invalid_redirect_location,
|
||||
url: uri.to_s,
|
||||
redirects:,
|
||||
location:,
|
||||
error: e.class.name,
|
||||
message: e.message)
|
||||
raise FetchFailed, 'redirect 先が不正です.'
|
||||
end
|
||||
|
||||
return fetch(redirect_url, max_bytes:, redirects: redirects - 1)
|
||||
end
|
||||
|
||||
unless response.is_a?(Net::HTTPSuccess)
|
||||
log_failure(:http_status,
|
||||
url: uri.to_s,
|
||||
code: response.code,
|
||||
content_type: response['content-type'],
|
||||
content_length: response['content-length'])
|
||||
raise FetchFailed, "外部サーバーが HTTP #{ response.code } を返しました."
|
||||
end
|
||||
|
||||
Response.new(response.body, response['content-type'].to_s, uri.to_s)
|
||||
rescue Net::OpenTimeout, Net::ReadTimeout, Timeout::Error => e
|
||||
log_failure(:timeout, url: uri&.to_s || raw_url, error: e.class.name, message: e.message)
|
||||
raise FetchTimeout, e.message
|
||||
rescue SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError => e
|
||||
log_failure(:network_error, url: uri&.to_s || raw_url, error: e.class.name, message: e.message)
|
||||
raise FetchFailed, e.message
|
||||
end
|
||||
|
||||
def self.request(uri, ip_address, max_bytes)
|
||||
http = Net::HTTP.new(uri.host, uri.port)
|
||||
http.ipaddr = ip_address
|
||||
http.use_ssl = uri.scheme == 'https'
|
||||
http.open_timeout = 5
|
||||
http.read_timeout = 8
|
||||
http.write_timeout = 5
|
||||
|
||||
request = Net::HTTP::Get.new(uri)
|
||||
request['User-Agent'] = 'BTRC-Hub thumbnail preview'
|
||||
request['Accept'] = 'text/html,image/*;q=0.9,*/*;q=0.1'
|
||||
|
||||
http.request(request) do |response|
|
||||
length = response['content-length'].to_i
|
||||
if length > max_bytes
|
||||
log_failure(:response_too_large,
|
||||
url: uri.to_s,
|
||||
content_type: response['content-type'],
|
||||
content_length: response['content-length'],
|
||||
max_bytes:)
|
||||
raise ResponseTooLarge, '外部データが大きすぎます.'
|
||||
end
|
||||
|
||||
body = +''
|
||||
response.read_body do |chunk|
|
||||
body << chunk
|
||||
next unless body.bytesize > max_bytes
|
||||
|
||||
log_failure(:response_too_large,
|
||||
url: uri.to_s,
|
||||
content_type: response['content-type'],
|
||||
content_length: response['content-length'],
|
||||
bytes_read: body.bytesize,
|
||||
max_bytes:)
|
||||
raise ResponseTooLarge, '外部データが大きすぎます.'
|
||||
end
|
||||
response.instance_variable_set(:@body, body)
|
||||
response.instance_variable_set(:@read, true)
|
||||
return response
|
||||
end
|
||||
end
|
||||
|
||||
def self.log_failure(reason, **payload)
|
||||
Rails.logger.warn("preview_http_fetcher_failure #{ { reason:, **payload }.to_json }")
|
||||
end
|
||||
|
||||
private_class_method :request, :log_failure
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,31 @@
|
||||
module Preview
|
||||
class KnownSiteExtractor
|
||||
def self.thumbnail_url(uri)
|
||||
youtube_thumbnail(uri)
|
||||
end
|
||||
|
||||
def self.niconico_video_id(uri)
|
||||
case uri.host&.downcase
|
||||
when 'www.nicovideo.jp', 'nicovideo.jp'
|
||||
uri.path[%r{\A/watch/(sm\d+)\z}, 1]
|
||||
when 'nico.ms'
|
||||
uri.path[%r{\A/(sm\d+)\z}, 1]
|
||||
end
|
||||
end
|
||||
|
||||
def self.youtube_thumbnail(uri)
|
||||
id =
|
||||
case uri.host&.downcase
|
||||
when 'youtu.be'
|
||||
uri.path.split('/').reject(&:blank?).first
|
||||
when 'www.youtube.com', 'youtube.com', 'm.youtube.com'
|
||||
uri.path == '/watch' ? URI.decode_www_form(uri.query.to_s).to_h['v'] : nil
|
||||
end
|
||||
return unless id&.match?(/\A[A-Za-z0-9_-]{6,20}\z/)
|
||||
|
||||
"https://i.ytimg.com/vi/#{ id }/hqdefault.jpg"
|
||||
end
|
||||
|
||||
private_class_method :youtube_thumbnail
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,95 @@
|
||||
module Preview
|
||||
class ThumbnailFetcher
|
||||
class GenerationFailed < StandardError; end
|
||||
ALLOWED_IMAGE_CONTENT_TYPES = [
|
||||
'image/jpeg', 'image/png', 'image/gif', 'image/webp'
|
||||
].freeze
|
||||
HTML_MAX_BYTES = 1.megabyte
|
||||
NICONICO_XML_MAX_BYTES = 256.kilobytes
|
||||
|
||||
def self.fetch(raw_url)
|
||||
uri, = UrlSafety.validate(raw_url)
|
||||
|
||||
known_url = KnownSiteExtractor.thumbnail_url(uri)
|
||||
image = fetch_image_or_nil(known_url) if known_url
|
||||
return image if image
|
||||
|
||||
niconico_url = niconico_thumbnail_url(uri)
|
||||
image = fetch_image_or_nil(niconico_url) if niconico_url
|
||||
return image if image
|
||||
|
||||
page = HttpFetcher.fetch(uri.to_s, max_bytes: HTML_MAX_BYTES)
|
||||
metadata = HtmlMetadataExtractor.extract(page)
|
||||
raise GenerationFailed, 'サムネール画像が見つかりませんでした.' if metadata[:image_url].blank?
|
||||
|
||||
fetch_image!(metadata[:image_url])
|
||||
end
|
||||
|
||||
def self.title(raw_url)
|
||||
uri, = UrlSafety.validate(raw_url)
|
||||
HtmlMetadataExtractor.extract(
|
||||
HttpFetcher.fetch(uri.to_s, max_bytes: HTML_MAX_BYTES))[:title]
|
||||
end
|
||||
|
||||
def self.fetch_image_or_nil(url)
|
||||
return nil if url.blank?
|
||||
|
||||
response = HttpFetcher.fetch(url)
|
||||
return nil unless allowed_image_content_type?(response.content_type)
|
||||
|
||||
response.body
|
||||
rescue HttpFetcher::FetchTimeout
|
||||
raise
|
||||
rescue HttpFetcher::FetchFailed
|
||||
nil
|
||||
end
|
||||
|
||||
def self.fetch_image!(url)
|
||||
response = HttpFetcher.fetch(url)
|
||||
unless allowed_image_content_type?(response.content_type)
|
||||
raise GenerationFailed, 'サムネール画像が見つかりませんでした.'
|
||||
end
|
||||
|
||||
response.body
|
||||
rescue HttpFetcher::FetchTimeout
|
||||
raise
|
||||
rescue HttpFetcher::ResponseTooLarge
|
||||
raise
|
||||
rescue HttpFetcher::FetchFailed
|
||||
raise GenerationFailed, 'サムネール画像を取得できませんでした.'
|
||||
end
|
||||
|
||||
def self.niconico_thumbnail_url(uri)
|
||||
video_id = KnownSiteExtractor.niconico_video_id(uri)
|
||||
return nil if video_id.blank?
|
||||
|
||||
response = HttpFetcher.fetch("https://ext.nicovideo.jp/api/getthumbinfo/#{ video_id }",
|
||||
max_bytes: NICONICO_XML_MAX_BYTES)
|
||||
xml = Nokogiri::XML(response.body)
|
||||
return nil unless xml.at_xpath('/nicovideo_thumb_response/@status')&.value == 'ok'
|
||||
|
||||
xml.at_xpath('//thumbnail_url')&.text&.strip.presence
|
||||
rescue HttpFetcher::FetchFailed, HttpFetcher::FetchTimeout => e
|
||||
Rails.logger.info("preview_niconico_getthumbinfo_fallback #{ { url: uri.to_s,
|
||||
video_id:,
|
||||
error: e.class.name,
|
||||
message: e.message }.to_json }")
|
||||
nil
|
||||
rescue Nokogiri::XML::SyntaxError => e
|
||||
Rails.logger.info("preview_niconico_getthumbinfo_fallback #{ { url: uri.to_s,
|
||||
video_id:,
|
||||
error: e.class.name,
|
||||
message: e.message }.to_json }")
|
||||
nil
|
||||
end
|
||||
|
||||
def self.allowed_image_content_type?(content_type)
|
||||
mime_type = content_type.to_s.split(';', 2).first.downcase.strip
|
||||
ALLOWED_IMAGE_CONTENT_TYPES.include?(mime_type)
|
||||
end
|
||||
|
||||
private_class_method :fetch_image_or_nil, :fetch_image!,
|
||||
:niconico_thumbnail_url,
|
||||
:allowed_image_content_type?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,55 @@
|
||||
require 'resolv'
|
||||
require 'ipaddr'
|
||||
require 'uri'
|
||||
|
||||
module Preview
|
||||
class UrlSafety
|
||||
class UnsafeUrl < StandardError; end
|
||||
|
||||
FORBIDDEN_NETWORKS = [
|
||||
'0.0.0.0/8', '10.0.0.0/8', '100.64.0.0/10', '127.0.0.0/8',
|
||||
'169.254.0.0/16', '172.16.0.0/12', '192.0.0.0/24',
|
||||
'192.0.2.0/24', '192.168.0.0/16', '198.18.0.0/15',
|
||||
'198.51.100.0/24', '203.0.113.0/24', '224.0.0.0/4',
|
||||
'240.0.0.0/4', '::/128', '::1/128', 'fc00::/7', 'fe80::/10',
|
||||
'ff00::/8', '2001:db8::/32', '::ffff:0:0/96'
|
||||
].map { IPAddr.new(_1) }.freeze
|
||||
|
||||
def self.validate(raw_url)
|
||||
value = raw_url.to_s.strip
|
||||
if value.match?(/\A[a-z][a-z0-9+\-.]*:/i)
|
||||
unless value.match?(/\Ahttps?:\/\//i)
|
||||
raise UnsafeUrl, 'http または https の URL を指定してください.'
|
||||
end
|
||||
else
|
||||
value = "http://#{ value }"
|
||||
end
|
||||
uri = URI.parse(value)
|
||||
|
||||
unless ['http', 'https'].include?(uri.scheme&.downcase) && uri.host.present?
|
||||
raise UnsafeUrl, 'http または https の URL を指定してください.'
|
||||
end
|
||||
raise UnsafeUrl, 'userinfo つき URL は使用できません.' if uri.userinfo.present?
|
||||
|
||||
addresses = Resolv.getaddresses(uri.host)
|
||||
raise UnsafeUrl, 'URL のホストを解決できません.' if addresses.empty?
|
||||
|
||||
parsed_addresses = addresses.map { IPAddr.new(_1) }
|
||||
if parsed_addresses.any? { |address| forbidden?(address) }
|
||||
raise UnsafeUrl, '安全でない接続先は使用できません.'
|
||||
end
|
||||
|
||||
[uri, parsed_addresses.map(&:to_s)]
|
||||
rescue Resolv::ResolvError
|
||||
raise UnsafeUrl, 'URL のホストを解決できません.'
|
||||
rescue URI::InvalidURIError, IPAddr::InvalidAddressError
|
||||
raise UnsafeUrl, 'URL が不正です.'
|
||||
end
|
||||
|
||||
def self.forbidden?(address)
|
||||
FORBIDDEN_NETWORKS.any? { _1.include?(address) }
|
||||
end
|
||||
|
||||
private_class_method :forbidden?
|
||||
end
|
||||
end
|
||||
新しい課題から参照
ユーザをブロックする