<commit_before># frozen_string_literal: true

class FetchLinkCardService < BaseService
  USER_AGENT = "#{HTTP::Request::USER_AGENT} (Mastodon/#{Mastodon::VERSION}; +http://#{Rails.configuration.x.local_domain}/)"

  def call(status)
    # Get first http/https URL that isn't local
    url = URI.extract(status.text).reject { |uri| (uri =~ /\Ahttps?:\/\//).nil? || TagManager.instance.local_url?(uri) }.first

    return if url.nil?

    response = http_client.get(url)

    return if response.code != 200 || response.mime_type != 'text/html'

    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')

    return if card.title.blank?

    card.save_with_optional_image!
  end

  private

  def http_client
    HTTP.headers(user_agent: USER_AGENT).timeout(:per_operation, write: 10, connect: 10, read: 10).follow<commit_msg>Show multibyte URI preview card (#2363)<commit_after># frozen_string_literal: true

class FetchLinkCardService < BaseService
  URL_PATTERN = %r{https?://\S+}
  USER_AGENT = "#{HTTP::Request::USER_AGENT} (Mastodon/#{Mastodon::VERSION}; +http://#{Rails.configuration.x.local_domain}/)"

  def call(status)
    # Get first http/https URL that isn't local
    url = status.text.match(URL_PATTERN).to_a.reject { |uri| TagManager.instance.local_url?(uri) }.first

    return if url.nil?

    response = http_client.get(url)

    return if response.code != 200 || response.mime_type != 'text/html'

    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')

    return if card.title.blank?

    card.save_with_optional_image!
  end

  private

  def http_client
    HTTP.headers(user_agent: USER_AGENT).timeout(:per_operation, write: 10, connect: 10, read: 10).follow
{'fraction_non_alphanumeric': 0.14687629292511378, 'fraction_numerical': 0.009102192800992967, 'mean_word_length': 4.409395973154362, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1674719', 'n_tokens_mistral': 849, 'n_tokens_neox': 796, 'n_words': 156}