2017-01-20 09:00:14 +09:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class FetchLinkCardService < BaseService
|
2017-04-24 02:08:59 +09:00
|
|
|
URL_PATTERN = %r{https?://\S+}
|
2017-04-22 00:26:23 +09:00
|
|
|
USER_AGENT = "#{HTTP::Request::USER_AGENT} (Mastodon/#{Mastodon::VERSION}; +http://#{Rails.configuration.x.local_domain}/)"
|
2017-04-18 23:04:13 +09:00
|
|
|
|
2017-01-20 09:00:14 +09:00
|
|
|
def call(status)
|
2017-01-28 00:55:06 +09:00
|
|
|
# Get first http/https URL that isn't local
|
2017-04-24 02:08:59 +09:00
|
|
|
url = status.text.match(URL_PATTERN).to_a.reject { |uri| TagManager.instance.local_url?(uri) }.first
|
2017-01-20 09:00:14 +09:00
|
|
|
|
|
|
|
return if url.nil?
|
|
|
|
|
|
|
|
response = http_client.get(url)
|
|
|
|
|
2017-01-25 08:49:08 +09:00
|
|
|
return if response.code != 200 || response.mime_type != 'text/html'
|
2017-01-20 09:00:14 +09:00
|
|
|
|
|
|
|
page = Nokogiri::HTML(response.to_s)
|
|
|
|
card = PreviewCard.where(status: status).first_or_initialize(status: status, url: url)
|
|
|
|
|
|
|
|
card.title = meta_property(page, 'og:title') || page.at_xpath('//title')&.content
|
|
|
|
card.description = meta_property(page, 'og:description') || meta_property(page, 'description')
|
|
|
|
card.image = URI.parse(meta_property(page, 'og:image')) if meta_property(page, 'og:image')
|
|
|
|
|
2017-01-25 08:49:08 +09:00
|
|
|
return if card.title.blank?
|
|
|
|
|
2017-01-20 09:00:14 +09:00
|
|
|
card.save_with_optional_image!
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def http_client
|
2017-04-18 23:04:13 +09:00
|
|
|
HTTP.headers(user_agent: USER_AGENT).timeout(:per_operation, write: 10, connect: 10, read: 10).follow
|
2017-01-20 09:00:14 +09:00
|
|
|
end
|
|
|
|
|
|
|
|
def meta_property(html, property)
|
|
|
|
html.at_xpath("//meta[@property=\"#{property}\"]")&.attribute('content')&.value || html.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
|
|
|
|
end
|
|
|
|
end
|