Module: RetrieveTitle

Defined in:
lib/retrieve_title.rb

Constant Summary collapse

CRAWL_TIMEOUT =
1
UNRECOVERABLE_ERRORS =
[
  Net::ReadTimeout,
  FinalDestination::SSRFError,
  FinalDestination::UrlEncodingError,
]

Class Method Summary collapse

Class Method Details

.crawl(url, max_redirects: nil, initial_https_redirect_ignore_limit: false) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/retrieve_title.rb', line 11

def self.crawl(url, max_redirects: nil, initial_https_redirect_ignore_limit: false)
  fetch_title(
    url,
    max_redirects: max_redirects,
    initial_https_redirect_ignore_limit: initial_https_redirect_ignore_limit,
  )
rescue *UNRECOVERABLE_ERRORS
  # ¯\_(ツ)_/¯
end

.extract_title(html, encoding = nil) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/retrieve_title.rb', line 21

def self.extract_title(html, encoding = nil)
  title = nil
  return nil if html =~ /<title>/ && html !~ %r{</title>}

  doc = nil
  begin
    doc = Nokogiri.HTML5(html, nil, encoding)
  rescue ArgumentError
    # invalid HTML (Eg: too many attributes, status tree too deep) - ignore
    # Error in nokogumbo is not specialized, uses generic ArgumentError
    # see: https://www.rubydoc.info/gems/nokogiri/Nokogiri/HTML5#label-Error+reporting
  end

  if doc
    title = doc.at("title")&.inner_text

    # A horrible hack - YouTube uses `document.title` to populate the title
    # for some reason. For any other site than YouTube this wouldn't be worth it.
    if title == "YouTube" && html =~ /document\.title *= *"(.*)";/
      title = Regexp.last_match[1].sub(/ - YouTube\z/, "")
    end

    if !title && node = doc.at('meta[property="og:title"]')
      title = node["content"]
    end
  end

  if title.present?
    title.gsub!(/\n/, " ")
    title.gsub!(/ +/, " ")
    title.strip!
    return title
  end
  nil
end