2017-01-20 00:00:14 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class FetchLinkCardService < BaseService
|
2017-04-23 18:08:59 +01:00
|
|
|
URL_PATTERN = %r{https?://\S+}
|
2017-04-21 16:26:23 +01:00
|
|
|
USER_AGENT = "#{HTTP::Request::USER_AGENT} (Mastodon/#{Mastodon::VERSION}; +http://#{Rails.configuration.x.local_domain}/)"
|
2017-04-18 15:04:13 +01:00
|
|
|
|
2017-01-20 00:00:14 +00:00
|
|
|
def call(status)
|
2017-01-27 15:55:06 +00:00
|
|
|
# Get first http/https URL that isn't local
|
2017-04-23 18:08:59 +01:00
|
|
|
url = status.text.match(URL_PATTERN).to_a.reject { |uri| TagManager.instance.local_url?(uri) }.first
|
2017-01-20 00:00:14 +00:00
|
|
|
|
|
|
|
return if url.nil?
|
|
|
|
|
|
|
|
response = http_client.get(url)
|
|
|
|
|
2017-01-24 23:49:08 +00:00
|
|
|
return if response.code != 200 || response.mime_type != 'text/html'
|
2017-01-20 00:00:14 +00: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-24 23:49:08 +00:00
|
|
|
return if card.title.blank?
|
|
|
|
|
2017-01-20 00:00:14 +00:00
|
|
|
card.save_with_optional_image!
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def http_client
|
2017-04-18 15:04:13 +01:00
|
|
|
HTTP.headers(user_agent: USER_AGENT).timeout(:per_operation, write: 10, connect: 10, read: 10).follow
|
2017-01-20 00:00:14 +00: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
|