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